@adminide-stack/yantra-mobile 12.0.172-alpha.0 → 12.0.172-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.
Files changed (63) hide show
  1. package/lib/components/GatewayConnector/GatewayConnector.js +10 -4
  2. package/lib/components/GatewayConnector/GatewayConnector.js.map +1 -1
  3. package/lib/components/GatewayConnector/GatewayStatusSheet.js +174 -0
  4. package/lib/components/GatewayConnector/GatewayStatusSheet.js.map +1 -0
  5. package/lib/components/GatewayToolbarButtonMobile.js +6 -2
  6. package/lib/components/GatewayToolbarButtonMobile.js.map +1 -1
  7. package/lib/config/env-config.js +12 -3
  8. package/lib/config/env-config.js.map +1 -1
  9. package/lib/features/apps/nativeAppHandoff.js +31 -13
  10. package/lib/features/apps/nativeAppHandoff.js.map +1 -1
  11. package/lib/features/chat/PromptFillBar.js +153 -0
  12. package/lib/features/chat/PromptFillBar.js.map +1 -0
  13. package/lib/features/chat/promptBlanks.js +120 -0
  14. package/lib/features/chat/promptBlanks.js.map +1 -0
  15. package/lib/features/chat/savedReply.js +11 -0
  16. package/lib/features/chat/savedReply.js.map +1 -0
  17. package/lib/features/games/GameInviteCard.js +93 -0
  18. package/lib/features/games/GameInviteCard.js.map +1 -0
  19. package/lib/features/games/cubeforge3D.js +75 -4
  20. package/lib/features/games/cubeforge3D.js.map +1 -1
  21. package/lib/features/games/cubeforgeFriends.js +112 -0
  22. package/lib/features/games/cubeforgeFriends.js.map +1 -0
  23. package/lib/features/games/gameInvite.js +13 -0
  24. package/lib/features/games/gameInvite.js.map +1 -0
  25. package/lib/features/games/useCubeforgeFriends.js +63 -0
  26. package/lib/features/games/useCubeforgeFriends.js.map +1 -0
  27. package/lib/features/games/vendored/core/cubeforge/nativeWorlds.js +68 -0
  28. package/lib/features/games/vendored/core/cubeforge/nativeWorlds.js.map +1 -0
  29. package/lib/features/games/vendored/core/cubeforge/sharedWorlds.js +10 -0
  30. package/lib/features/games/vendored/core/cubeforge/sharedWorlds.js.map +1 -0
  31. package/lib/features/games/vendored/ui/GamesRoot.js +69 -5
  32. package/lib/features/games/vendored/ui/GamesRoot.js.map +1 -1
  33. package/lib/features/games/vendored/ui/screens/Cubeforge3DHomeScreen.js +296 -0
  34. package/lib/features/games/vendored/ui/screens/Cubeforge3DHomeScreen.js.map +1 -0
  35. package/lib/features/games/vendored/ui/screens/CubeforgeScreen.js +1 -1
  36. package/lib/features/games/vendored/ui/screens/CubeforgeScreen.js.map +1 -1
  37. package/lib/features/messaging/ChatComponents.js +12 -4
  38. package/lib/features/messaging/ChatComponents.js.map +1 -1
  39. package/lib/features/messaging/messageCards.js +22 -0
  40. package/lib/features/messaging/messageCards.js.map +1 -0
  41. package/lib/features/travel/TravelAgentChatPane.js +9 -1
  42. package/lib/features/travel/TravelAgentChatPane.js.map +1 -1
  43. package/lib/hooks/useCdecliAutoConnect.js +8 -1
  44. package/lib/hooks/useCdecliAutoConnect.js.map +1 -1
  45. package/lib/hooks/useCdecliChannel.js +142 -49
  46. package/lib/hooks/useCdecliChannel.js.map +1 -1
  47. package/lib/hooks/useChatApi.js +21 -10
  48. package/lib/hooks/useChatApi.js.map +1 -1
  49. package/lib/hooks/useChatStream.js +18 -5
  50. package/lib/hooks/useChatStream.js.map +1 -1
  51. package/lib/module.js +2 -1
  52. package/lib/module.js.map +1 -1
  53. package/lib/screens/Chat/index.js +23 -15
  54. package/lib/screens/Chat/index.js.map +1 -1
  55. package/lib/screens/GamesNative/index.js +48 -3
  56. package/lib/screens/GamesNative/index.js.map +1 -1
  57. package/lib/screens/Home/HomeScreen.js +147 -33
  58. package/lib/screens/Home/HomeScreen.js.map +1 -1
  59. package/lib/screens/Home/components/HomeSuggestions.js +1 -1
  60. package/lib/screens/Home/components/HomeSuggestions.js.map +1 -1
  61. package/lib/screens/Home/components/homeCatalog.js +68 -16
  62. package/lib/screens/Home/components/homeCatalog.js.map +1 -1
  63. package/package.json +2 -2
@@ -1,4 +1,4 @@
1
- import {useState,useRef,useCallback,useEffect,useMemo,useSyncExternalStore}from'react';import {Platform}from'react-native';import {useCreateAccountChatFileUploadLinksMutation,useCreateAccountChatFileDownloadLinksMutation}from'common/graphql';import {markChannelHistoryRunning,useChatMutations,useChatMessages,clearChannelHistoryRunning,patchChannelHistoryPreview}from'./useChatApi.js';import {useCdecliChannel}from'./useCdecliChannel.js';import {useChatModelId,chatModelForRequest}from'../features/chat/chatModelPick.js';import {usePrerequisiteIds}from'./usePrerequisiteIds.js';import {isAgentJwtRejected,shouldInlineGatewayMediaForHostedAgent}from'./systemTokenJwt.js';import {config}from'../config/env-config.js';import {queueGatewayMessage,MAX_QUEUED_MESSAGES,dropQueuedGatewayMessage,queuedGatewayMessages,subscribeQueuedGatewayMessages,restoreQueuedGatewayMessages,isQueuedMessageDelivered,clearQueuedGatewayMessages}from'../services/queuedGatewayMessages.js';import {isImageAttachment}from'../features/attachments/isImageAttachment.js';import {buildGatewayMedia,buildGatewayMediaPreferUrls}from'../features/attachments/buildGatewayMedia.js';import {preserveAttachmentPreviews}from'../features/attachments/preserveAttachmentPreviews.js';import {releasePreviewBytes}from'../features/attachments/releasePreviewBytes.js';import {resolveAssistantReply}from'../features/chat/emptyChatResponse.js';import {splitPreResponse}from'../features/chat/preResponse.js';import {appendOrReplaceAssistant,appendFollowUpAssistant,mergeOptimisticGatewayMessages,collapseConsecutiveAssistants}from'../state/chatThreadMerge.js';var __defProp = Object.defineProperty;
1
+ import {useState,useRef,useCallback,useEffect,useMemo,useSyncExternalStore}from'react';import {Platform}from'react-native';import {useCreateAccountChatFileUploadLinksMutation,useCreateAccountChatFileDownloadLinksMutation}from'common/graphql';import {markChannelHistoryRunning,useChatMutations,useChatMessages,clearChannelHistoryRunning,patchChannelHistoryPreview}from'./useChatApi.js';import {useCdecliChannel}from'./useCdecliChannel.js';import {useChatModelId,chatModelForRequest}from'../features/chat/chatModelPick.js';import {usePrerequisiteIds}from'./usePrerequisiteIds.js';import {isAgentJwtRejected,shouldInlineGatewayMediaForHostedAgent}from'./systemTokenJwt.js';import {config}from'../config/env-config.js';import {queueGatewayMessage,MAX_QUEUED_MESSAGES,dropQueuedGatewayMessage,queuedGatewayMessages,subscribeQueuedGatewayMessages,restoreQueuedGatewayMessages,isQueuedMessageDelivered,clearQueuedGatewayMessages}from'../services/queuedGatewayMessages.js';import {isImageAttachment}from'../features/attachments/isImageAttachment.js';import {buildGatewayMedia,buildGatewayMediaPreferUrls}from'../features/attachments/buildGatewayMedia.js';import {preserveAttachmentPreviews}from'../features/attachments/preserveAttachmentPreviews.js';import {releasePreviewBytes}from'../features/attachments/releasePreviewBytes.js';import {resolveAssistantReply}from'../features/chat/emptyChatResponse.js';import {splitPreResponse}from'../features/chat/preResponse.js';import {seenRowIds,savedReplyFor}from'../features/chat/savedReply.js';import {appendOrReplaceAssistant,appendFollowUpAssistant,mergeOptimisticGatewayMessages,collapseConsecutiveAssistants}from'../state/chatThreadMerge.js';var __defProp = Object.defineProperty;
2
2
  var __defProps = Object.defineProperties;
3
3
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
4
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
@@ -123,8 +123,18 @@ function useChatStream(sessionId, routing = {
123
123
  const {
124
124
  messages: backendMessages,
125
125
  loading: backendMessagesLoading,
126
- messagesLoaded: backendMessagesLoaded
126
+ messagesLoaded: backendMessagesLoaded,
127
+ fetchThread
127
128
  } = useChatMessages(sessionId);
129
+ const backendMessagesRef = useRef(backendMessages);
130
+ backendMessagesRef.current = backendMessages;
131
+ const fetchThreadRef = useRef(fetchThread);
132
+ fetchThreadRef.current = fetchThread;
133
+ const seenPostIdsRef = useRef(/* @__PURE__ */ new Set());
134
+ const markRoundStart = useCallback(() => {
135
+ var _a;
136
+ seenPostIdsRef.current = seenRowIds((_a = backendMessagesRef.current) != null ? _a : []);
137
+ }, []);
128
138
  const lastHydratedSessionIdRef = useRef(null);
129
139
  const ignoreHydrationRef = useRef(false);
130
140
  const streamChannelId = sessionId || cdecliStreamOverrideId;
@@ -154,6 +164,7 @@ function useChatStream(sessionId, routing = {
154
164
  isSendingRef.current = true;
155
165
  followUpRoundRef.current = true;
156
166
  cdecliRoundHandledRef.current = false;
167
+ markRoundStart();
157
168
  saveSessionIdRef.current = sessionIdRef.current;
158
169
  setIsLoading(true);
159
170
  setIsStreaming(true);
@@ -269,8 +280,9 @@ function useChatStream(sessionId, routing = {
269
280
  setError(err || "CDeCLI stream error.");
270
281
  finalizeCdecliRound(resolveAssistantReply(""));
271
282
  })();
272
- }
273
- }), [saveMessages, accountUserId, finalizeCdecliRound, flushPendingStream, clearPendingStream]);
283
+ },
284
+ fetchSavedReply: async () => savedReplyFor(await fetchThreadRef.current(), seenPostIdsRef.current)
285
+ }), [saveMessages, accountUserId, finalizeCdecliRound, flushPendingStream, clearPendingStream, markRoundStart]);
274
286
  const {
275
287
  sendMessage: sendCdecliMessage,
276
288
  sendQueued: sendQueuedCdecli,
@@ -467,6 +479,7 @@ function useChatStream(sessionId, routing = {
467
479
  userMsgForSaveRef.current = userMessage;
468
480
  saveSessionIdRef.current = effectiveSessionId != null ? effectiveSessionId : null;
469
481
  cdecliRoundHandledRef.current = false;
482
+ markRoundStart();
470
483
  if (!effectiveSessionId) {
471
484
  setError("Missing chat session id.");
472
485
  if (!alreadyVisible) setMessages((p) => p.slice(0, -1));
@@ -535,7 +548,7 @@ function useChatStream(sessionId, routing = {
535
548
  }
536
549
  if (ok && queuedId) dropQueuedGatewayMessage(queuedId);
537
550
  return ok ? "sent" : "failed";
538
- }, [sessionId, sendCdecliMessage, patchChannelTitle, sendQueuedCdecli, setQueue, createAccountChatFileUploadLinksMutation, createAccountChatFileDownloadLinksMutation]);
551
+ }, [sessionId, sendCdecliMessage, patchChannelTitle, sendQueuedCdecli, setQueue, createAccountChatFileUploadLinksMutation, createAccountChatFileDownloadLinksMutation, markRoundStart]);
539
552
  sendMessageRef.current = sendMessage;
540
553
  const queuedChannelId = sessionId || cdecliStreamOverrideId || null;
541
554
  const queuedSnapshot = useCallback(() => queuedGatewayMessages(queuedChannelId, routing.accountId), [queuedChannelId, routing.accountId]);
@@ -1 +1 @@
1
- {"version":3,"file":"useChatStream.js","sources":["../../src/hooks/useChatStream.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport { Platform } from 'react-native';\nimport {\n useCreateAccountChatFileDownloadLinksMutation,\n useCreateAccountChatFileUploadLinksMutation,\n} from 'common/graphql';\nimport {\n clearChannelHistoryRunning,\n markChannelHistoryRunning,\n patchChannelHistoryPreview,\n useChatMutations,\n useChatMessages,\n} from './useChatApi';\nimport { useCdecliChannel, type CdecliTurnOptions } from './useCdecliChannel';\nimport { chatModelForRequest, useChatModelId } from '../features/chat/chatModelPick';\nimport { usePrerequisiteIds } from './usePrerequisiteIds';\nimport { isAgentJwtRejected, shouldInlineGatewayMediaForHostedAgent } from './systemTokenJwt';\nimport { config } from '../config';\nimport {\n MAX_QUEUED_MESSAGES,\n clearQueuedGatewayMessages,\n dropQueuedGatewayMessage,\n isQueuedMessageDelivered,\n queueGatewayMessage,\n queuedGatewayMessages,\n restoreQueuedGatewayMessages,\n subscribeQueuedGatewayMessages,\n} from '../services/queuedGatewayMessages';\nimport { isImageAttachment } from '../features/attachments/isImageAttachment';\nimport { buildGatewayMedia, buildGatewayMediaPreferUrls } from '../features/attachments/buildGatewayMedia';\nimport { preserveAttachmentPreviews } from '../features/attachments/preserveAttachmentPreviews';\nimport { releasePreviewBytes } from '../features/attachments/releasePreviewBytes';\nimport { resolveAssistantReply } from '../features/chat/emptyChatResponse';\nimport { splitPreResponse } from '../features/chat/preResponse';\nimport {\n appendFollowUpAssistant,\n appendOrReplaceAssistant,\n collapseConsecutiveAssistants,\n mergeOptimisticGatewayMessages,\n} from '../state/chatThreadMerge';\n\n// Each flush re-parses the whole reply as markdown. Mid-range Android CPUs\n// drop frames at 20 flushes/s; 10/s still reads as live typing.\nconst STREAM_FLUSH_MS = Platform.OS === 'android' ? 100 : 50;\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 isAgentJwtRejected(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/** The queued row renders this turn now, so the optimistic bubble must not stay behind it. */\nfunction withoutTrailingUserMessage(prev: ChatMessage[], text: string): ChatMessage[] {\n const last = prev[prev.length - 1];\n return last?.role === 'user' && last.content === text ? prev.slice(0, -1) : prev;\n}\n\n/** A message the gateway queued for the agent while a turn was running. */\nexport interface QueuedFollowUp {\n /** The gateway's id for it - what cancels it. */\n id: string;\n text: string;\n attachments?: MessageAttachment[];\n}\n\n/** Retries of a turn parked on a live gateway (see `outboxRetrying`). */\nexport const OUTBOX_RETRY_DELAYS_MS = [3_000, 10_000, 30_000] as const;\n\n/** A mid-turn message shows under this id until the gateway gives it one. */\nconst PROVISIONAL_FOLLOW_UP = 'sending-';\nconst isProvisionalFollowUp = (id: string) => id.startsWith(PROVISIONAL_FOLLOW_UP);\n\n/** What became of a send: delivered to the gateway, parked in the outbox, or refused outright. */\nexport type SendOutcome = 'sent' | 'queued' | 'failed';\n\nfunction formatBackendThread(\n backendMessages: Array<{\n role: string;\n content?: string;\n // The generated `ChatMessageUI` types `type` as a plain string; it is narrowed\n // to the UI union in the map below, so take it wide rather than cast at the call.\n attachments?: Array<{ id: string; name: string; type: string; mimeType?: string; size?: number; url?: string }>;\n tokenCount?: number;\n model?: string;\n }>,\n): ChatMessage[] {\n return collapseConsecutiveAssistants(\n backendMessages.map((msg) => ({\n role: msg.role as 'user' | 'assistant',\n content: msg.content ?? '',\n attachments: msg.attachments?.map((a) => ({\n id: a.id,\n name: a.name,\n type: a.type === 'screenshot' ? 'screenshot' : 'file',\n mimeType: a.mimeType,\n size: a.size,\n url: a.url,\n })),\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 );\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 /** Remint the system JWT and reconnect after cdecli-agent 401s the session. */\n recoverAgentAuth?: () => Promise<boolean>;\n /** Agent skill every turn on this stream carries (`metadata.skill`), e.g. Web Builder's. */\n skill?: string;\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 /** Brain assist — never the published agent stream. Shown as a Quick answer strip. */\n const [quickReply, setQuickReply] = 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 * Messages sent while a turn was running, which the gateway queued for the\n * agent. Shown above the composer until the agent starts on them (the way\n * Claude Code shows a message typed mid-turn), then moved into the thread.\n * Kept out of `messages` so a backend hydration cannot drop or double them.\n */\n const [queuedFollowUps, setQueuedFollowUps] = useState<QueuedFollowUp[]>([]);\n const queuedFollowUpsRef = useRef<QueuedFollowUp[]>([]);\n /** Names the row a mid-turn message shows in until the gateway gives it an id. */\n const provisionalSeqRef = useRef(0);\n const sendMessageRef = useRef<\n (\n content: string,\n attachments?: MessageAttachment[],\n sessionIdOverride?: string | null,\n alreadyVisible?: boolean,\n queuedId?: string,\n turnOptions?: CdecliTurnOptions,\n ) => Promise<SendOutcome>\n >(async () => 'failed');\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 const sessionIdRef = useRef<string | null>(sessionId);\n sessionIdRef.current = sessionId || cdecliStreamOverrideId || null;\n /** Blocks duplicate cdecli `onComplete` from appending assistant twice / saving twice per send. */\n const cdecliRoundHandledRef = useRef(false);\n /**\n * The round in flight was opened by the agent, not by a send: a follow-up,\n * e.g. the answer to a request the gateway queued while the agent was busy.\n * It completes as a new bubble instead of replacing the reply before it.\n */\n const followUpRoundRef = useRef(false);\n /** One remint+resend per turn when cdecli-agent 401s the JWT. */\n const authRetryUsedRef = useRef(false);\n const recoveringAuthRef = useRef(false);\n const chatModelId = useChatModelId();\n const routingRef = useRef(routing);\n routingRef.current = routing;\n\n const tryRecoverAndResendRef = useRef<(reason: string) => Promise<boolean>>(async () => false);\n\n /** Coalesce token deltas so Fabric is not committing a native tree every chunk. */\n const pendingStreamRef = useRef('');\n const streamFlushTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const clearPendingStream = useCallback(() => {\n if (streamFlushTimerRef.current != null) {\n clearTimeout(streamFlushTimerRef.current);\n streamFlushTimerRef.current = null;\n }\n pendingStreamRef.current = '';\n }, []);\n\n const flushPendingStream = useCallback(() => {\n streamFlushTimerRef.current = null;\n const pending = pendingStreamRef.current;\n if (!pending) return;\n pendingStreamRef.current = '';\n setResponse((r) => {\n const next = r + pending;\n const sid = sessionIdRef.current;\n if (sid) markChannelHistoryRunning(sid, next);\n return next;\n });\n }, []);\n\n useEffect(() => () => clearPendingStream(), [clearPendingStream]);\n\n /** The live reply, readable from a send (an answer keeps the question it answers). */\n const responseTextRef = useRef('');\n useEffect(() => {\n responseTextRef.current = response;\n }, [response]);\n\n const { saveMessages, patchChannelTitle } = useChatMutations();\n const titlePatchedChannelsRef = useRef(new Set<string>());\n const { accountUserId } = usePrerequisiteIds();\n const [createAccountChatFileUploadLinksMutation] = useCreateAccountChatFileUploadLinksMutation();\n const [createAccountChatFileDownloadLinksMutation] = useCreateAccountChatFileDownloadLinksMutation();\n const {\n messages: backendMessages,\n loading: backendMessagesLoading,\n messagesLoaded: backendMessagesLoaded,\n } = useChatMessages(sessionId);\n const lastHydratedSessionIdRef = useRef<string | null>(null);\n /** Trash-clear: do not re-hydrate gateway history until the next send. */\n const ignoreHydrationRef = useRef(false);\n\n const streamChannelId = sessionId || cdecliStreamOverrideId;\n\n const finalizeCdecliRound = useCallback(\n (assistantContent?: string) => {\n const previewSid = saveSessionIdRef.current || sessionIdRef.current;\n clearPendingStream();\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n followUpRoundRef.current = false;\n setResponse('');\n setQuickReply('');\n setIsLoading(false);\n setIsStreaming(false);\n isSendingRef.current = false;\n if (previewSid) clearChannelHistoryRunning(previewSid);\n if (assistantContent !== undefined) {\n setMessages((prev) =>\n appendOrReplaceAssistant(prev, { role: 'assistant' as const, content: assistantContent }),\n );\n if (previewSid) patchChannelHistoryPreview(previewSid, assistantContent);\n }\n },\n [clearPendingStream],\n );\n\n const cdecliCallbacks = useMemo(\n () => ({\n onChunk: (text: string) => {\n if (!isSendingRef.current) {\n // No send opened this round: the agent is speaking on its own.\n isSendingRef.current = true;\n followUpRoundRef.current = true;\n cdecliRoundHandledRef.current = false;\n saveSessionIdRef.current = sessionIdRef.current;\n setIsLoading(true);\n setIsStreaming(true);\n setError(null);\n const sid = sessionIdRef.current;\n if (sid) markChannelHistoryRunning(sid, text);\n // The agent has started on what was queued: those messages\n // join the thread now, above the answer they are getting.\n const started = queuedFollowUpsRef.current;\n if (started.length > 0) {\n queuedFollowUpsRef.current = [];\n setQueuedFollowUps([]);\n setMessages((prev) => [\n ...prev,\n ...started.map((q) => ({\n role: 'user' as const,\n content: q.text,\n attachments: q.attachments,\n })),\n ]);\n }\n }\n pendingStreamRef.current += text;\n if (streamFlushTimerRef.current == null) {\n streamFlushTimerRef.current = setTimeout(flushPendingStream, STREAM_FLUSH_MS);\n }\n },\n // The brain's provisional answer is the WHOLE reply-so-far, not a chunk:\n // it is set outright, and set to '' when the real stream supersedes it.\n onQuickReply: (text: string) => {\n setQuickReply(text);\n },\n // The gateway's own words on the running work (a status answer, a\n // long-wait report) arrive as thread posts through hydration; the\n // callback only keeps them from ending the reply in progress.\n onNotice: () => undefined,\n onStreamRestart: () => {\n clearPendingStream();\n pendingStreamRef.current = '';\n setResponse('');\n },\n onComplete: (text: string) => {\n clearPendingStream();\n if (cdecliRoundHandledRef.current) {\n return;\n }\n\n // Judge the agent's own words: a quick answer in front of them is\n // not the agent failing, and never belongs in the error banner.\n const agentText = splitPreResponse(text).text;\n if (isCdecliAgentFailureOutput(agentText)) {\n void (async () => {\n if (await tryRecoverAndResendRef.current(agentText)) return;\n if (cdecliRoundHandledRef.current) return;\n cdecliRoundHandledRef.current = true;\n setError(\n isAgentJwtRejected(agentText)\n ? agentText\n : 'CDeCLI agent error. Check gateway status and server-side LLM configuration.',\n );\n finalizeCdecliRound(isAgentJwtRejected(agentText) ? undefined : text);\n })();\n return;\n }\n\n cdecliRoundHandledRef.current = true;\n authRetryUsedRef.current = false;\n\n const reply = resolveAssistantReply(text);\n const sid = saveSessionIdRef.current;\n const um = userMsgForSaveRef.current;\n const followUp = followUpRoundRef.current;\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n followUpRoundRef.current = false;\n\n const assistant = { role: 'assistant' as const, content: reply };\n setMessages((prev) =>\n followUp ? appendFollowUpAssistant(prev, assistant) : appendOrReplaceAssistant(prev, assistant),\n );\n const previewSid = sid || sessionIdRef.current;\n if (previewSid) {\n clearChannelHistoryRunning(previewSid);\n patchChannelHistoryPreview(previewSid, reply);\n }\n setResponse('');\n setQuickReply('');\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: reply,\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 void (async () => {\n if (await tryRecoverAndResendRef.current(err)) return;\n if (cdecliRoundHandledRef.current) return;\n cdecliRoundHandledRef.current = true;\n setError(err || 'CDeCLI stream error.');\n finalizeCdecliRound(resolveAssistantReply(''));\n })();\n },\n }),\n [saveMessages, accountUserId, finalizeCdecliRound, flushPendingStream, clearPendingStream],\n );\n\n const {\n sendMessage: sendCdecliMessage,\n sendQueued: sendQueuedCdecli,\n cancelQueued: cancelQueuedCdecli,\n cancel: cancelCdecliTurn,\n } = useCdecliChannel(\n routing.channelConnected,\n routing.accountId,\n streamChannelId,\n cdecliCallbacks,\n chatModelForRequest(chatModelId),\n routing.skill,\n );\n\n const setQueue = useCallback((next: QueuedFollowUp[]) => {\n queuedFollowUpsRef.current = next;\n setQueuedFollowUps(next);\n }, []);\n\n useEffect(() => {\n if (sessionId && cdecliStreamOverrideId && sessionId === cdecliStreamOverrideId) {\n setCdecliStreamOverrideId(undefined);\n }\n }, [sessionId, cdecliStreamOverrideId]);\n\n useEffect(() => {\n const prevSid = lastHydratedSessionIdRef.current;\n if (prevSid && sessionId && prevSid !== sessionId && isSendingRef.current) {\n // Switching threads: drop local send flags so this view can hydrate.\n // The previous channel's agent keeps running server-side; history still\n // shows it as running until that turn completes or we reopen it.\n clearPendingStream();\n setQueue([]);\n isSendingRef.current = false;\n followUpRoundRef.current = false;\n cdecliRoundHandledRef.current = false;\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n setIsLoading(false);\n setIsStreaming(false);\n setResponse('');\n setQuickReply('');\n }\n\n if (!sessionId) {\n setMessages([]);\n setResponse('');\n setQuickReply('');\n lastHydratedSessionIdRef.current = null;\n return;\n }\n\n const stampHistoryPreview = (msgs: ChatMessage[]) => {\n const last = msgs[msgs.length - 1];\n const lastAssistant = [...msgs].reverse().find((msg) => msg.role === 'assistant' && msg.content.trim());\n if (lastAssistant && !isSendingRef.current) {\n patchChannelHistoryPreview(sessionId, lastAssistant.content);\n }\n // Finished thread (last post is assistant) — drop the history \"Running\" badge.\n // A live turn ends with a user post until the assistant lands.\n if (!isSendingRef.current && last?.role === 'assistant') {\n clearChannelHistoryRunning(sessionId);\n }\n };\n\n if (ignoreHydrationRef.current) {\n return;\n }\n\n const keepStream = isSendingRef.current;\n const sessionChanged = lastHydratedSessionIdRef.current !== sessionId;\n if (sessionChanged) {\n lastHydratedSessionIdRef.current = sessionId;\n // Do not merge the previous channel's in-memory thread into this one.\n if (!backendMessagesLoaded) {\n if (!keepStream) {\n setMessages([]);\n setResponse('');\n setQuickReply('');\n }\n return;\n }\n const formatted = formatBackendThread(backendMessages ?? []);\n stampHistoryPreview(formatted);\n setMessages((prev) => (keepStream ? mergeOptimisticGatewayMessages(prev, formatted) : formatted));\n if (!keepStream) {\n setResponse('');\n setQuickReply('');\n }\n return;\n }\n\n if (backendMessagesLoaded) {\n const formatted = formatBackendThread(backendMessages ?? []);\n stampHistoryPreview(formatted);\n // Positional merge first so assistant replies the gateway never persisted\n // (cdecli skill turns emit no chatMessageAdded) survive this snapshot instead\n // of being dropped, then preserve in-memory attachment previews on the result.\n setMessages((prev) => preserveAttachmentPreviews(prev, mergeOptimisticGatewayMessages(prev, formatted)));\n if (!keepStream) {\n setResponse('');\n setQuickReply('');\n }\n }\n }, [sessionId, backendMessages, backendMessagesLoaded, clearPendingStream, setQueue]);\n\n const sendMessage = useCallback(\n async (\n content: string,\n attachments?: MessageAttachment[],\n sessionIdOverride?: string | null,\n alreadyVisible = false,\n /** Set when this send is the release of an outbox entry; it owns that entry's fate. */\n queuedId: string | undefined = undefined,\n /**\n * Extras for this turn (a surface job the agent settles). Only a turn that\n * starts now carries them: a queued or parked message goes out later without.\n */\n turnOptions: CdecliTurnOptions = {},\n ): Promise<SendOutcome> => {\n if (!content.trim() && !attachments?.length) return 'failed';\n\n const effectiveSessionId = sessionIdOverride !== undefined ? sessionIdOverride : sessionId;\n const rt = routingRef.current;\n const trimmed = content.trim();\n const sendText =\n trimmed ||\n (attachments?.length\n ? `Attached: ${attachments\n .map((a) => a.name)\n .filter(Boolean)\n .join(', ')}`\n : '');\n\n const userMessage: ChatMessage = {\n role: 'user',\n content: sendText,\n attachments,\n };\n\n /**\n * The gateway is down. The turn is remembered, not erased: it stays in the\n * thread as a queued bubble and the outbox releases it in order the moment\n * the channel reports connected. Losing what the user typed here is the\n * whole reason this lane exists.\n */\n if (!rt.channelConnected) {\n if (!effectiveSessionId) {\n setError('Missing chat session id.');\n return 'failed';\n }\n // A release that raced the connection dropping stays where it is.\n if (queuedId) return 'queued';\n const result = queueGatewayMessage({\n channelId: effectiveSessionId,\n accountId: rt.accountId,\n text: sendText,\n attachments,\n });\n if (!result.ok) {\n setError(\n result.reason === 'full'\n ? `${MAX_QUEUED_MESSAGES} messages are already waiting for the gateway. They send as soon as it connects.`\n : 'Nothing to send.',\n );\n return 'failed';\n }\n if (alreadyVisible) setMessages((prev) => withoutTrailingUserMessage(prev, sendText));\n setError(null);\n return 'queued';\n }\n\n /**\n * A turn is already in flight. The gateway queues the message for the\n * agent, which answers it when the running turn ends; the running reply\n * is left alone. It waits above the composer (cancellable) until the\n * agent starts on it. A status question is answered on the spot, and a\n * turn that had already ended takes the message straight away.\n */\n if (isSendingRef.current && !turnOptions.answersAsk) {\n if (!effectiveSessionId) {\n setError('Missing chat session id.');\n return 'failed';\n }\n // Above the composer from the tap, not from the gateway's answer: the\n // provisional row takes the gateway's id once it has one.\n const provisionalId = `${PROVISIONAL_FOLLOW_UP}${(provisionalSeqRef.current += 1)}`;\n const preview = releasePreviewBytes(attachments);\n if (!alreadyVisible) {\n setQueue([\n ...queuedFollowUpsRef.current,\n { id: provisionalId, text: sendText, attachments: preview },\n ]);\n }\n const withoutProvisional = () => queuedFollowUpsRef.current.filter((q) => q.id !== provisionalId);\n const media = attachments?.length ? buildGatewayMedia(attachments, { includeData: true }) : [];\n const outcome = await sendQueuedCdecli(sendText, effectiveSessionId, media);\n if (outcome.status === 'failed') {\n setQueue(withoutProvisional());\n // Keep the words: the outbox holds the turn (and survives a restart)\n // and offers the retry. A release that failed is already in it.\n const parked = queuedId\n ? { ok: true as const }\n : queueGatewayMessage({\n channelId: effectiveSessionId,\n accountId: rt.accountId,\n text: sendText,\n attachments,\n });\n if (parked.ok && alreadyVisible) setMessages((prev) => withoutTrailingUserMessage(prev, sendText));\n // Parked: the outbox notice says so and offers the retry.\n setError(parked.ok ? null : outcome.error || 'Could not send the message. Try again.');\n return parked.ok ? 'queued' : 'failed';\n }\n if (queuedId) dropQueuedGatewayMessage(queuedId);\n setError(null);\n if (outcome.status === 'queued') {\n setQueue(\n alreadyVisible\n ? [...queuedFollowUpsRef.current, { id: outcome.id, text: sendText, attachments: preview }]\n : queuedFollowUpsRef.current.map((q) =>\n q.id === provisionalId ? { ...q, id: outcome.id } : q,\n ),\n );\n if (alreadyVisible) setMessages((prev) => withoutTrailingUserMessage(prev, sendText));\n } else {\n // The running turn had ended: the agent took it straight away.\n setQueue(withoutProvisional());\n if (!alreadyVisible) setMessages((prev) => [...prev, userMessage]);\n }\n return 'sent';\n }\n\n // An answer to a parked question while its turn is still open: the reply so far\n // (the one asking) stays in the thread, and the answer starts the next round.\n if (isSendingRef.current && turnOptions.answersAsk) {\n const asked = responseTextRef.current + pendingStreamRef.current;\n clearPendingStream();\n if (asked.trim()) {\n setMessages((prev) =>\n appendOrReplaceAssistant(prev, { role: 'assistant' as const, content: asked }),\n );\n }\n }\n\n isSendingRef.current = true;\n followUpRoundRef.current = false;\n ignoreHydrationRef.current = false;\n if (effectiveSessionId && sendText) {\n titlePatchedChannelsRef.current.add(effectiveSessionId);\n patchChannelTitle(effectiveSessionId, sendText, true);\n markChannelHistoryRunning(effectiveSessionId);\n }\n if (!alreadyVisible) {\n // The transcript keeps this turn for the rest of the session, so it\n // keeps the preview URI and not the base64 behind it. The bytes stay\n // on `userMsgForSaveRef` below, which is nulled when the turn ends -\n // a retry still has them, a backgrounded app no longer carries them.\n const retained: ChatMessage = {\n ...userMessage,\n attachments: releasePreviewBytes(userMessage.attachments),\n };\n setMessages((prev) => [...prev, retained]);\n authRetryUsedRef.current = false;\n }\n setResponse('');\n setQuickReply('');\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 (!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 'failed';\n }\n\n if (sessionIdOverride) {\n setCdecliStreamOverrideId(sessionIdOverride);\n await new Promise<void>((resolve) => {\n setTimeout(resolve, 0);\n });\n }\n\n const inlineForHostedAgent = shouldInlineGatewayMediaForHostedAgent(\n config.GRAPHQL_URL,\n config.CDECLI_AGENT_ENDPOINT,\n );\n // Vision turns must carry inline bytes. URL-only media is what made\n // \"what is this\" + a photo look like a text-only question.\n const inlineImages = (attachments ?? []).some(isImageAttachment) || inlineForHostedAgent;\n let media = inlineImages\n ? buildGatewayMedia(attachments, { includeData: true })\n : await buildGatewayMediaPreferUrls(\n attachments,\n async (filenames) => {\n const result = await createAccountChatFileUploadLinksMutation({\n variables: { filenames },\n });\n return result.data?.createAccountChatFileUploadLinks || [];\n },\n async (urls) => {\n const result = await createAccountChatFileDownloadLinksMutation({\n variables: { urls },\n });\n return result.data?.createAccountChatFileDownloadLinks || [];\n },\n );\n if ((attachments?.length ?? 0) > 0 && media.length === 0) {\n media = buildGatewayMedia(attachments, { includeData: true });\n }\n const ok = await sendCdecliMessage(sendText, effectiveSessionId, media, turnOptions);\n if (!ok && !cdecliRoundHandledRef.current && !recoveringAuthRef.current) {\n cdecliRoundHandledRef.current = true;\n // The send never reached the agent. Park it rather than drop it - a\n // release keeps its place at the head of its own queue.\n const parked = queuedId\n ? { ok: true as const }\n : queueGatewayMessage({\n channelId: effectiveSessionId,\n accountId: rt.accountId,\n text: sendText,\n attachments,\n });\n // Parked: the outbox notice says so and offers the retry; a second banner\n // saying it again in red read as the message being lost.\n setError(parked.ok ? null : 'Failed to send message via CDeCLI. Check gateway connection.');\n // Queued: the queued row renders the turn, so the optimistic bubble goes.\n // Not queued: only drop a bubble this call put there.\n setMessages((p) => {\n if (parked.ok) return withoutTrailingUserMessage(p, sendText);\n return alreadyVisible ? p : p.slice(0, -1);\n });\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n userMsgForSaveRef.current = null;\n saveSessionIdRef.current = null;\n clearChannelHistoryRunning(effectiveSessionId);\n return parked.ok ? 'queued' : 'failed';\n }\n if (ok && queuedId) dropQueuedGatewayMessage(queuedId);\n return ok ? 'sent' : 'failed';\n },\n [\n sessionId,\n sendCdecliMessage,\n patchChannelTitle,\n sendQueuedCdecli,\n setQueue,\n createAccountChatFileUploadLinksMutation,\n createAccountChatFileDownloadLinksMutation,\n ],\n );\n\n sendMessageRef.current = sendMessage;\n\n /* ---------------------------------------------------------------------- *\n * Outbox: turns typed while the gateway was down.\n * ---------------------------------------------------------------------- */\n\n const queuedChannelId = sessionId || cdecliStreamOverrideId || null;\n const queuedSnapshot = useCallback(\n () => queuedGatewayMessages(queuedChannelId, routing.accountId),\n [queuedChannelId, routing.accountId],\n );\n const queuedMessages = useSyncExternalStore(subscribeQueuedGatewayMessages, queuedSnapshot, queuedSnapshot);\n\n useEffect(() => {\n void restoreQueuedGatewayMessages();\n }, []);\n\n /** This chat's saved history, as the flush checks a queued turn against it. */\n const historyRef = useRef({ sessionId, loading: backendMessagesLoading, messages: backendMessages });\n historyRef.current = { sessionId, loading: backendMessagesLoading, messages: backendMessages };\n\n /** One release at a time; a send that fails leaves its entry at the head for the next reconnect. */\n const flushingRef = useRef(false);\n const flushQueuedMessages = useCallback(async () => {\n if (flushingRef.current) return;\n flushingRef.current = true;\n try {\n // Bounded: the outbox can never hand out more than its own depth.\n for (let i = 0; i <= MAX_QUEUED_MESSAGES; i += 1) {\n const rt = routingRef.current;\n const sid = sessionIdRef.current;\n if (!rt.channelConnected || !sid) return;\n const next = queuedGatewayMessages(sid, rt.accountId)[0];\n if (!next) return;\n // Never replay a turn the chat already holds. While its history is still\n // loading, wait: the release runs again once it lands.\n const history = historyRef.current;\n if (history.sessionId !== sid || history.loading) return;\n if (isQueuedMessageDelivered(next, history.messages ?? [])) {\n dropQueuedGatewayMessage(next.id);\n } else {\n const outcome = await sendMessageRef.current(\n next.text,\n next.attachments,\n next.channelId,\n false,\n next.id,\n );\n if (outcome !== 'sent') return;\n }\n }\n } finally {\n flushingRef.current = false;\n }\n }, []);\n\n /**\n * Release on the disconnected→connected edge, and when a channel with a queue\n * is opened on an already-live gateway. Deliberately not keyed on queue depth:\n * a send that fails puts its turn back, and depth would spin that into a loop.\n */\n const wasConnectedRef = useRef(routing.channelConnected);\n useEffect(() => {\n const connected = routing.channelConnected;\n const reconnected = connected && !wasConnectedRef.current;\n wasConnectedRef.current = connected;\n if (!connected || !queuedChannelId) return;\n if (!reconnected && queuedGatewayMessages(queuedChannelId, routing.accountId).length === 0) return;\n void flushQueuedMessages();\n // backendMessagesLoading: a release that waited for the chat's history runs when it lands.\n }, [routing.channelConnected, routing.accountId, queuedChannelId, flushQueuedMessages, backendMessagesLoading]);\n\n /**\n * A turn parked while the gateway is live - its own send failed (a dropped\n * request, a 5xx) - is tried again on this schedule, and after it the notice's\n * Send now is the way. Bounded: a send the gateway keeps failing must not spin.\n */\n const hasQueue = queuedMessages.length > 0;\n const [outboxRetries, setOutboxRetries] = useState(0);\n useEffect(() => {\n if (!hasQueue) {\n setOutboxRetries(0);\n return undefined;\n }\n if (!routing.channelConnected || outboxRetries >= OUTBOX_RETRY_DELAYS_MS.length) return undefined;\n const timer = setTimeout(() => {\n void flushQueuedMessages().finally(() => setOutboxRetries((n) => n + 1));\n }, OUTBOX_RETRY_DELAYS_MS[outboxRetries]);\n return () => clearTimeout(timer);\n }, [hasQueue, routing.channelConnected, outboxRetries, flushQueuedMessages]);\n const outboxRetrying = hasQueue && routing.channelConnected && outboxRetries < OUTBOX_RETRY_DELAYS_MS.length;\n\n const discardQueuedMessages = useCallback(() => {\n if (!queuedChannelId) return;\n clearQueuedGatewayMessages(queuedChannelId);\n setError(null);\n }, [queuedChannelId]);\n\n tryRecoverAndResendRef.current = async (reason: string) => {\n if (authRetryUsedRef.current || cdecliRoundHandledRef.current) return false;\n if (!isAgentJwtRejected(reason)) return false;\n const recover = routingRef.current.recoverAgentAuth;\n if (!recover) return false;\n authRetryUsedRef.current = true;\n recoveringAuthRef.current = true;\n try {\n setError('Refreshing CDeCLI credentials…');\n const recovered = await recover();\n if (!recovered) return false;\n const um = userMsgForSaveRef.current;\n const sid = saveSessionIdRef.current;\n cdecliRoundHandledRef.current = false;\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n setError(null);\n if (um && sid) {\n queueMicrotask(() => {\n void sendMessageRef.current(um.content, um.attachments, sid, true);\n });\n }\n return true;\n } catch (err) {\n console.error('[useChatStream] recoverAgentAuth failed:', err);\n return false;\n } finally {\n recoveringAuthRef.current = false;\n }\n };\n\n const cancel = useCallback(() => {\n clearPendingStream();\n const sid = saveSessionIdRef.current ?? sessionId;\n void cancelCdecliTurn(sid ?? 'messenger');\n if (!cdecliRoundHandledRef.current) {\n cdecliRoundHandledRef.current = true;\n finalizeCdecliRound(resolveAssistantReply(''));\n }\n }, [cancelCdecliTurn, finalizeCdecliRound, sessionId, clearPendingStream]);\n\n const clearMessages = useCallback(() => {\n clearPendingStream();\n const hadActiveTurn = isSendingRef.current;\n const sid = saveSessionIdRef.current ?? sessionId;\n isSendingRef.current = false;\n cdecliRoundHandledRef.current = true;\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n // Only hit /cancel when a turn was live — otherwise cdecli logs\n // \"Cannot cancel: no active session\" (Research greet + trash).\n if (hadActiveTurn) {\n void cancelCdecliTurn(sid ?? 'messenger');\n }\n ignoreHydrationRef.current = true;\n // Emptying the thread empties its outbox too: a queued turn released after\n // the user cleared the chat would answer a conversation they threw away.\n if (sid) clearQueuedGatewayMessages(sid);\n // ...and what the gateway queued for the agent.\n for (const queued of queuedFollowUpsRef.current) {\n if (!isProvisionalFollowUp(queued.id)) void cancelQueuedCdecli(queued.id, sid ?? 'messenger');\n }\n setQueue([]);\n setMessages([]);\n setResponse('');\n setQuickReply('');\n setError(null);\n setIsLoading(false);\n setIsStreaming(false);\n if (sid) clearChannelHistoryRunning(sid);\n }, [cancelCdecliTurn, cancelQueuedCdecli, clearPendingStream, sessionId, setQueue]);\n\n /** Take one queued message back before the agent gets to it. Too late once\n * the agent started it: it then joins the thread with its answer. */\n const cancelQueuedFollowUp = useCallback(\n async (id: string) => {\n const sid = sessionIdRef.current;\n // Still on its way to the gateway: there is nothing there to cancel yet.\n if (!sid || isProvisionalFollowUp(id)) return;\n const result = await cancelQueuedCdecli(id, sid);\n if (result.ok) {\n setQueue(queuedFollowUpsRef.current.filter((q) => q.id !== id));\n } else {\n setError(result.error || 'Could not cancel that message.');\n }\n },\n [cancelQueuedCdecli, setQueue],\n );\n\n /** Stop the running reply so the agent takes the queued messages now. */\n const sendQueuedNow = useCallback(() => {\n if (isSendingRef.current) cancel();\n }, [cancel]);\n\n const messagesLoading = !!sessionId && backendMessagesLoading && !backendMessagesLoaded;\n\n return {\n messages,\n response,\n quickReply,\n error,\n isLoading,\n isStreaming,\n messagesLoading,\n hasMessages:\n messages.length > 0 ||\n !!response ||\n !!quickReply ||\n queuedMessages.length > 0 ||\n queuedFollowUps.length > 0,\n /** Turns waiting on the gateway, oldest first. Rendered as queued bubbles. */\n queuedMessages,\n /** A parked turn will be tried again on its own (the gateway is live). */\n outboxRetrying,\n /** Send the queue now (the notice's retry), independent of the reconnect edge. */\n flushQueuedMessages,\n discardQueuedMessages,\n /** Sent while the agent was busy and queued for it, oldest first. */\n queuedFollowUps,\n cancelQueuedFollowUp,\n sendQueuedNow,\n sendMessage,\n cancel,\n clearMessages,\n };\n}\n"],"names":["media","_a"],"mappings":";;;;;;;;;;;;;;;;;;;AAoBA,MAAM,eAAkB,GAAA,QAAA,CAAS,EAAO,KAAA,SAAA,GAAY,GAAM,GAAA,EAAA;AAG1D,SAAS,2BAA2B,IAAuB,EAAA;AACzD,EAAM,MAAA,CAAA,GAAI,KAAK,IAAK,EAAA;AACpB,EAAI,IAAA,CAAC,GAAU,OAAA,KAAA;AACf,EAAO,OAAA,YAAA,CAAa,KAAK,CAAC,CAAA,IAAK,oBAAoB,IAAK,CAAA,CAAC,KAAK,oBAAqB,CAAA,IAAA,CAAK,CAAC,CAAK,IAAA,kBAAA,CAAmB,KAAK,CAAC,CAAA,IAAK,wBAAwB,IAAK,CAAA,CAAC,CAAK,IAAA,kBAAA,CAAmB,CAAC,CAAA;AACrL;AAyBA,SAAS,0BAAA,CAA2B,MAAqB,IAA6B,EAAA;AACpF,EAAA,MAAM,IAAO,GAAA,IAAA,CAAK,IAAK,CAAA,MAAA,GAAS,CAAC,CAAA;AACjC,EAAO,OAAA,CAAA,IAAA,IAAA,IAAA,GAAA,MAAA,GAAA,IAAA,CAAM,IAAS,MAAA,MAAA,IAAU,IAAK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,MAAA;AACL,MAAS,QAAA,CAAA,MAAA,CAAO,SAAS,gCAAgC,CAAA;AAAA;AAC3D,GACC,EAAA,CAAC,kBAAoB,EAAA,QAAQ,CAAC,CAAA;AAGjC,EAAM,MAAA,aAAA,GAAgB,YAAY,MAAM;AACtC,IAAI,IAAA,YAAA,CAAa,SAAgB,MAAA,EAAA;AAAA,GACnC,EAAG,CAAC,MAAM,CAAC,CAAA;AACX,EAAA,MAAM,eAAkB,GAAA,CAAC,CAAC,SAAA,IAAa,0BAA0B,CAAC,qBAAA;AAClE,EAAO,OAAA;AAAA,IACL,QAAA;AAAA,IACA,QAAA;AAAA,IACA,UAAA;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,IAAY,CAAC,CAAC,UAAc,IAAA,cAAA,CAAe,MAAS,GAAA,CAAA,IAAK,gBAAgB,MAAS,GAAA,CAAA;AAAA;AAAA,IAExH,cAAA;AAAA;AAAA,IAEA,cAAA;AAAA;AAAA,IAEA,mBAAA;AAAA,IACA,qBAAA;AAAA;AAAA,IAEA,eAAA;AAAA,IACA,oBAAA;AAAA,IACA,aAAA;AAAA,IACA,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, useSyncExternalStore } from 'react';\nimport { Platform } from 'react-native';\nimport {\n useCreateAccountChatFileDownloadLinksMutation,\n useCreateAccountChatFileUploadLinksMutation,\n} from 'common/graphql';\nimport {\n clearChannelHistoryRunning,\n markChannelHistoryRunning,\n patchChannelHistoryPreview,\n useChatMutations,\n useChatMessages,\n} from './useChatApi';\nimport { useCdecliChannel, type CdecliTurnOptions } from './useCdecliChannel';\nimport { chatModelForRequest, useChatModelId } from '../features/chat/chatModelPick';\nimport { usePrerequisiteIds } from './usePrerequisiteIds';\nimport { isAgentJwtRejected, shouldInlineGatewayMediaForHostedAgent } from './systemTokenJwt';\nimport { config } from '../config';\nimport {\n MAX_QUEUED_MESSAGES,\n clearQueuedGatewayMessages,\n dropQueuedGatewayMessage,\n isQueuedMessageDelivered,\n queueGatewayMessage,\n queuedGatewayMessages,\n restoreQueuedGatewayMessages,\n subscribeQueuedGatewayMessages,\n} from '../services/queuedGatewayMessages';\nimport { isImageAttachment } from '../features/attachments/isImageAttachment';\nimport { buildGatewayMedia, buildGatewayMediaPreferUrls } from '../features/attachments/buildGatewayMedia';\nimport { preserveAttachmentPreviews } from '../features/attachments/preserveAttachmentPreviews';\nimport { releasePreviewBytes } from '../features/attachments/releasePreviewBytes';\nimport { resolveAssistantReply } from '../features/chat/emptyChatResponse';\nimport { splitPreResponse } from '../features/chat/preResponse';\nimport { savedReplyFor, seenRowIds } from '../features/chat/savedReply';\nimport {\n appendFollowUpAssistant,\n appendOrReplaceAssistant,\n collapseConsecutiveAssistants,\n mergeOptimisticGatewayMessages,\n} from '../state/chatThreadMerge';\n\n// Each flush re-parses the whole reply as markdown. Mid-range Android CPUs\n// drop frames at 20 flushes/s; 10/s still reads as live typing.\nconst STREAM_FLUSH_MS = Platform.OS === 'android' ? 100 : 50;\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 isAgentJwtRejected(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/** The queued row renders this turn now, so the optimistic bubble must not stay behind it. */\nfunction withoutTrailingUserMessage(prev: ChatMessage[], text: string): ChatMessage[] {\n const last = prev[prev.length - 1];\n return last?.role === 'user' && last.content === text ? prev.slice(0, -1) : prev;\n}\n\n/** A message the gateway queued for the agent while a turn was running. */\nexport interface QueuedFollowUp {\n /** The gateway's id for it - what cancels it. */\n id: string;\n text: string;\n attachments?: MessageAttachment[];\n}\n\n/** Retries of a turn parked on a live gateway (see `outboxRetrying`). */\nexport const OUTBOX_RETRY_DELAYS_MS = [3_000, 10_000, 30_000] as const;\n\n/** A mid-turn message shows under this id until the gateway gives it one. */\nconst PROVISIONAL_FOLLOW_UP = 'sending-';\nconst isProvisionalFollowUp = (id: string) => id.startsWith(PROVISIONAL_FOLLOW_UP);\n\n/** What became of a send: delivered to the gateway, parked in the outbox, or refused outright. */\nexport type SendOutcome = 'sent' | 'queued' | 'failed';\n\nfunction formatBackendThread(\n backendMessages: Array<{\n role: string;\n content?: string;\n // The generated `ChatMessageUI` types `type` as a plain string; it is narrowed\n // to the UI union in the map below, so take it wide rather than cast at the call.\n attachments?: Array<{ id: string; name: string; type: string; mimeType?: string; size?: number; url?: string }>;\n tokenCount?: number;\n model?: string;\n }>,\n): ChatMessage[] {\n return collapseConsecutiveAssistants(\n backendMessages.map((msg) => ({\n role: msg.role as 'user' | 'assistant',\n content: msg.content ?? '',\n attachments: msg.attachments?.map((a) => ({\n id: a.id,\n name: a.name,\n type: a.type === 'screenshot' ? 'screenshot' : 'file',\n mimeType: a.mimeType,\n size: a.size,\n url: a.url,\n })),\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 );\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 /** Remint the system JWT and reconnect after cdecli-agent 401s the session. */\n recoverAgentAuth?: () => Promise<boolean>;\n /** Agent skill every turn on this stream carries (`metadata.skill`), e.g. Web Builder's. */\n skill?: string;\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 /** Brain assist — never the published agent stream. Shown as a Quick answer strip. */\n const [quickReply, setQuickReply] = 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 * Messages sent while a turn was running, which the gateway queued for the\n * agent. Shown above the composer until the agent starts on them (the way\n * Claude Code shows a message typed mid-turn), then moved into the thread.\n * Kept out of `messages` so a backend hydration cannot drop or double them.\n */\n const [queuedFollowUps, setQueuedFollowUps] = useState<QueuedFollowUp[]>([]);\n const queuedFollowUpsRef = useRef<QueuedFollowUp[]>([]);\n /** Names the row a mid-turn message shows in until the gateway gives it an id. */\n const provisionalSeqRef = useRef(0);\n const sendMessageRef = useRef<\n (\n content: string,\n attachments?: MessageAttachment[],\n sessionIdOverride?: string | null,\n alreadyVisible?: boolean,\n queuedId?: string,\n turnOptions?: CdecliTurnOptions,\n ) => Promise<SendOutcome>\n >(async () => 'failed');\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 const sessionIdRef = useRef<string | null>(sessionId);\n sessionIdRef.current = sessionId || cdecliStreamOverrideId || null;\n /** Blocks duplicate cdecli `onComplete` from appending assistant twice / saving twice per send. */\n const cdecliRoundHandledRef = useRef(false);\n /**\n * The round in flight was opened by the agent, not by a send: a follow-up,\n * e.g. the answer to a request the gateway queued while the agent was busy.\n * It completes as a new bubble instead of replacing the reply before it.\n */\n const followUpRoundRef = useRef(false);\n /** One remint+resend per turn when cdecli-agent 401s the JWT. */\n const authRetryUsedRef = useRef(false);\n const recoveringAuthRef = useRef(false);\n const chatModelId = useChatModelId();\n const routingRef = useRef(routing);\n routingRef.current = routing;\n\n const tryRecoverAndResendRef = useRef<(reason: string) => Promise<boolean>>(async () => false);\n\n /** Coalesce token deltas so Fabric is not committing a native tree every chunk. */\n const pendingStreamRef = useRef('');\n const streamFlushTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const clearPendingStream = useCallback(() => {\n if (streamFlushTimerRef.current != null) {\n clearTimeout(streamFlushTimerRef.current);\n streamFlushTimerRef.current = null;\n }\n pendingStreamRef.current = '';\n }, []);\n\n const flushPendingStream = useCallback(() => {\n streamFlushTimerRef.current = null;\n const pending = pendingStreamRef.current;\n if (!pending) return;\n pendingStreamRef.current = '';\n setResponse((r) => {\n const next = r + pending;\n const sid = sessionIdRef.current;\n if (sid) markChannelHistoryRunning(sid, next);\n return next;\n });\n }, []);\n\n useEffect(() => () => clearPendingStream(), [clearPendingStream]);\n\n /** The live reply, readable from a send (an answer keeps the question it answers). */\n const responseTextRef = useRef('');\n useEffect(() => {\n responseTextRef.current = response;\n }, [response]);\n\n const { saveMessages, patchChannelTitle } = useChatMutations();\n const titlePatchedChannelsRef = useRef(new Set<string>());\n const { accountUserId } = usePrerequisiteIds();\n const [createAccountChatFileUploadLinksMutation] = useCreateAccountChatFileUploadLinksMutation();\n const [createAccountChatFileDownloadLinksMutation] = useCreateAccountChatFileDownloadLinksMutation();\n const {\n messages: backendMessages,\n loading: backendMessagesLoading,\n messagesLoaded: backendMessagesLoaded,\n fetchThread,\n } = useChatMessages(sessionId);\n const backendMessagesRef = useRef(backendMessages);\n backendMessagesRef.current = backendMessages;\n const fetchThreadRef = useRef(fetchThread);\n fetchThreadRef.current = fetchThread;\n /**\n * The saved posts the open round could already see when it began. A reply read\n * back from the server must be newer than these (`savedReplyFor`).\n */\n const seenPostIdsRef = useRef<ReadonlySet<string>>(new Set());\n const markRoundStart = useCallback(() => {\n seenPostIdsRef.current = seenRowIds(backendMessagesRef.current ?? []);\n }, []);\n const lastHydratedSessionIdRef = useRef<string | null>(null);\n /** Trash-clear: do not re-hydrate gateway history until the next send. */\n const ignoreHydrationRef = useRef(false);\n\n const streamChannelId = sessionId || cdecliStreamOverrideId;\n\n const finalizeCdecliRound = useCallback(\n (assistantContent?: string) => {\n const previewSid = saveSessionIdRef.current || sessionIdRef.current;\n clearPendingStream();\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n followUpRoundRef.current = false;\n setResponse('');\n setQuickReply('');\n setIsLoading(false);\n setIsStreaming(false);\n isSendingRef.current = false;\n if (previewSid) clearChannelHistoryRunning(previewSid);\n if (assistantContent !== undefined) {\n setMessages((prev) =>\n appendOrReplaceAssistant(prev, { role: 'assistant' as const, content: assistantContent }),\n );\n if (previewSid) patchChannelHistoryPreview(previewSid, assistantContent);\n }\n },\n [clearPendingStream],\n );\n\n const cdecliCallbacks = useMemo(\n () => ({\n onChunk: (text: string) => {\n if (!isSendingRef.current) {\n // No send opened this round: the agent is speaking on its own.\n isSendingRef.current = true;\n followUpRoundRef.current = true;\n cdecliRoundHandledRef.current = false;\n markRoundStart();\n saveSessionIdRef.current = sessionIdRef.current;\n setIsLoading(true);\n setIsStreaming(true);\n setError(null);\n const sid = sessionIdRef.current;\n if (sid) markChannelHistoryRunning(sid, text);\n // The agent has started on what was queued: those messages\n // join the thread now, above the answer they are getting.\n const started = queuedFollowUpsRef.current;\n if (started.length > 0) {\n queuedFollowUpsRef.current = [];\n setQueuedFollowUps([]);\n setMessages((prev) => [\n ...prev,\n ...started.map((q) => ({\n role: 'user' as const,\n content: q.text,\n attachments: q.attachments,\n })),\n ]);\n }\n }\n pendingStreamRef.current += text;\n if (streamFlushTimerRef.current == null) {\n streamFlushTimerRef.current = setTimeout(flushPendingStream, STREAM_FLUSH_MS);\n }\n },\n // The brain's provisional answer is the WHOLE reply-so-far, not a chunk:\n // it is set outright, and set to '' when the real stream supersedes it.\n onQuickReply: (text: string) => {\n setQuickReply(text);\n },\n // The gateway's own words on the running work (a status answer, a\n // long-wait report) arrive as thread posts through hydration; the\n // callback only keeps them from ending the reply in progress.\n onNotice: () => undefined,\n onStreamRestart: () => {\n clearPendingStream();\n pendingStreamRef.current = '';\n setResponse('');\n },\n onComplete: (text: string) => {\n clearPendingStream();\n if (cdecliRoundHandledRef.current) {\n return;\n }\n\n // Judge the agent's own words: a quick answer in front of them is\n // not the agent failing, and never belongs in the error banner.\n const agentText = splitPreResponse(text).text;\n if (isCdecliAgentFailureOutput(agentText)) {\n void (async () => {\n if (await tryRecoverAndResendRef.current(agentText)) return;\n if (cdecliRoundHandledRef.current) return;\n cdecliRoundHandledRef.current = true;\n setError(\n isAgentJwtRejected(agentText)\n ? agentText\n : 'CDeCLI agent error. Check gateway status and server-side LLM configuration.',\n );\n finalizeCdecliRound(isAgentJwtRejected(agentText) ? undefined : text);\n })();\n return;\n }\n\n cdecliRoundHandledRef.current = true;\n authRetryUsedRef.current = false;\n\n const reply = resolveAssistantReply(text);\n const sid = saveSessionIdRef.current;\n const um = userMsgForSaveRef.current;\n const followUp = followUpRoundRef.current;\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n followUpRoundRef.current = false;\n\n const assistant = { role: 'assistant' as const, content: reply };\n setMessages((prev) =>\n followUp ? appendFollowUpAssistant(prev, assistant) : appendOrReplaceAssistant(prev, assistant),\n );\n const previewSid = sid || sessionIdRef.current;\n if (previewSid) {\n clearChannelHistoryRunning(previewSid);\n patchChannelHistoryPreview(previewSid, reply);\n }\n setResponse('');\n setQuickReply('');\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: reply,\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 void (async () => {\n if (await tryRecoverAndResendRef.current(err)) return;\n if (cdecliRoundHandledRef.current) return;\n cdecliRoundHandledRef.current = true;\n setError(err || 'CDeCLI stream error.');\n finalizeCdecliRound(resolveAssistantReply(''));\n })();\n },\n fetchSavedReply: async () => savedReplyFor(await fetchThreadRef.current(), seenPostIdsRef.current),\n }),\n [saveMessages, accountUserId, finalizeCdecliRound, flushPendingStream, clearPendingStream, markRoundStart],\n );\n\n const {\n sendMessage: sendCdecliMessage,\n sendQueued: sendQueuedCdecli,\n cancelQueued: cancelQueuedCdecli,\n cancel: cancelCdecliTurn,\n } = useCdecliChannel(\n routing.channelConnected,\n routing.accountId,\n streamChannelId,\n cdecliCallbacks,\n chatModelForRequest(chatModelId),\n routing.skill,\n );\n\n const setQueue = useCallback((next: QueuedFollowUp[]) => {\n queuedFollowUpsRef.current = next;\n setQueuedFollowUps(next);\n }, []);\n\n useEffect(() => {\n if (sessionId && cdecliStreamOverrideId && sessionId === cdecliStreamOverrideId) {\n setCdecliStreamOverrideId(undefined);\n }\n }, [sessionId, cdecliStreamOverrideId]);\n\n useEffect(() => {\n const prevSid = lastHydratedSessionIdRef.current;\n if (prevSid && sessionId && prevSid !== sessionId && isSendingRef.current) {\n // Switching threads: drop local send flags so this view can hydrate.\n // The previous channel's agent keeps running server-side; history still\n // shows it as running until that turn completes or we reopen it.\n clearPendingStream();\n setQueue([]);\n isSendingRef.current = false;\n followUpRoundRef.current = false;\n cdecliRoundHandledRef.current = false;\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n setIsLoading(false);\n setIsStreaming(false);\n setResponse('');\n setQuickReply('');\n }\n\n if (!sessionId) {\n setMessages([]);\n setResponse('');\n setQuickReply('');\n lastHydratedSessionIdRef.current = null;\n return;\n }\n\n const stampHistoryPreview = (msgs: ChatMessage[]) => {\n const last = msgs[msgs.length - 1];\n const lastAssistant = [...msgs].reverse().find((msg) => msg.role === 'assistant' && msg.content.trim());\n if (lastAssistant && !isSendingRef.current) {\n patchChannelHistoryPreview(sessionId, lastAssistant.content);\n }\n // Finished thread (last post is assistant) — drop the history \"Running\" badge.\n // A live turn ends with a user post until the assistant lands.\n if (!isSendingRef.current && last?.role === 'assistant') {\n clearChannelHistoryRunning(sessionId);\n }\n };\n\n if (ignoreHydrationRef.current) {\n return;\n }\n\n const keepStream = isSendingRef.current;\n const sessionChanged = lastHydratedSessionIdRef.current !== sessionId;\n if (sessionChanged) {\n lastHydratedSessionIdRef.current = sessionId;\n // Do not merge the previous channel's in-memory thread into this one.\n if (!backendMessagesLoaded) {\n if (!keepStream) {\n setMessages([]);\n setResponse('');\n setQuickReply('');\n }\n return;\n }\n const formatted = formatBackendThread(backendMessages ?? []);\n stampHistoryPreview(formatted);\n setMessages((prev) => (keepStream ? mergeOptimisticGatewayMessages(prev, formatted) : formatted));\n if (!keepStream) {\n setResponse('');\n setQuickReply('');\n }\n return;\n }\n\n if (backendMessagesLoaded) {\n const formatted = formatBackendThread(backendMessages ?? []);\n stampHistoryPreview(formatted);\n // Positional merge first so assistant replies the gateway never persisted\n // (cdecli skill turns emit no chatMessageAdded) survive this snapshot instead\n // of being dropped, then preserve in-memory attachment previews on the result.\n setMessages((prev) => preserveAttachmentPreviews(prev, mergeOptimisticGatewayMessages(prev, formatted)));\n if (!keepStream) {\n setResponse('');\n setQuickReply('');\n }\n }\n }, [sessionId, backendMessages, backendMessagesLoaded, clearPendingStream, setQueue]);\n\n const sendMessage = useCallback(\n async (\n content: string,\n attachments?: MessageAttachment[],\n sessionIdOverride?: string | null,\n alreadyVisible = false,\n /** Set when this send is the release of an outbox entry; it owns that entry's fate. */\n queuedId: string | undefined = undefined,\n /**\n * Extras for this turn (a surface job the agent settles). Only a turn that\n * starts now carries them: a queued or parked message goes out later without.\n */\n turnOptions: CdecliTurnOptions = {},\n ): Promise<SendOutcome> => {\n if (!content.trim() && !attachments?.length) return 'failed';\n\n const effectiveSessionId = sessionIdOverride !== undefined ? sessionIdOverride : sessionId;\n const rt = routingRef.current;\n const trimmed = content.trim();\n const sendText =\n trimmed ||\n (attachments?.length\n ? `Attached: ${attachments\n .map((a) => a.name)\n .filter(Boolean)\n .join(', ')}`\n : '');\n\n const userMessage: ChatMessage = {\n role: 'user',\n content: sendText,\n attachments,\n };\n\n /**\n * The gateway is down. The turn is remembered, not erased: it stays in the\n * thread as a queued bubble and the outbox releases it in order the moment\n * the channel reports connected. Losing what the user typed here is the\n * whole reason this lane exists.\n */\n if (!rt.channelConnected) {\n if (!effectiveSessionId) {\n setError('Missing chat session id.');\n return 'failed';\n }\n // A release that raced the connection dropping stays where it is.\n if (queuedId) return 'queued';\n const result = queueGatewayMessage({\n channelId: effectiveSessionId,\n accountId: rt.accountId,\n text: sendText,\n attachments,\n });\n if (!result.ok) {\n setError(\n result.reason === 'full'\n ? `${MAX_QUEUED_MESSAGES} messages are already waiting for the gateway. They send as soon as it connects.`\n : 'Nothing to send.',\n );\n return 'failed';\n }\n if (alreadyVisible) setMessages((prev) => withoutTrailingUserMessage(prev, sendText));\n setError(null);\n return 'queued';\n }\n\n /**\n * A turn is already in flight. The gateway queues the message for the\n * agent, which answers it when the running turn ends; the running reply\n * is left alone. It waits above the composer (cancellable) until the\n * agent starts on it. A status question is answered on the spot, and a\n * turn that had already ended takes the message straight away.\n */\n if (isSendingRef.current && !turnOptions.answersAsk) {\n if (!effectiveSessionId) {\n setError('Missing chat session id.');\n return 'failed';\n }\n // Above the composer from the tap, not from the gateway's answer: the\n // provisional row takes the gateway's id once it has one.\n const provisionalId = `${PROVISIONAL_FOLLOW_UP}${(provisionalSeqRef.current += 1)}`;\n const preview = releasePreviewBytes(attachments);\n if (!alreadyVisible) {\n setQueue([\n ...queuedFollowUpsRef.current,\n { id: provisionalId, text: sendText, attachments: preview },\n ]);\n }\n const withoutProvisional = () => queuedFollowUpsRef.current.filter((q) => q.id !== provisionalId);\n const media = attachments?.length ? buildGatewayMedia(attachments, { includeData: true }) : [];\n const outcome = await sendQueuedCdecli(sendText, effectiveSessionId, media);\n if (outcome.status === 'failed') {\n setQueue(withoutProvisional());\n // Keep the words: the outbox holds the turn (and survives a restart)\n // and offers the retry. A release that failed is already in it.\n const parked = queuedId\n ? { ok: true as const }\n : queueGatewayMessage({\n channelId: effectiveSessionId,\n accountId: rt.accountId,\n text: sendText,\n attachments,\n });\n if (parked.ok && alreadyVisible) setMessages((prev) => withoutTrailingUserMessage(prev, sendText));\n // Parked: the outbox notice says so and offers the retry.\n setError(parked.ok ? null : outcome.error || 'Could not send the message. Try again.');\n return parked.ok ? 'queued' : 'failed';\n }\n if (queuedId) dropQueuedGatewayMessage(queuedId);\n setError(null);\n if (outcome.status === 'queued') {\n setQueue(\n alreadyVisible\n ? [...queuedFollowUpsRef.current, { id: outcome.id, text: sendText, attachments: preview }]\n : queuedFollowUpsRef.current.map((q) =>\n q.id === provisionalId ? { ...q, id: outcome.id } : q,\n ),\n );\n if (alreadyVisible) setMessages((prev) => withoutTrailingUserMessage(prev, sendText));\n } else {\n // The running turn had ended: the agent took it straight away.\n setQueue(withoutProvisional());\n if (!alreadyVisible) setMessages((prev) => [...prev, userMessage]);\n }\n return 'sent';\n }\n\n // An answer to a parked question while its turn is still open: the reply so far\n // (the one asking) stays in the thread, and the answer starts the next round.\n if (isSendingRef.current && turnOptions.answersAsk) {\n const asked = responseTextRef.current + pendingStreamRef.current;\n clearPendingStream();\n if (asked.trim()) {\n setMessages((prev) =>\n appendOrReplaceAssistant(prev, { role: 'assistant' as const, content: asked }),\n );\n }\n }\n\n isSendingRef.current = true;\n followUpRoundRef.current = false;\n ignoreHydrationRef.current = false;\n if (effectiveSessionId && sendText) {\n titlePatchedChannelsRef.current.add(effectiveSessionId);\n patchChannelTitle(effectiveSessionId, sendText, true);\n markChannelHistoryRunning(effectiveSessionId);\n }\n if (!alreadyVisible) {\n // The transcript keeps this turn for the rest of the session, so it\n // keeps the preview URI and not the base64 behind it. The bytes stay\n // on `userMsgForSaveRef` below, which is nulled when the turn ends -\n // a retry still has them, a backgrounded app no longer carries them.\n const retained: ChatMessage = {\n ...userMessage,\n attachments: releasePreviewBytes(userMessage.attachments),\n };\n setMessages((prev) => [...prev, retained]);\n authRetryUsedRef.current = false;\n }\n setResponse('');\n setQuickReply('');\n setIsLoading(true);\n setIsStreaming(true);\n setError(null);\n userMsgForSaveRef.current = userMessage;\n saveSessionIdRef.current = effectiveSessionId ?? null;\n cdecliRoundHandledRef.current = false;\n markRoundStart();\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 'failed';\n }\n\n if (sessionIdOverride) {\n setCdecliStreamOverrideId(sessionIdOverride);\n await new Promise<void>((resolve) => {\n setTimeout(resolve, 0);\n });\n }\n\n const inlineForHostedAgent = shouldInlineGatewayMediaForHostedAgent(\n config.GRAPHQL_URL,\n config.CDECLI_AGENT_ENDPOINT,\n );\n // Vision turns must carry inline bytes. URL-only media is what made\n // \"what is this\" + a photo look like a text-only question.\n const inlineImages = (attachments ?? []).some(isImageAttachment) || inlineForHostedAgent;\n let media = inlineImages\n ? buildGatewayMedia(attachments, { includeData: true })\n : await buildGatewayMediaPreferUrls(\n attachments,\n async (filenames) => {\n const result = await createAccountChatFileUploadLinksMutation({\n variables: { filenames },\n });\n return result.data?.createAccountChatFileUploadLinks || [];\n },\n async (urls) => {\n const result = await createAccountChatFileDownloadLinksMutation({\n variables: { urls },\n });\n return result.data?.createAccountChatFileDownloadLinks || [];\n },\n );\n if ((attachments?.length ?? 0) > 0 && media.length === 0) {\n media = buildGatewayMedia(attachments, { includeData: true });\n }\n const ok = await sendCdecliMessage(sendText, effectiveSessionId, media, turnOptions);\n if (!ok && !cdecliRoundHandledRef.current && !recoveringAuthRef.current) {\n cdecliRoundHandledRef.current = true;\n // The send never reached the agent. Park it rather than drop it - a\n // release keeps its place at the head of its own queue.\n const parked = queuedId\n ? { ok: true as const }\n : queueGatewayMessage({\n channelId: effectiveSessionId,\n accountId: rt.accountId,\n text: sendText,\n attachments,\n });\n // Parked: the outbox notice says so and offers the retry; a second banner\n // saying it again in red read as the message being lost.\n setError(parked.ok ? null : 'Failed to send message via CDeCLI. Check gateway connection.');\n // Queued: the queued row renders the turn, so the optimistic bubble goes.\n // Not queued: only drop a bubble this call put there.\n setMessages((p) => {\n if (parked.ok) return withoutTrailingUserMessage(p, sendText);\n return alreadyVisible ? p : p.slice(0, -1);\n });\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n userMsgForSaveRef.current = null;\n saveSessionIdRef.current = null;\n clearChannelHistoryRunning(effectiveSessionId);\n return parked.ok ? 'queued' : 'failed';\n }\n if (ok && queuedId) dropQueuedGatewayMessage(queuedId);\n return ok ? 'sent' : 'failed';\n },\n [\n sessionId,\n sendCdecliMessage,\n patchChannelTitle,\n sendQueuedCdecli,\n setQueue,\n createAccountChatFileUploadLinksMutation,\n createAccountChatFileDownloadLinksMutation,\n markRoundStart,\n ],\n );\n\n sendMessageRef.current = sendMessage;\n\n /* ---------------------------------------------------------------------- *\n * Outbox: turns typed while the gateway was down.\n * ---------------------------------------------------------------------- */\n\n const queuedChannelId = sessionId || cdecliStreamOverrideId || null;\n const queuedSnapshot = useCallback(\n () => queuedGatewayMessages(queuedChannelId, routing.accountId),\n [queuedChannelId, routing.accountId],\n );\n const queuedMessages = useSyncExternalStore(subscribeQueuedGatewayMessages, queuedSnapshot, queuedSnapshot);\n\n useEffect(() => {\n void restoreQueuedGatewayMessages();\n }, []);\n\n /** This chat's saved history, as the flush checks a queued turn against it. */\n const historyRef = useRef({ sessionId, loading: backendMessagesLoading, messages: backendMessages });\n historyRef.current = { sessionId, loading: backendMessagesLoading, messages: backendMessages };\n\n /** One release at a time; a send that fails leaves its entry at the head for the next reconnect. */\n const flushingRef = useRef(false);\n const flushQueuedMessages = useCallback(async () => {\n if (flushingRef.current) return;\n flushingRef.current = true;\n try {\n // Bounded: the outbox can never hand out more than its own depth.\n for (let i = 0; i <= MAX_QUEUED_MESSAGES; i += 1) {\n const rt = routingRef.current;\n const sid = sessionIdRef.current;\n if (!rt.channelConnected || !sid) return;\n const next = queuedGatewayMessages(sid, rt.accountId)[0];\n if (!next) return;\n // Never replay a turn the chat already holds. While its history is still\n // loading, wait: the release runs again once it lands.\n const history = historyRef.current;\n if (history.sessionId !== sid || history.loading) return;\n if (isQueuedMessageDelivered(next, history.messages ?? [])) {\n dropQueuedGatewayMessage(next.id);\n } else {\n const outcome = await sendMessageRef.current(\n next.text,\n next.attachments,\n next.channelId,\n false,\n next.id,\n );\n if (outcome !== 'sent') return;\n }\n }\n } finally {\n flushingRef.current = false;\n }\n }, []);\n\n /**\n * Release on the disconnected→connected edge, and when a channel with a queue\n * is opened on an already-live gateway. Deliberately not keyed on queue depth:\n * a send that fails puts its turn back, and depth would spin that into a loop.\n */\n const wasConnectedRef = useRef(routing.channelConnected);\n useEffect(() => {\n const connected = routing.channelConnected;\n const reconnected = connected && !wasConnectedRef.current;\n wasConnectedRef.current = connected;\n if (!connected || !queuedChannelId) return;\n if (!reconnected && queuedGatewayMessages(queuedChannelId, routing.accountId).length === 0) return;\n void flushQueuedMessages();\n // backendMessagesLoading: a release that waited for the chat's history runs when it lands.\n }, [routing.channelConnected, routing.accountId, queuedChannelId, flushQueuedMessages, backendMessagesLoading]);\n\n /**\n * A turn parked while the gateway is live - its own send failed (a dropped\n * request, a 5xx) - is tried again on this schedule, and after it the notice's\n * Send now is the way. Bounded: a send the gateway keeps failing must not spin.\n */\n const hasQueue = queuedMessages.length > 0;\n const [outboxRetries, setOutboxRetries] = useState(0);\n useEffect(() => {\n if (!hasQueue) {\n setOutboxRetries(0);\n return undefined;\n }\n if (!routing.channelConnected || outboxRetries >= OUTBOX_RETRY_DELAYS_MS.length) return undefined;\n const timer = setTimeout(() => {\n void flushQueuedMessages().finally(() => setOutboxRetries((n) => n + 1));\n }, OUTBOX_RETRY_DELAYS_MS[outboxRetries]);\n return () => clearTimeout(timer);\n }, [hasQueue, routing.channelConnected, outboxRetries, flushQueuedMessages]);\n const outboxRetrying = hasQueue && routing.channelConnected && outboxRetries < OUTBOX_RETRY_DELAYS_MS.length;\n\n const discardQueuedMessages = useCallback(() => {\n if (!queuedChannelId) return;\n clearQueuedGatewayMessages(queuedChannelId);\n setError(null);\n }, [queuedChannelId]);\n\n tryRecoverAndResendRef.current = async (reason: string) => {\n if (authRetryUsedRef.current || cdecliRoundHandledRef.current) return false;\n if (!isAgentJwtRejected(reason)) return false;\n const recover = routingRef.current.recoverAgentAuth;\n if (!recover) return false;\n authRetryUsedRef.current = true;\n recoveringAuthRef.current = true;\n try {\n setError('Refreshing CDeCLI credentials…');\n const recovered = await recover();\n if (!recovered) return false;\n const um = userMsgForSaveRef.current;\n const sid = saveSessionIdRef.current;\n cdecliRoundHandledRef.current = false;\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n setError(null);\n if (um && sid) {\n queueMicrotask(() => {\n void sendMessageRef.current(um.content, um.attachments, sid, true);\n });\n }\n return true;\n } catch (err) {\n console.error('[useChatStream] recoverAgentAuth failed:', err);\n return false;\n } finally {\n recoveringAuthRef.current = false;\n }\n };\n\n const cancel = useCallback(() => {\n clearPendingStream();\n const sid = saveSessionIdRef.current ?? sessionId;\n void cancelCdecliTurn(sid ?? 'messenger');\n if (!cdecliRoundHandledRef.current) {\n cdecliRoundHandledRef.current = true;\n finalizeCdecliRound(resolveAssistantReply(''));\n }\n }, [cancelCdecliTurn, finalizeCdecliRound, sessionId, clearPendingStream]);\n\n const clearMessages = useCallback(() => {\n clearPendingStream();\n const hadActiveTurn = isSendingRef.current;\n const sid = saveSessionIdRef.current ?? sessionId;\n isSendingRef.current = false;\n cdecliRoundHandledRef.current = true;\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n // Only hit /cancel when a turn was live — otherwise cdecli logs\n // \"Cannot cancel: no active session\" (Research greet + trash).\n if (hadActiveTurn) {\n void cancelCdecliTurn(sid ?? 'messenger');\n }\n ignoreHydrationRef.current = true;\n // Emptying the thread empties its outbox too: a queued turn released after\n // the user cleared the chat would answer a conversation they threw away.\n if (sid) clearQueuedGatewayMessages(sid);\n // ...and what the gateway queued for the agent.\n for (const queued of queuedFollowUpsRef.current) {\n if (!isProvisionalFollowUp(queued.id)) void cancelQueuedCdecli(queued.id, sid ?? 'messenger');\n }\n setQueue([]);\n setMessages([]);\n setResponse('');\n setQuickReply('');\n setError(null);\n setIsLoading(false);\n setIsStreaming(false);\n if (sid) clearChannelHistoryRunning(sid);\n }, [cancelCdecliTurn, cancelQueuedCdecli, clearPendingStream, sessionId, setQueue]);\n\n /** Take one queued message back before the agent gets to it. Too late once\n * the agent started it: it then joins the thread with its answer. */\n const cancelQueuedFollowUp = useCallback(\n async (id: string) => {\n const sid = sessionIdRef.current;\n // Still on its way to the gateway: there is nothing there to cancel yet.\n if (!sid || isProvisionalFollowUp(id)) return;\n const result = await cancelQueuedCdecli(id, sid);\n if (result.ok) {\n setQueue(queuedFollowUpsRef.current.filter((q) => q.id !== id));\n } else {\n setError(result.error || 'Could not cancel that message.');\n }\n },\n [cancelQueuedCdecli, setQueue],\n );\n\n /** Stop the running reply so the agent takes the queued messages now. */\n const sendQueuedNow = useCallback(() => {\n if (isSendingRef.current) cancel();\n }, [cancel]);\n\n const messagesLoading = !!sessionId && backendMessagesLoading && !backendMessagesLoaded;\n\n return {\n messages,\n response,\n quickReply,\n error,\n isLoading,\n isStreaming,\n messagesLoading,\n hasMessages:\n messages.length > 0 ||\n !!response ||\n !!quickReply ||\n queuedMessages.length > 0 ||\n queuedFollowUps.length > 0,\n /** Turns waiting on the gateway, oldest first. Rendered as queued bubbles. */\n queuedMessages,\n /** A parked turn will be tried again on its own (the gateway is live). */\n outboxRetrying,\n /** Send the queue now (the notice's retry), independent of the reconnect edge. */\n flushQueuedMessages,\n discardQueuedMessages,\n /** Sent while the agent was busy and queued for it, oldest first. */\n queuedFollowUps,\n cancelQueuedFollowUp,\n sendQueuedNow,\n sendMessage,\n cancel,\n clearMessages,\n };\n}\n"],"names":["media","_a"],"mappings":";;;;;;;;;;;;;;;;;;;AAqBA,MAAM,eAAkB,GAAA,QAAA,CAAS,EAAO,KAAA,SAAA,GAAY,GAAM,GAAA,EAAA;AAG1D,SAAS,2BAA2B,IAAuB,EAAA;AACzD,EAAM,MAAA,CAAA,GAAI,KAAK,IAAK,EAAA;AACpB,EAAI,IAAA,CAAC,GAAU,OAAA,KAAA;AACf,EAAO,OAAA,YAAA,CAAa,KAAK,CAAC,CAAA,IAAK,oBAAoB,IAAK,CAAA,CAAC,KAAK,oBAAqB,CAAA,IAAA,CAAK,CAAC,CAAK,IAAA,kBAAA,CAAmB,KAAK,CAAC,CAAA,IAAK,wBAAwB,IAAK,CAAA,CAAC,CAAK,IAAA,kBAAA,CAAmB,CAAC,CAAA;AACrL;AAyBA,SAAS,0BAAA,CAA2B,MAAqB,IAA6B,EAAA;AACpF,EAAA,MAAM,IAAO,GAAA,IAAA,CAAK,IAAK,CAAA,MAAA,GAAS,CAAC,CAAA;AACjC,EAAO,OAAA,CAAA,IAAA,IAAA,IAAA,GAAA,MAAA,GAAA,IAAA,CAAM,IAAS,MAAA,MAAA,IAAU,IAAK,CAAA,OAAA,KAAY,OAAO,IAAK,CAAA,KAAA,CA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S,GAAA,CAAA,IAAK,gBAAgB,MAAS,GAAA,CAAA;AAAA;AAAA,IAExH,cAAA;AAAA;AAAA,IAEA,cAAA;AAAA;AAAA,IAEA,mBAAA;AAAA,IACA,qBAAA;AAAA;AAAA,IAEA,eAAA;AAAA,IACA,oBAAA;AAAA,IACA,aAAA;AAAA,IACA,WAAA;AAAA,IACA,MAAA;AAAA,IACA;AAAA,GACF;AACF"}
package/lib/module.js CHANGED
@@ -1,4 +1,5 @@
1
- import {Feature}from'@common-stack/client-react';import {filteredRoutes}from'./compute.js';import {registerHostTranscriptProtocol}from'./features/chat/hostTranscriptProtocol.js';import {typePolicies}from'./graphql/typePolicies.js';registerHostTranscriptProtocol();
1
+ import {Feature}from'@common-stack/client-react';import {filteredRoutes}from'./compute.js';import {registerHostTranscriptProtocol}from'./features/chat/hostTranscriptProtocol.js';import {registerGameInviteCard}from'./features/games/GameInviteCard.js';import {typePolicies}from'./graphql/typePolicies.js';registerHostTranscriptProtocol();
2
+ registerGameInviteCard();
2
3
  var YantraMobileModule = new Feature({
3
4
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
4
5
  routeConfig: filteredRoutes,
package/lib/module.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"module.js","sources":["../src/module.ts"],"sourcesContent":["/* eslint-disable import/no-extraneous-dependencies */\nimport { Feature } from '@common-stack/client-react';\nimport { filteredRoutes } from './compute';\nimport { registerHostTranscriptProtocol } from './features/chat/hostTranscriptProtocol';\nimport { typePolicies } from './graphql/typePolicies';\n\n// Before any chat renders, in this host or in a federated remote it loads.\nregisterHostTranscriptProtocol();\n\nexport default new Feature({\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n routeConfig: filteredRoutes as any,\n clientStateParams: {\n typePolicies,\n },\n // Mirror billing/browser: namespace plan vs subscription cache ids so a\n // CurrentSubscription{id:'basic'} cannot clobber AdminPlan{id:'basic'}.\n dataIdFromObject: {\n AdminPlan: (result: { id: string }) => `AdminPlan:${result.id}`,\n CurrentSubscription: (result: { id: string }) => `CurrentSubscription:${result.id}`,\n },\n});\n"],"names":[],"mappings":"uOAOA,8BAA+B,EAAA;AAC/B,yBAAe,IAAI,OAAQ,CAAA;AAAA;AAAA,EAEzB,WAAa,EAAA,cAAA;AAAA,EACb,iBAAmB,EAAA;AAAA,IACjB;AAAA,GACF;AAAA;AAAA;AAAA,EAGA,gBAAkB,EAAA;AAAA,IAChB,SAAW,EAAA,CAAC,MAEN,KAAA,CAAA,UAAA,EAAa,OAAO,EAAE,CAAA,CAAA;AAAA,IAC5B,mBAAqB,EAAA,CAAC,MAEhB,KAAA,CAAA,oBAAA,EAAuB,OAAO,EAAE,CAAA;AAAA;AAE1C,CAAC,CAAA"}
1
+ {"version":3,"file":"module.js","sources":["../src/module.ts"],"sourcesContent":["/* eslint-disable import/no-extraneous-dependencies */\nimport { Feature } from '@common-stack/client-react';\nimport { filteredRoutes } from './compute';\nimport { registerHostTranscriptProtocol } from './features/chat/hostTranscriptProtocol';\nimport { registerGameInviteCard } from './features/games/GameInviteCard';\nimport { typePolicies } from './graphql/typePolicies';\n\n// Before any chat renders, in this host or in a federated remote it loads.\nregisterHostTranscriptProtocol();\nregisterGameInviteCard();\n\nexport default new Feature({\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n routeConfig: filteredRoutes as any,\n clientStateParams: {\n typePolicies,\n },\n // Mirror billing/browser: namespace plan vs subscription cache ids so a\n // CurrentSubscription{id:'basic'} cannot clobber AdminPlan{id:'basic'}.\n dataIdFromObject: {\n AdminPlan: (result: { id: string }) => `AdminPlan:${result.id}`,\n CurrentSubscription: (result: { id: string }) => `CurrentSubscription:${result.id}`,\n },\n});\n"],"names":[],"mappings":"+SAQA,8BAA+B,EAAA;AAC/B,sBAAuB,EAAA;AACvB,yBAAe,IAAI,OAAQ,CAAA;AAAA;AAAA,EAEzB,WAAa,EAAA,cAAA;AAAA,EACb,iBAAmB,EAAA;AAAA,IACjB;AAAA,GACF;AAAA;AAAA;AAAA,EAGA,gBAAkB,EAAA;AAAA,IAChB,SAAW,EAAA,CAAC,MAEN,KAAA,CAAA,UAAA,EAAa,OAAO,EAAE,CAAA,CAAA;AAAA,IAC5B,mBAAqB,EAAA,CAAC,MAEhB,KAAA,CAAA,oBAAA,EAAuB,OAAO,EAAE,CAAA;AAAA;AAE1C,CAAC,CAAA"}
@@ -1,4 +1,4 @@
1
- import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {useMemo,useLayoutEffect,useState,useCallback,useRef,useEffect}from'react';import {useWindowDimensions,Keyboard,StyleSheet,View,Pressable}from'react-native';import {Box,Text,InputToolBar}from'@admin-layout/gluestack-ui-mobile';import {ComposerModeSwitch,composerMode}from'../../features/chat/ComposerModeSwitch.js';import {useSafeAreaInsets,SafeAreaView}from'react-native-safe-area-context';import {useNavigation,useRoute,CommonActions}from'@react-navigation/native';import {MessageActionBar}from'../../features/chat/MessageActionBar.js';import {withTemporaryChat}from'../../features/chat/withTemporaryChat.js';import {ChatTranscript}from'../../features/chat/ChatTranscript.js';import {ChatLinkOpenerProvider}from'../../features/links/ChatLinkOpenerProvider.js';import {AskUserCard}from'../../features/chat/AskUserCard.js';import {pendingAskUser}from'../../features/chat/askUser.js';import {PendingConnectorConnectCard}from'../../features/chat/ConnectorConnectPrompt.js';import {QueuedFollowUps}from'../../features/chat/QueuedFollowUps.js';import {queuedFollowUpRows}from'../../features/chat/queuedFollowUpRows.js';import {displayConnectorConnectMessages,displayConnectorConnectText}from'common';import {splitPreResponse}from'../../features/chat/preResponse.js';import {FreeCreditsCard}from'../../features/credits/FreeCreditsCard.js';import {lockedTurnToResend}from'../../features/credits/freeCredits.js';import {useFreeCredits}from'../../features/credits/useFreeCredits.js';import'common/graphql';import'../../config/env-config.js';import'../../hooks/usePrerequisiteIds.js';import'@react-native-async-storage/async-storage';import'expo-secure-store';import'../../features/messaging/yantraChatOrg.js';import {useCdecliConnection}from'../../contexts/cdecliConnection.js';import'../../contexts/GatewayContext.js';import {useChatLiveStream}from'../../contexts/ChatLiveStreamContext.js';import {KeyboardAwareScreen,KeyboardComposerDock}from'../../components/KeyboardComposerDock.js';import {YantraBrandLoader,YANTRA_LOADER_SIZE_COMPACT}from'../../components/YantraBrandLoader.js';import ThinkingIndicator from'../../components/ThinkingIndicator.js';import {mobileTokens}from'../../theme/mobileTokens.js';import {useAppTheme}from'../../theme/AppThemeProvider.js';import DeepSearchModal from'../Home/components/DeepSearchModal.js';import {normalizeSummaryText,extractDeepSearchSources}from'../Home/deepSearchUtils.js';import {AudioRecorderPanel}from'../../features/audio-input/AudioRecorderPanel.js';import {NativeDictationBar}from'../../features/audio-input/NativeDictationBar.js';import {isNativeDictationAvailable}from'../../features/audio-input/nativeDictation.js';import {useImageAttachments}from'../../features/attachments/useImageAttachments.js';import {ComposerAttachmentBar}from'../../features/attachments/ComposerAttachmentBar.js';import {useComposerAttachMenu}from'../../features/attachments/ComposerAttachMenu.js';import {peekComposerAttachments,hasComposerAttachments,takeComposerAttachments}from'../../features/attachments/composerAttachmentHandoff.js';import {MicErrorBoundary}from'../../features/audio-input/MicErrorBoundary.js';import {requestMicPermission}from'../../features/audio-input/useAudioPermission.js';import {shouldRedirectToShop}from'../../features/shopping/chat/homeShoppingIntent.js';import {replaceWithShopNative,shopHandoffParams,pushShopNative}from'../../features/shopping/chat/openShopNative.js';import {resolveNativeHandoff,nativeRouteForConnectors}from'../../features/apps/nativeAppHandoff.js';import {parseToolActivity}from'../../features/chat/toolActivity.js';import {replaceWithNativeApp,nativeHandoffParams,pushNativeApp}from'../../features/apps/nativeAppNavigation.js';var __defProp = Object.defineProperty;
1
+ import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {useMemo,useLayoutEffect,useState,useCallback,useRef,useEffect}from'react';import {useWindowDimensions,Keyboard,StyleSheet,View,Pressable}from'react-native';import {Box,Text,InputToolBar}from'@admin-layout/gluestack-ui-mobile';import {ComposerModeSwitch,composerMode}from'../../features/chat/ComposerModeSwitch.js';import {useSafeAreaInsets,SafeAreaView}from'react-native-safe-area-context';import {useNavigation,useRoute,CommonActions}from'@react-navigation/native';import {MessageActionBar}from'../../features/chat/MessageActionBar.js';import {withTemporaryChat}from'../../features/chat/withTemporaryChat.js';import {ChatTranscript}from'../../features/chat/ChatTranscript.js';import {ChatLinkOpenerProvider}from'../../features/links/ChatLinkOpenerProvider.js';import {AskUserCard}from'../../features/chat/AskUserCard.js';import {pendingAskUser}from'../../features/chat/askUser.js';import {PendingConnectorConnectCard}from'../../features/chat/ConnectorConnectPrompt.js';import {QueuedFollowUps}from'../../features/chat/QueuedFollowUps.js';import {queuedFollowUpRows}from'../../features/chat/queuedFollowUpRows.js';import {displayConnectorConnectMessages,displayConnectorConnectText}from'common';import {splitPreResponse}from'../../features/chat/preResponse.js';import {FreeCreditsCard}from'../../features/credits/FreeCreditsCard.js';import {lockedTurnToResend}from'../../features/credits/freeCredits.js';import {useFreeCredits}from'../../features/credits/useFreeCredits.js';import'common/graphql';import'../../config/env-config.js';import'../../hooks/usePrerequisiteIds.js';import'@react-native-async-storage/async-storage';import'expo-secure-store';import'../../features/messaging/yantraChatOrg.js';import {useCdecliConnection}from'../../contexts/cdecliConnection.js';import'../../contexts/GatewayContext.js';import {useChatLiveStream}from'../../contexts/ChatLiveStreamContext.js';import {KeyboardAwareScreen,KeyboardComposerDock}from'../../components/KeyboardComposerDock.js';import {YantraBrandLoader,YANTRA_LOADER_SIZE_COMPACT}from'../../components/YantraBrandLoader.js';import ThinkingIndicator from'../../components/ThinkingIndicator.js';import {mobileTokens}from'../../theme/mobileTokens.js';import {useAppTheme}from'../../theme/AppThemeProvider.js';import DeepSearchModal from'../Home/components/DeepSearchModal.js';import {normalizeSummaryText,extractDeepSearchSources}from'../Home/deepSearchUtils.js';import {AudioRecorderPanel}from'../../features/audio-input/AudioRecorderPanel.js';import {NativeDictationBar}from'../../features/audio-input/NativeDictationBar.js';import {isNativeDictationAvailable}from'../../features/audio-input/nativeDictation.js';import {useImageAttachments}from'../../features/attachments/useImageAttachments.js';import {ComposerAttachmentBar}from'../../features/attachments/ComposerAttachmentBar.js';import {useComposerAttachMenu}from'../../features/attachments/ComposerAttachMenu.js';import {peekComposerAttachments,hasComposerAttachments,takeComposerAttachments}from'../../features/attachments/composerAttachmentHandoff.js';import {MicErrorBoundary}from'../../features/audio-input/MicErrorBoundary.js';import {requestMicPermission}from'../../features/audio-input/useAudioPermission.js';import {shouldRedirectToShop}from'../../features/shopping/chat/homeShoppingIntent.js';import {replaceWithShopNative,shopHandoffParams,pushShopNative}from'../../features/shopping/chat/openShopNative.js';import {resolveAppHandoff,nativeRouteForConnectors}from'../../features/apps/nativeAppHandoff.js';import {parseToolActivity}from'../../features/chat/toolActivity.js';import {replaceWithNativeApp,nativeHandoffParams,pushNativeApp}from'../../features/apps/nativeAppNavigation.js';var __defProp = Object.defineProperty;
2
2
  var __defProps = Object.defineProperties;
3
3
  var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
4
4
  var __getOwnPropSymbols = Object.getOwnPropertySymbols;
@@ -17,6 +17,7 @@ var __spreadValues = (a, b) => {
17
17
  return a;
18
18
  };
19
19
  var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
20
+ const DEEP_RESEARCH_SKILL = "yantra-deep-research";
20
21
  function routingModeOf(value) {
21
22
  if (value === "deep-search" || value === "build") return value;
22
23
  return "chat";
@@ -202,7 +203,8 @@ function ChatScreen() {
202
203
  autoFiredRef.current = true;
203
204
  firstTurnRef.current = {
204
205
  text: initialQuery != null ? initialQuery : "",
205
- attachments
206
+ attachments,
207
+ deepSearch: isDeepSearchMode
206
208
  };
207
209
  if (isDeepSearchMode) {
208
210
  setIsDeepSearchModalOpen(true);
@@ -210,9 +212,11 @@ function ChatScreen() {
210
212
  void (async () => {
211
213
  var _a2;
212
214
  const mode = modeOf(isDeepSearchMode, isBuildMode);
213
- const [openShop, nativeRoute] = shopRouteChecked ? [false, null] : await Promise.all([shouldRedirectToShop(initialQuery != null ? initialQuery : "", (_a2 = attachments == null ? void 0 : attachments.length) != null ? _a2 : 0, mode).catch(() => false), resolveNativeHandoff(initialQuery != null ? initialQuery : "", {
214
- mode
215
+ const [shopSaysOpen, appTarget] = shopRouteChecked ? [false, null] : await Promise.all([shouldRedirectToShop(initialQuery != null ? initialQuery : "", (_a2 = attachments == null ? void 0 : attachments.length) != null ? _a2 : 0, mode).catch(() => false), resolveAppHandoff(initialQuery != null ? initialQuery : "", {
216
+ mode,
217
+ fallbackApp: typeof params.initialApp === "string" ? params.initialApp : null
215
218
  })]);
219
+ const openShop = shopSaysOpen || Boolean(appTarget == null ? void 0 : appTarget.shop);
216
220
  if (openShop) {
217
221
  firstTurnRef.current = null;
218
222
  releaseRoutingTurn(FIRST_TURN);
@@ -225,10 +229,10 @@ function ChatScreen() {
225
229
  }));
226
230
  return;
227
231
  }
228
- if (nativeRoute) {
232
+ if (appTarget) {
229
233
  firstTurnRef.current = null;
230
234
  releaseRoutingTurn(FIRST_TURN);
231
- replaceWithNativeApp(navigation, nativeRoute, nativeHandoffParams({
235
+ replaceWithNativeApp(navigation, appTarget.route, nativeHandoffParams({
232
236
  orgName: params.orgName,
233
237
  query: initialQuery != null ? initialQuery : "",
234
238
  files: attachments,
@@ -245,14 +249,16 @@ function ChatScreen() {
245
249
  });
246
250
  } catch (e) {
247
251
  }
248
- }, [channelId, initialQuery, initialAttachments, navigation, isDeepSearchMode, isBuildMode, params.orgName, shopRouteChecked, releaseRoutingTurn]);
252
+ }, [channelId, initialQuery, initialAttachments, navigation, isDeepSearchMode, isBuildMode, params.orgName, params.initialApp, shopRouteChecked, releaseRoutingTurn]);
249
253
  useEffect(() => {
250
254
  const turn = firstTurnRef.current;
251
255
  if (!firstTurnRouted || !turn || !channelId) return;
252
256
  if (cdecli.status !== "connected" && cdecli.status !== "error") return;
253
257
  firstTurnRef.current = null;
254
258
  releaseRoutingTurn(FIRST_TURN);
255
- void sendMessage(turn.text, turn.attachments, channelId);
259
+ void sendMessage(turn.text, turn.attachments, channelId, void 0, void 0, turn.deepSearch ? {
260
+ skill: DEEP_RESEARCH_SKILL
261
+ } : void 0);
256
262
  }, [firstTurnRouted, cdecli.status, channelId, sendMessage, releaseRoutingTurn]);
257
263
  const handleAskUserAnswer = useCallback((formatted) => {
258
264
  const text = formatted.trim();
@@ -305,11 +311,11 @@ function ChatScreen() {
305
311
  void (async () => {
306
312
  var _a3;
307
313
  const mode = isDeepSearchMode ? "deep-search" : "chat";
308
- const [openShop, nativeRoute] = await Promise.all([
314
+ const [openShop, appTarget] = await Promise.all([
309
315
  // `forSend()` is undefined with nothing attached; `.length` on it threw,
310
316
  // so a typed shopping ask never reached Shop.
311
317
  shouldRedirectToShop(t, (_a3 = pending == null ? void 0 : pending.length) != null ? _a3 : 0, mode).catch(() => false),
312
- resolveNativeHandoff(t, {
318
+ resolveAppHandoff(t, {
313
319
  mode,
314
320
  followUp: hasAssistantReply
315
321
  })
@@ -332,17 +338,17 @@ function ChatScreen() {
332
338
  }
333
339
  return;
334
340
  }
335
- if (nativeRoute) {
341
+ if (appTarget) {
336
342
  releaseRoutingTurn(turnId);
337
343
  if (messages.length === 0) {
338
- replaceWithNativeApp(navigation, nativeRoute, nativeHandoffParams({
344
+ replaceWithNativeApp(navigation, appTarget.route, nativeHandoffParams({
339
345
  orgName: params.orgName,
340
346
  query: t,
341
347
  files: pending,
342
348
  channelId
343
349
  }));
344
350
  } else {
345
- pushNativeApp(navigation, nativeRoute, nativeHandoffParams({
351
+ pushNativeApp(navigation, appTarget.route, nativeHandoffParams({
346
352
  orgName: params.orgName,
347
353
  query: t,
348
354
  files: pending
@@ -351,7 +357,9 @@ function ChatScreen() {
351
357
  return;
352
358
  }
353
359
  releaseRoutingTurn(turnId);
354
- void sendMessage(t, pending, channelId);
360
+ void sendMessage(t, pending, channelId, void 0, void 0, mode === "deep-search" ? {
361
+ skill: DEEP_RESEARCH_SKILL
362
+ } : void 0);
355
363
  })();
356
364
  imageAttachments.clear();
357
365
  }, [channelId, sendMessage, isDeepSearchMode, isBuildMode, navigation, params.orgName, imageAttachments, messages.length, hasAssistantReply, chatBusy, releaseRoutingTurn]);
@@ -693,4 +701,4 @@ const styles = StyleSheet.create({
693
701
  paddingBottom: 4
694
702
  }
695
703
  });
696
- var index = withTemporaryChat(ChatScreen);export{index as default};//# sourceMappingURL=index.js.map
704
+ var index = withTemporaryChat(ChatScreen);export{DEEP_RESEARCH_SKILL,index as default};//# sourceMappingURL=index.js.map