@adminide-stack/yantra-mobile 12.0.54-alpha.1 → 12.0.54-alpha.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/components/NavigationHeader/NavigationHeader.js +5 -2
- package/lib/components/NavigationHeader/NavigationHeader.js.map +1 -1
- package/lib/features/agent-chat/NativeAgentChat.js +354 -0
- package/lib/features/agent-chat/NativeAgentChat.js.map +1 -0
- package/lib/features/attachments/displayUserMessageText.js +3 -2
- package/lib/features/attachments/displayUserMessageText.js.map +1 -1
- package/lib/features/attachments/useImageAttachments.js +9 -7
- package/lib/features/attachments/useImageAttachments.js.map +1 -1
- package/lib/features/canvas/withRemoteSafeArea.js +46 -0
- package/lib/features/canvas/withRemoteSafeArea.js.map +1 -0
- package/lib/features/chat/ChatTranscript.js +23 -15
- package/lib/features/chat/ChatTranscript.js.map +1 -1
- package/lib/features/chat/toolActivity.js +42 -6
- package/lib/features/chat/toolActivity.js.map +1 -1
- package/lib/features/chat/transcriptGroups.js +11 -2
- package/lib/features/chat/transcriptGroups.js.map +1 -1
- package/lib/features/shopping/chat/homeShoppingIntent.js +58 -0
- package/lib/features/shopping/chat/homeShoppingIntent.js.map +1 -0
- package/lib/features/shopping/chat/openShopNative.js +60 -0
- package/lib/features/shopping/chat/openShopNative.js.map +1 -0
- package/lib/hooks/useCdecliChannel.js +10 -8
- package/lib/hooks/useCdecliChannel.js.map +1 -1
- package/lib/hooks/useChatStream.js +13 -6
- package/lib/hooks/useChatStream.js.map +1 -1
- package/lib/index.js +1 -1
- package/lib/index.js.map +1 -1
- package/lib/screens/Chat/index.js +44 -5
- package/lib/screens/Chat/index.js.map +1 -1
- package/lib/screens/Home/HomeScreen.js +23 -3
- package/lib/screens/Home/HomeScreen.js.map +1 -1
- package/lib/screens/ShoppingNative/index.js +21 -2
- package/lib/screens/ShoppingNative/index.js.map +1 -1
- package/lib/screens/ShoppingNative/useShoppingHostChat.js +66 -0
- package/lib/screens/ShoppingNative/useShoppingHostChat.js.map +1 -0
- package/lib/services/brainQuickReply.js +72 -2
- package/lib/services/brainQuickReply.js.map +1 -1
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toolActivity.js","sources":["../../../src/features/chat/toolActivity.ts"],"sourcesContent":["/**\n * Tool-activity parsing for the polished status timeline (mobile).\n *\n * A port of the web's `features/chat/toolActivity`, copied rather than imported:\n * mobile is a separate bundle and shares no code with the web shell. It is pure\n * string logic with no DOM or React dependency, so the two are kept in step by\n * having the same tests rather than by a shared module.\n *\n *\n * The cdecli/agent narrates tool use into the streamed assistant text as bare\n * rows, e.g.:\n *\n * ⚙ ToolSearch\n * ⚙ mcp__cdecli__execute_action — yantra-image-generation/Image\n *\n * Rendered raw, these read as debug noise. We parse them out of the prose into\n * structured steps that {@link ./ToolTimeline} renders as an animated,\n * collapsible timeline, and hand back the cleaned prose so the bubble shows only\n * the real answer.\n *\n * Parsing is deliberately conservative: a line only counts as tool activity when\n * it leads with the gear/wrench glyph the agent prefixes, or is a standalone\n * `mcp__…` invocation. Ordinary prose never matches, so a miss degrades to\n * \"leave the text as-is\" rather than eating real content.\n */\n\nexport interface ToolStep {\n /** Stable within a single parse pass — index-based, so identical tools don't collide. */\n id: string;\n /** Humanized present-tense label, e.g. \"Generating image\". */\n label: string;\n /** Optional detail, e.g. the connector slug or raw tool token. */\n detail?: string;\n /** 'running' only ever applies to the LAST step of an in-flight turn. */\n status: 'running' | 'done';\n}\n\nexport interface ParsedToolActivity {\n steps: ToolStep[];\n /** Prose with every tool-activity line removed. */\n text: string;\n}\n\n// A tool-activity line: optional indent, a gear/wrench glyph (with optional\n// emoji variation selector), then the tool token + optional \"— detail\". The `m`\n// flag scopes ^/$ to each line; `u` so the glyph classes match correctly.\nconst GEAR_LINE_RE = /^[ \\t]*[⚙🔧\\u{1F6E0}]️?[ \\t]+(.+?)[ \\t]*$/u;\n// A bare MCP invocation on its own line — the agent sometimes omits the glyph.\n// `mcp__` is vanishingly unlikely in real prose, so this is safe to strip.\nconst BARE_MCP_LINE_RE = /^[ \\t]*(mcp__[^\\s].*?)[ \\t]*$/;\n\n/** Known tool tokens → present-tense labels. Anything unmapped falls back to a humanized token. */\nconst TOOL_LABELS: Array<[RegExp, string]> = [\n [/^tool[_-]?search$/i, 'Searching tools'],\n [/^web[_-]?search$/i, 'Searching the web'],\n [/^web[_-]?scrape$/i, 'Reading a page'],\n [/^web[_-]?batch[_-]?scrape$/i, 'Reading pages'],\n [/^reddit[_-]?search$/i, 'Searching Reddit'],\n [/^x[_-]?search$/i, 'Searching X'],\n [/^youtube[_-]?search$/i, 'Searching YouTube'],\n [/^academic[_-]?search$/i, 'Searching papers'],\n [/^(yantra[_-]?)?github[_-]?search$/i, 'Searching GitHub'],\n [/^bash$/i, 'Running a command'],\n [/^(str_replace_editor|edit|write)$/i, 'Editing files'],\n [/^read$/i, 'Reading files'],\n];\n\n/** Connector slug → verb phrase for `execute_action — <connector>/<action>` rows. */\nconst CONNECTOR_LABELS: Array<[RegExp, string]> = [\n [/image[_-]?gen/i, 'Generating image'],\n [/video[_-]?gen/i, 'Generating video'],\n [/(audio|tts|speech|voice)/i, 'Generating audio'],\n [/search/i, 'Searching'],\n];\n\n/** Title-case a slug/token: \"yantra-image-generation\" → \"Yantra image generation\". */\nfunction prettifySlug(slug: string): string {\n const words = slug\n .replace(/^yantra[_-]/i, '')\n .replace(/[_-]+/g, ' ')\n .trim();\n return words ? words.charAt(0).toUpperCase() + words.slice(1) : slug;\n}\n\n/**\n * Turn a raw tool row body into a { label, detail }. Handles the two shapes we\n * see: a bare tool name (\"ToolSearch\") and an MCP execute_action carrying a\n * \"connector/action\" detail after an em/en dash.\n */\nexport function humanizeToolLine(body: string): { label: string; detail?: string } {\n const trimmed = body.trim();\n\n // `mcp__cdecli__execute_action — yantra-image-generation/Image`\n const dashSplit = trimmed.split(/\\s+[—–-]\\s+/);\n const head = dashSplit[0]?.trim() ?? trimmed;\n const detailRaw = dashSplit.length > 1 ? dashSplit.slice(1).join(' — ').trim() : undefined;\n\n // Strip an `mcp__<server>__` prefix off the head token.\n const bareTool = head.replace(/^mcp__[^_]+__/i, '').replace(/^mcp__/i, '');\n\n // execute_action rows: the meaning is in the connector detail, not the verb.\n if (/^execute_action$/i.test(bareTool) && detailRaw) {\n const connector = detailRaw.split('/')[0]?.trim() ?? detailRaw;\n for (const [re, label] of CONNECTOR_LABELS) {\n if (re.test(connector)) return { label, detail: prettifySlug(connector) };\n }\n return { label: `Running ${prettifySlug(connector)}`, detail: detailRaw };\n }\n\n for (const [re, label] of TOOL_LABELS) {\n if (re.test(bareTool)) return { label, detail: detailRaw };\n }\n\n // Generic fallback: prettify the token (camelCase / snake_case → spaced).\n const spaced = bareTool\n .replace(/([a-z])([A-Z])/g, '$1 $2')\n .replace(/[_-]+/g, ' ')\n .trim();\n // Lowercase the WHOLE token, not just its first character: the split above\n // turns \"someNewTool\" into \"some New Tool\", and lowercasing only the head\n // left the label reading \"Running some New Tool\" mid-sentence.\n const label = spaced ? `Running ${spaced.toLowerCase()}` : 'Working';\n return { label, detail: detailRaw };\n}\n\n/**\n * Extract tool-activity rows from streamed/persisted assistant content.\n *\n * @param content raw assistant text\n * @param active when true the turn is still streaming, so the LAST step is\n * marked 'running'; otherwise every step is 'done'.\n */\nexport function parseToolActivity(content: string, active = false): ParsedToolActivity {\n if (!content) return { steps: [], text: content ?? '' };\n\n const steps: ToolStep[] = [];\n const kept: string[] = [];\n\n for (const line of content.split('\\n')) {\n const gear = GEAR_LINE_RE.exec(line);\n const mcp = gear ? null : BARE_MCP_LINE_RE.exec(line);\n const body = gear?.[1] ?? mcp?.[1];\n if (body) {\n const { label, detail } = humanizeToolLine(body);\n steps.push({ id: `tool-${steps.length}`, label, detail, status: 'done' });\n continue;\n }\n kept.push(line);\n }\n\n // Collapse the blank lines the removed rows leave behind (3+ newlines → 2).\n const text = kept\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();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ACJ,KAAA;AAAA,QACA;AAAA,OACF,GAAI,iBAAiB,IAAI,CAAA;AACzB,MAAA,KAAA,CAAM,IAAK,CAAA;AAAA,QACT,EAAA,EAAI,CAAQ,KAAA,EAAA,KAAA,CAAM,MAAM,CAAA,CAAA;AAAA,QACxB,KAAA;AAAA,QACA,MAAA;AAAA,QACA,MAAQ,EAAA;AAAA,OACT,CAAA;AACD,MAAA;AAAA;AAEF,IAAA,IAAA,CAAK,KAAK,IAAI,CAAA;AAAA;AAIhB,EAAM,MAAA,IAAA,GAAO,KAAK,IAAK,CAAA,IAAI,EAAE,OAAQ,CAAA,SAAA,EAAW,MAAM,CAAA,CAAE,IAAK,EAAA;AAC7D,EAAI,IAAA,MAAA,IAAU,KAAM,CAAA,MAAA,GAAS,CAAG,EAAA;AAC9B,IAAA,KAAA,CAAM,KAAM,CAAA,MAAA,GAAS,CAAC,CAAA,CAAE,MAAS,GAAA,SAAA;AAAA;AAEnC,EAAO,OAAA;AAAA,IACL,KAAA;AAAA,IACA;AAAA,GACF;AACF"}
|
|
1
|
+
{"version":3,"file":"toolActivity.js","sources":["../../../src/features/chat/toolActivity.ts"],"sourcesContent":["/**\n * Tool-activity parsing for the polished status timeline (mobile).\n *\n * A port of the web's `features/chat/toolActivity`, copied rather than imported:\n * mobile is a separate bundle and shares no code with the web shell. It is pure\n * string logic with no DOM or React dependency, so the two are kept in step by\n * having the same tests rather than by a shared module.\n *\n *\n * The cdecli/agent narrates tool use into the streamed assistant text as bare\n * rows, e.g.:\n *\n * ⚙ ToolSearch\n * ⚙ mcp__cdecli__execute_action — yantra-image-generation/Image\n *\n * Rendered raw, these read as debug noise. We parse them out of the prose into\n * structured steps that {@link ./ToolTimeline} renders as an animated,\n * collapsible timeline, and hand back the cleaned prose so the bubble shows only\n * the real answer.\n *\n * Parsing is deliberately conservative: a line only counts as tool activity when\n * it leads with the gear/wrench glyph the agent prefixes, or is a standalone\n * `mcp__…` invocation. Ordinary prose never matches, so a miss degrades to\n * \"leave the text as-is\" rather than eating real content.\n */\n\nexport interface ToolStep {\n /** Stable within a single parse pass — index-based, so identical tools don't collide. */\n id: string;\n /** Humanized present-tense label, e.g. \"Generating image\". */\n label: string;\n /** Optional detail, e.g. the connector slug or raw tool token. */\n detail?: string;\n /** 'running' only ever applies to the LAST step of an in-flight turn. */\n status: 'running' | 'done';\n}\n\nexport interface ParsedToolActivity {\n steps: ToolStep[];\n /** Prose with every tool-activity line removed. */\n text: string;\n}\n\n// A tool-activity line: optional indent, a gear/wrench glyph (with optional\n// emoji variation selector), then the tool token + optional \"— detail\". The `m`\n// flag scopes ^/$ to each line; `u` so the glyph classes match correctly.\nconst GEAR_LINE_RE = /^[ \\t]*[⚙🔧\\u{1F6E0}]️?[ \\t]+(.+?)[ \\t]*$/u;\n// A bare MCP invocation on its own line — the agent sometimes omits the glyph.\n// `mcp__` is vanishingly unlikely in real prose, so this is safe to strip.\nconst BARE_MCP_LINE_RE = /^[ \\t]*(mcp__[^\\s].*?)[ \\t]*$/;\n\n/** Known tool tokens → present-tense labels. Anything unmapped falls back to a humanized token. */\nconst TOOL_LABELS: Array<[RegExp, string]> = [\n [/^tool[_-]?search$/i, 'Searching tools'],\n [/^web[_-]?search$/i, 'Searching the web'],\n [/^web[_-]?scrape$/i, 'Reading a page'],\n [/^web[_-]?batch[_-]?scrape$/i, 'Reading pages'],\n [/^reddit[_-]?search$/i, 'Searching Reddit'],\n [/^x[_-]?search$/i, 'Searching X'],\n [/^youtube[_-]?search$/i, 'Searching YouTube'],\n [/^academic[_-]?search$/i, 'Searching papers'],\n [/^(yantra[_-]?)?github[_-]?search$/i, 'Searching GitHub'],\n [/^bash$/i, 'Running a command'],\n [/^grep$/i, 'Searching files'],\n [/^(str_replace_editor|edit|write)$/i, 'Editing files'],\n [/^read$/i, 'Reading files'],\n];\n\n/** Connector slug → verb phrase for `execute_action — <connector>/<action>` rows. */\nconst CONNECTOR_LABELS: Array<[RegExp, string]> = [\n [/image[_-]?gen/i, 'Generating image'],\n [/video[_-]?gen/i, 'Generating video'],\n [/(audio|tts|speech|voice)/i, 'Generating audio'],\n [/search/i, 'Searching'],\n];\n\n/** Title-case a slug/token: \"yantra-image-generation\" → \"Yantra image generation\". */\nfunction prettifySlug(slug: string): string {\n const words = slug\n .replace(/^yantra[_-]/i, '')\n .replace(/[_-]+/g, ' ')\n .trim();\n return words ? words.charAt(0).toUpperCase() + words.slice(1) : slug;\n}\n\n/** Shell / interpreter snippets the agent pastes after a bash/read row. */\nexport function isToolPayloadLine(line: string): boolean {\n const t = line.trim();\n if (!t) return false;\n if (/^```/.test(t)) return true;\n if (/^(import\\s+\\w+|from\\s+\\S+\\s+import)\\b/.test(t)) return true;\n if (/^(const|let|var)\\s+\\w+\\s*=/.test(t)) return true;\n if (/\\brequire\\s*\\(/.test(t)) return true;\n if (/^path\\s*=\\s*['\"`]/.test(t)) return true;\n if (/\\/(?:data\\/users\\/)?\\.cdecli-server\\b/.test(t)) return true;\n if (/^(mkdir|curl|chmod|rm |cp |mv |cat |echo |python3?\\b|node\\s+-e|npx |yarn |npm )\\b/.test(t)) return true;\n if (/^(fs\\.|JSON\\.parse|JSON\\.stringify)/.test(t)) return true;\n return false;\n}\n\nfunction looksLikeCommandDetail(detail: string): boolean {\n const t = detail.trim();\n if (!t) return false;\n if (isToolPayloadLine(t)) return true;\n if (/^(python3?|node|mkdir|curl|npx|bash|sh|zsh)\\b/.test(t)) return true;\n if (t.length > 72) return true;\n return false;\n}\n\nfunction sanitizeDetail(detail: string | undefined): string | undefined {\n if (!detail) return undefined;\n if (looksLikeCommandDetail(detail)) return undefined;\n return detail;\n}\n\n/** Drop fenced tool scripts without removing shopping/widget JSON fences. */\nexport function stripToolPayloads(text: string): string {\n const withoutFences = text.replace(/```([^\\n]*)\\n([\\s\\S]*?)(?:```|$)/g, (full, lang, body) => {\n const language = String(lang).trim().toLowerCase();\n if (/\\bpropsComponent\\b/.test(body)) return full;\n if (/^(python|py|javascript|js|ts|tsx|bash|sh|shell|zsh)$/.test(language)) return '';\n if (String(body).split('\\n').some(isToolPayloadLine)) return '';\n return full;\n });\n return withoutFences\n .split('\\n')\n .filter((line) => !isToolPayloadLine(line))\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim();\n}\n\n/**\n * Turn a raw tool row body into a { label, detail }. Handles the two shapes we\n * see: a bare tool name (\"ToolSearch\") and an MCP execute_action carrying a\n * \"connector/action\" detail after an em/en dash.\n */\nexport function humanizeToolLine(body: string): { label: string; detail?: string } {\n const trimmed = body.trim();\n\n // `mcp__cdecli__execute_action — yantra-image-generation/Image`\n const dashSplit = trimmed.split(/\\s+[—–-]\\s+/);\n const head = dashSplit[0]?.trim() ?? trimmed;\n const detailRaw = dashSplit.length > 1 ? dashSplit.slice(1).join(' — ').trim() : undefined;\n\n // Strip an `mcp__<server>__` prefix off the head token.\n const bareTool = head.replace(/^mcp__[^_]+__/i, '').replace(/^mcp__/i, '');\n\n // execute_action rows: the meaning is in the connector detail, not the verb.\n if (/^execute_action$/i.test(bareTool) && detailRaw) {\n const connector = detailRaw.split('/')[0]?.trim() ?? detailRaw;\n for (const [re, label] of CONNECTOR_LABELS) {\n if (re.test(connector)) return { label, detail: prettifySlug(connector) };\n }\n return { label: `Running ${prettifySlug(connector)}`, detail: sanitizeDetail(detailRaw) };\n }\n\n for (const [re, label] of TOOL_LABELS) {\n if (re.test(bareTool)) return { label, detail: sanitizeDetail(detailRaw) };\n }\n\n // Generic fallback: prettify the token (camelCase / snake_case → spaced).\n const spaced = bareTool\n .replace(/([a-z])([A-Z])/g, '$1 $2')\n .replace(/[_-]+/g, ' ')\n .trim();\n // Lowercase the WHOLE token, not just its first character: the split above\n // turns \"someNewTool\" into \"some New Tool\", and lowercasing only the head\n // left the label reading \"Running some New Tool\" mid-sentence.\n const label = spaced ? `Running ${spaced.toLowerCase()}` : 'Working';\n return { label, detail: sanitizeDetail(detailRaw) };\n}\n\n/**\n * Extract tool-activity rows from streamed/persisted assistant content.\n *\n * @param content raw assistant text\n * @param active when true the turn is still streaming, so the LAST step is\n * marked 'running'; otherwise every step is 'done'.\n */\nexport function parseToolActivity(content: string, active = false): ParsedToolActivity {\n if (!content) return { steps: [], text: content ?? '' };\n\n const steps: ToolStep[] = [];\n const kept: string[] = [];\n\n for (const line of content.split('\\n')) {\n const gear = GEAR_LINE_RE.exec(line);\n const mcp = gear ? null : BARE_MCP_LINE_RE.exec(line);\n const body = gear?.[1] ?? mcp?.[1];\n if (body) {\n const { label, detail } = humanizeToolLine(body);\n steps.push({ id: `tool-${steps.length}`, label, detail, status: 'done' });\n continue;\n }\n kept.push(line);\n }\n\n const text = stripToolPayloads(\n kept\n .join('\\n')\n .replace(/\\n{3,}/g, '\\n\\n')\n .trim(),\n );\n\n if (active && steps.length > 0) {\n steps[steps.length - 1].status = 'running';\n }\n\n return { steps, text };\n}\n"],"names":["label"],"mappings":"AA6CA,MAAM,YAAe,GAAA,4CAAA;AAGrB,MAAM,gBAAmB,GAAA,+BAAA;AAGzB,MAAM,WAAA,GAAuC,CAAC,CAAC,oBAAsB,EAAA,iBAAiB,GAAG,CAAC,mBAAA,EAAqB,mBAAmB,CAAA,EAAG,CAAC,mBAAA,EAAqB,gBAAgB,CAAG,EAAA,CAAC,6BAA+B,EAAA,eAAe,CAAG,EAAA,CAAC,wBAAwB,kBAAkB,CAAA,EAAG,CAAC,iBAAA,EAAmB,aAAa,CAAA,EAAG,CAAC,uBAAyB,EAAA,mBAAmB,CAAG,EAAA,CAAC,wBAA0B,EAAA,kBAAkB,GAAG,CAAC,oCAAA,EAAsC,kBAAkB,CAAA,EAAG,CAAC,SAAA,EAAW,mBAAmB,CAAG,EAAA,CAAC,SAAW,EAAA,iBAAiB,CAAG,EAAA,CAAC,oCAAsC,EAAA,eAAe,CAAG,EAAA,CAAC,SAAW,EAAA,eAAe,CAAC,CAAA;AAGrmB,MAAM,mBAA4C,CAAC,CAAC,gBAAkB,EAAA,kBAAkB,GAAG,CAAC,gBAAA,EAAkB,kBAAkB,C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AA,CAAA,CAAA;AAChC,IAAA,IAAI,IAAM,EAAA;AACR,MAAM,MAAA;AAAA,QACJ,KAAA;AAAA,QACA;AAAA,OACF,GAAI,iBAAiB,IAAI,CAAA;AACzB,MAAA,KAAA,CAAM,IAAK,CAAA;AAAA,QACT,EAAA,EAAI,CAAQ,KAAA,EAAA,KAAA,CAAM,MAAM,CAAA,CAAA;AAAA,QACxB,KAAA;AAAA,QACA,MAAA;AAAA,QACA,MAAQ,EAAA;AAAA,OACT,CAAA;AACD,MAAA;AAAA;AAEF,IAAA,IAAA,CAAK,KAAK,IAAI,CAAA;AAAA;AAEhB,EAAM,MAAA,IAAA,GAAO,iBAAkB,CAAA,IAAA,CAAK,IAAK,CAAA,IAAI,CAAE,CAAA,OAAA,CAAQ,SAAW,EAAA,MAAM,CAAE,CAAA,IAAA,EAAM,CAAA;AAChF,EAAI,IAAA,MAAA,IAAU,KAAM,CAAA,MAAA,GAAS,CAAG,EAAA;AAC9B,IAAA,KAAA,CAAM,KAAM,CAAA,MAAA,GAAS,CAAC,CAAA,CAAE,MAAS,GAAA,SAAA;AAAA;AAEnC,EAAO,OAAA;AAAA,IACL,KAAA;AAAA,IACA;AAAA,GACF;AACF"}
|
|
@@ -2,14 +2,23 @@ function collapseDuplicateUserRows(rows) {
|
|
|
2
2
|
const out = [];
|
|
3
3
|
for (const row of rows) {
|
|
4
4
|
const last = out[out.length - 1];
|
|
5
|
-
const trimmed = row.content
|
|
6
|
-
if (row.role === "user" && (last == null ? void 0 : last.role) === "user" && last.content.
|
|
5
|
+
const trimmed = normalizeUserContent(row.content);
|
|
6
|
+
if (row.role === "user" && (last == null ? void 0 : last.role) === "user" && isSameUserTurn(last.content, row.content) && trimmed) {
|
|
7
7
|
continue;
|
|
8
8
|
}
|
|
9
9
|
out.push(row);
|
|
10
10
|
}
|
|
11
11
|
return out;
|
|
12
12
|
}
|
|
13
|
+
function normalizeUserContent(content) {
|
|
14
|
+
return content.replace(/\n\nLook at the attached images? before answering\.?\s*$/i, "").trim();
|
|
15
|
+
}
|
|
16
|
+
function isSameUserTurn(a, b) {
|
|
17
|
+
const left = normalizeUserContent(a);
|
|
18
|
+
const right = normalizeUserContent(b);
|
|
19
|
+
if (!left || !right) return false;
|
|
20
|
+
return left === right;
|
|
21
|
+
}
|
|
13
22
|
function groupConsecutiveRoleRows(rows) {
|
|
14
23
|
const groups = [];
|
|
15
24
|
for (const row of rows) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transcriptGroups.js","sources":["../../../src/features/chat/transcriptGroups.ts"],"sourcesContent":["/**\n * Consecutive same-role turns share one visual cluster, matching web\n * (stacked bubbles, not one concatenated blob). ASK_USER-only assistant rows\n * are stripped first, so a card answer sits under the original prompt as its\n * own bubble in the same right-aligned stack.\n */\n\nexport type RoleRow = {\n id: string;\n role: string;\n content: string;\n};\n\nexport type RoleGroup<T extends RoleRow> = {\n id: string;\n role: string;\n items: T[];\n};\n\n/** Drop an immediately-repeated user bubble (web planMessages). */\nexport function collapseDuplicateUserRows<T extends RoleRow>(rows: readonly T[]): T[] {\n const out: T[] = [];\n for (const row of rows) {\n const last = out[out.length - 1];\n const trimmed = row.content
|
|
1
|
+
{"version":3,"file":"transcriptGroups.js","sources":["../../../src/features/chat/transcriptGroups.ts"],"sourcesContent":["/**\n * Consecutive same-role turns share one visual cluster, matching web\n * (stacked bubbles, not one concatenated blob). ASK_USER-only assistant rows\n * are stripped first, so a card answer sits under the original prompt as its\n * own bubble in the same right-aligned stack.\n */\n\nexport type RoleRow = {\n id: string;\n role: string;\n content: string;\n};\n\nexport type RoleGroup<T extends RoleRow> = {\n id: string;\n role: string;\n items: T[];\n};\n\n/** Drop an immediately-repeated user bubble (web planMessages). */\nexport function collapseDuplicateUserRows<T extends RoleRow>(rows: readonly T[]): T[] {\n const out: T[] = [];\n for (const row of rows) {\n const last = out[out.length - 1];\n const trimmed = normalizeUserContent(row.content);\n if (row.role === 'user' && last?.role === 'user' && isSameUserTurn(last.content, row.content) && trimmed) {\n continue;\n }\n out.push(row);\n }\n return out;\n}\n\nfunction normalizeUserContent(content: string): string {\n return content.replace(/\\n\\nLook at the attached images? before answering\\.?\\s*$/i, '').trim();\n}\n\nfunction isSameUserTurn(a: string, b: string): boolean {\n const left = normalizeUserContent(a);\n const right = normalizeUserContent(b);\n if (!left || !right) return false;\n return left === right;\n}\n\nexport function groupConsecutiveRoleRows<T extends RoleRow>(rows: readonly T[]): Array<RoleGroup<T>> {\n const groups: Array<RoleGroup<T>> = [];\n for (const row of rows) {\n const last = groups[groups.length - 1];\n if (last && last.role === row.role) {\n last.items.push(row);\n last.id = `${last.items[0].id}..${row.id}`;\n } else {\n groups.push({ id: row.id, role: row.role, items: [row] });\n }\n }\n return groups;\n}\n\n/** Visible user-group copy, one block — follow-ups append to the previous send. */\nexport function joinGroupedTexts(texts: readonly string[]): string {\n return texts\n .map((t) => t.trim())\n .filter(Boolean)\n .join('\\n\\n');\n}\n"],"names":[],"mappings":"AAmBO,SAAS,0BAA6C,IAAyB,EAAA;AACpF,EAAA,MAAM,MAAW,EAAC;AAClB,EAAA,KAAA,MAAW,OAAO,IAAM,EAAA;AACtB,IAAA,MAAM,IAAO,GAAA,GAAA,CAAI,GAAI,CAAA,MAAA,GAAS,CAAC,CAAA;AAC/B,IAAM,MAAA,OAAA,GAAU,oBAAqB,CAAA,GAAA,CAAI,OAAO,CAAA;AAChD,IAAA,IAAI,GAAI,CAAA,IAAA,KAAS,MAAU,IAAA,CAAA,IAAA,IAAA,IAAA,GAAA,MAAA,GAAA,IAAA,CAAM,IAAS,MAAA,MAAA,IAAU,cAAe,CAAA,IAAA,CAAK,OAAS,EAAA,GAAA,CAAI,OAAO,CAAA,IAAK,OAAS,EAAA;AACxG,MAAA;AAAA;AAEF,IAAA,GAAA,CAAI,KAAK,GAAG,CAAA;AAAA;AAEd,EAAO,OAAA,GAAA;AACT;AACA,SAAS,qBAAqB,OAAyB,EAAA;AACrD,EAAA,OAAO,OAAQ,CAAA,OAAA,CAAQ,2DAA6D,EAAA,EAAE,EAAE,IAAK,EAAA;AAC/F;AACA,SAAS,cAAA,CAAe,GAAW,CAAoB,EAAA;AACrD,EAAM,MAAA,IAAA,GAAO,qBAAqB,CAAC,CAAA;AACnC,EAAM,MAAA,KAAA,GAAQ,qBAAqB,CAAC,CAAA;AACpC,EAAA,IAAI,CAAC,IAAA,IAAQ,CAAC,KAAA,EAAc,OAAA,KAAA;AAC5B,EAAA,OAAO,IAAS,KAAA,KAAA;AAClB;AACO,SAAS,yBAA4C,IAAyC,EAAA;AACnG,EAAA,MAAM,SAA8B,EAAC;AACrC,EAAA,KAAA,MAAW,OAAO,IAAM,EAAA;AACtB,IAAA,MAAM,IAAO,GAAA,MAAA,CAAO,MAAO,CAAA,MAAA,GAAS,CAAC,CAAA;AACrC,IAAA,IAAI,IAAQ,IAAA,IAAA,CAAK,IAAS,KAAA,GAAA,CAAI,IAAM,EAAA;AAClC,MAAK,IAAA,CAAA,KAAA,CAAM,KAAK,GAAG,CAAA;AACnB,MAAK,IAAA,CAAA,EAAA,GAAK,GAAG,IAAK,CAAA,KAAA,CAAM,CAAC,CAAE,CAAA,EAAE,CAAK,EAAA,EAAA,GAAA,CAAI,EAAE,CAAA,CAAA;AAAA,KACnC,MAAA;AACL,MAAA,MAAA,CAAO,IAAK,CAAA;AAAA,QACV,IAAI,GAAI,CAAA,EAAA;AAAA,QACR,MAAM,GAAI,CAAA,IAAA;AAAA,QACV,KAAA,EAAO,CAAC,GAAG;AAAA,OACZ,CAAA;AAAA;AACH;AAEF,EAAO,OAAA,MAAA;AACT"}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import {classifyIntentViaBrain,parseShoppingViaBrain}from'../../../services/brainQuickReply.js';const LEADING_PREFIX = /^(please\s+)?(can you\s+)?(help me\s+)?(find|search for|shop for|buy|get|show me|recommend|compare)\s+/i;
|
|
2
|
+
function parseBudget(text) {
|
|
3
|
+
const patterns = [/\b(?:under|below|max|budget(?:\s+is)?)\s+\$?\s*(\d+(?:\.\d+)?)/i, /\b(?:my\s+)?budget\s*(?:is|:)?\s+\$?\s*(\d+(?:\.\d+)?)/i];
|
|
4
|
+
for (const pattern of patterns) {
|
|
5
|
+
const match = text.match(pattern);
|
|
6
|
+
if (match) {
|
|
7
|
+
const value = Number.parseFloat(match[1]);
|
|
8
|
+
if (Number.isFinite(value) && value > 0) return value;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
return void 0;
|
|
12
|
+
}
|
|
13
|
+
function extractShoppingIntentFromText(text) {
|
|
14
|
+
const trimmed = text.trim();
|
|
15
|
+
if (trimmed.length < 4) return null;
|
|
16
|
+
const budget = parseBudget(trimmed);
|
|
17
|
+
const hasPriceCue = budget != null || /\$\s?\d+/.test(trimmed) || /\bunder\s+\d+/i.test(trimmed);
|
|
18
|
+
const hasProductEntity = /(^|[^A-Za-z0-9/_-])(headphones?|earbuds?|ear\s*buds?|laptop|notebook|computer|phone|smartphone|tablet|ipad|watch|smartwatch|camera|tv|television|monitor|keyboard|mouse|speaker|console|playstation|xbox|switch|shoes?|sneakers?|jacket|coat|backpack|bag|purse|wallet|gift|toy|game|furniture|desk|chair|sofa|mattress|appliance|blender|coffee maker|vacuum|router|modem|charger|cable|case|cover|skincare|serum|perfume|makeup|vitamin|protein|supplement|bike|bicycle|tent|camping|grill|bbq|string lights|electronics|gadget|device|accessory|accessories|iphone|airpods?)(?![A-Za-z0-9/_-])/i.test(trimmed);
|
|
19
|
+
const hasCommerceAction = /\b(buy|purchase|shop(?:ping)?(?:\s+for)?|order|add to cart|compare|recommend(?:ation)?s?|best)\b/i.test(trimmed);
|
|
20
|
+
if (!hasProductEntity && !(hasCommerceAction && hasPriceCue) && !(/\bproducts?\b/i.test(trimmed) && hasCommerceAction)) {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
let query = trimmed.replace(LEADING_PREFIX, "").trim();
|
|
24
|
+
query = query.replace(/\b(?:my\s+)?budget\s*(?:is|:)?\s+\$?\s*\d+(?:\.\d+)?/gi, "").replace(/\b(?:under|below|max|budget)\s+\$?\s*\d+(?:\.\d+)?/gi, "").replace(/\s+\bmy\s*$/i, "").trim();
|
|
25
|
+
return {
|
|
26
|
+
query: query || trimmed,
|
|
27
|
+
budget
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
const VISUAL_IDENTIFY = /^(what(?:'s| is) this|whats this|what is that|identify(?: this)?|what product|which product|find this)\b/i;
|
|
31
|
+
function shouldOpenShopFromHomeChat(text, fileCount, mode) {
|
|
32
|
+
if (mode === "build" || mode === "deep-search") return false;
|
|
33
|
+
const trimmed = text.trim();
|
|
34
|
+
if (extractShoppingIntentFromText(trimmed)) return true;
|
|
35
|
+
if (fileCount > 0 && (!trimmed || VISUAL_IDENTIFY.test(trimmed.replace(/[.!?]+$/g, "").trim()))) return true;
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
async function shouldRedirectToShop(text, fileCount, mode) {
|
|
39
|
+
if (mode === "build" || mode === "deep-search") return false;
|
|
40
|
+
try {
|
|
41
|
+
if (shouldOpenShopFromHomeChat(text, fileCount, mode)) return true;
|
|
42
|
+
} catch (e) {
|
|
43
|
+
}
|
|
44
|
+
const trimmed = text.trim();
|
|
45
|
+
if (!trimmed) return false;
|
|
46
|
+
try {
|
|
47
|
+
const [classified, shopping] = await Promise.all([classifyIntentViaBrain(trimmed, {
|
|
48
|
+
timeoutMs: 2e3
|
|
49
|
+
}), parseShoppingViaBrain(trimmed, {
|
|
50
|
+
timeoutMs: 2e3
|
|
51
|
+
})]);
|
|
52
|
+
if ((classified == null ? void 0 : classified.intent) === "shopping") return true;
|
|
53
|
+
if (shopping == null ? void 0 : shopping.query) return true;
|
|
54
|
+
} catch (e) {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
return false;
|
|
58
|
+
}export{extractShoppingIntentFromText,shouldOpenShopFromHomeChat,shouldRedirectToShop};//# sourceMappingURL=homeShoppingIntent.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"homeShoppingIntent.js","sources":["../../../../src/features/shopping/chat/homeShoppingIntent.ts"],"sourcesContent":["import { classifyIntentViaBrain, parseShoppingViaBrain } from '../../../services/brainQuickReply';\n\n/**\n * Same product-claim heuristic as web shopping `extractShoppingIntentFromText`.\n * Home and Chat use it so a shop ask opens Shop Native + Agent.\n */\n\nconst LEADING_PREFIX =\n /^(please\\s+)?(can you\\s+)?(help me\\s+)?(find|search for|shop for|buy|get|show me|recommend|compare)\\s+/i;\n\nfunction parseBudget(text: string): number | undefined {\n const patterns = [\n /\\b(?:under|below|max|budget(?:\\s+is)?)\\s+\\$?\\s*(\\d+(?:\\.\\d+)?)/i,\n /\\b(?:my\\s+)?budget\\s*(?:is|:)?\\s+\\$?\\s*(\\d+(?:\\.\\d+)?)/i,\n ];\n for (const pattern of patterns) {\n const match = text.match(pattern);\n if (match) {\n const value = Number.parseFloat(match[1]);\n if (Number.isFinite(value) && value > 0) return value;\n }\n }\n return undefined;\n}\n\nexport function extractShoppingIntentFromText(text: string): { query: string; budget?: number } | null {\n const trimmed = text.trim();\n if (trimmed.length < 4) return null;\n\n const budget = parseBudget(trimmed);\n const hasPriceCue = budget != null || /\\$\\s?\\d+/.test(trimmed) || /\\bunder\\s+\\d+/i.test(trimmed);\n\n const hasProductEntity =\n /(^|[^A-Za-z0-9/_-])(headphones?|earbuds?|ear\\s*buds?|laptop|notebook|computer|phone|smartphone|tablet|ipad|watch|smartwatch|camera|tv|television|monitor|keyboard|mouse|speaker|console|playstation|xbox|switch|shoes?|sneakers?|jacket|coat|backpack|bag|purse|wallet|gift|toy|game|furniture|desk|chair|sofa|mattress|appliance|blender|coffee maker|vacuum|router|modem|charger|cable|case|cover|skincare|serum|perfume|makeup|vitamin|protein|supplement|bike|bicycle|tent|camping|grill|bbq|string lights|electronics|gadget|device|accessory|accessories|iphone|airpods?)(?![A-Za-z0-9/_-])/i.test(\n trimmed,\n );\n\n const hasCommerceAction =\n /\\b(buy|purchase|shop(?:ping)?(?:\\s+for)?|order|add to cart|compare|recommend(?:ation)?s?|best)\\b/i.test(\n trimmed,\n );\n\n if (\n !hasProductEntity &&\n !(hasCommerceAction && hasPriceCue) &&\n !(/\\bproducts?\\b/i.test(trimmed) && hasCommerceAction)\n ) {\n return null;\n }\n\n let query = trimmed.replace(LEADING_PREFIX, '').trim();\n query = query\n .replace(/\\b(?:my\\s+)?budget\\s*(?:is|:)?\\s+\\$?\\s*\\d+(?:\\.\\d+)?/gi, '')\n .replace(/\\b(?:under|below|max|budget)\\s+\\$?\\s*\\d+(?:\\.\\d+)?/gi, '')\n .replace(/\\s+\\bmy\\s*$/i, '')\n .trim();\n\n return { query: query || trimmed, budget };\n}\n\nconst VISUAL_IDENTIFY =\n /^(what(?:'s| is) this|whats this|what is that|identify(?: this)?|what product|which product|find this)\\b/i;\n\nexport function shouldOpenShopFromHomeChat(\n text: string,\n fileCount: number,\n mode: 'chat' | 'deep-search' | 'build',\n): boolean {\n if (mode === 'build' || mode === 'deep-search') return false;\n const trimmed = text.trim();\n if (extractShoppingIntentFromText(trimmed)) return true;\n if (fileCount > 0 && (!trimmed || VISUAL_IDENTIFY.test(trimmed.replace(/[.!?]+$/g, '').trim()))) return true;\n return false;\n}\n\n/**\n * Agentic shop open: local product claim first, then cdecli yantra-brain\n * (classify + shopping parse) — same proxy web uses.\n */\nexport async function shouldRedirectToShop(\n text: string,\n fileCount: number,\n mode: 'chat' | 'deep-search' | 'build',\n): Promise<boolean> {\n if (mode === 'build' || mode === 'deep-search') return false;\n try {\n if (shouldOpenShopFromHomeChat(text, fileCount, mode)) return true;\n } catch {\n /* fall through to brain */\n }\n const trimmed = text.trim();\n if (!trimmed) return false;\n try {\n const [classified, shopping] = await Promise.all([\n classifyIntentViaBrain(trimmed, { timeoutMs: 2000 }),\n parseShoppingViaBrain(trimmed, { timeoutMs: 2000 }),\n ]);\n if (classified?.intent === 'shopping') return true;\n if (shopping?.query) return true;\n } catch {\n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A,CAAI,CAAC,sBAAA,CAAuB,OAAS,EAAA;AAAA,MAChF,SAAW,EAAA;AAAA,KACZ,CAAG,EAAA,qBAAA,CAAsB,OAAS,EAAA;AAAA,MACjC,SAAW,EAAA;AAAA,KACZ,CAAC,CAAC,CAAA;AACH,IAAI,IAAA,CAAA,UAAA,IAAA,IAAA,GAAA,KAAA,CAAA,GAAA,UAAA,CAAY,MAAW,MAAA,UAAA,EAAmB,OAAA,IAAA;AAC9C,IAAI,IAAA,QAAA,IAAA,IAAA,GAAA,KAAA,CAAA,GAAA,QAAA,CAAU,OAAc,OAAA,IAAA;AAAA,GACtB,CAAA,OAAA,CAAA,EAAA;AACN,IAAO,OAAA,KAAA;AAAA;AAET,EAAO,OAAA,KAAA;AACT"}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import {StackActions,CommonActions}from'@react-navigation/native';var __defProp = Object.defineProperty;
|
|
2
|
+
var __defProps = Object.defineProperties;
|
|
3
|
+
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
|
|
4
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
7
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
8
|
+
var __spreadValues = (a, b) => {
|
|
9
|
+
for (var prop in b || (b = {}))
|
|
10
|
+
if (__hasOwnProp.call(b, prop))
|
|
11
|
+
__defNormalProp(a, prop, b[prop]);
|
|
12
|
+
if (__getOwnPropSymbols)
|
|
13
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
14
|
+
if (__propIsEnum.call(b, prop))
|
|
15
|
+
__defNormalProp(a, prop, b[prop]);
|
|
16
|
+
}
|
|
17
|
+
return a;
|
|
18
|
+
};
|
|
19
|
+
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
20
|
+
const SHOP_ROUTE = "MainStack.ShoppingNative";
|
|
21
|
+
function shopHandoffParams(opts) {
|
|
22
|
+
var _a;
|
|
23
|
+
const params = __spreadProps(__spreadValues({}, opts.orgName ? {
|
|
24
|
+
orgName: opts.orgName
|
|
25
|
+
} : {}), {
|
|
26
|
+
initialAgentQuery: opts.query,
|
|
27
|
+
openAgent: true
|
|
28
|
+
});
|
|
29
|
+
if ((_a = opts.files) == null ? void 0 : _a.length) params.initialAgentAttachments = opts.files;
|
|
30
|
+
return params;
|
|
31
|
+
}
|
|
32
|
+
function isBareChatRoute(name) {
|
|
33
|
+
return /(^|\.)Chat$/.test(name);
|
|
34
|
+
}
|
|
35
|
+
function replaceWithShopNative(navigation, params) {
|
|
36
|
+
if (typeof navigation.replace === "function") {
|
|
37
|
+
navigation.replace(SHOP_ROUTE, params);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
navigation.dispatch(StackActions.replace(SHOP_ROUTE, params));
|
|
41
|
+
}
|
|
42
|
+
function pushShopNative(navigation, params) {
|
|
43
|
+
navigation.dispatch(CommonActions.navigate({
|
|
44
|
+
name: SHOP_ROUTE,
|
|
45
|
+
params
|
|
46
|
+
}));
|
|
47
|
+
}
|
|
48
|
+
function openShopFromHome(navigation, params) {
|
|
49
|
+
navigation.dispatch((state) => {
|
|
50
|
+
const kept = state.routes.filter((route) => !isBareChatRoute(route.name) && !/(^|\.)ShoppingNative$/.test(route.name));
|
|
51
|
+
const routes = [...kept, {
|
|
52
|
+
name: SHOP_ROUTE,
|
|
53
|
+
params
|
|
54
|
+
}];
|
|
55
|
+
return CommonActions.reset(__spreadProps(__spreadValues({}, state), {
|
|
56
|
+
routes,
|
|
57
|
+
index: routes.length - 1
|
|
58
|
+
}));
|
|
59
|
+
});
|
|
60
|
+
}export{isBareChatRoute,openShopFromHome,pushShopNative,replaceWithShopNative,shopHandoffParams};//# sourceMappingURL=openShopNative.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openShopNative.js","sources":["../../../../src/features/shopping/chat/openShopNative.ts"],"sourcesContent":["import { CommonActions, StackActions } from '@react-navigation/native';\nimport type { MessageAttachment } from '../../../hooks/useChatStream';\n\nconst SHOP_ROUTE = 'MainStack.ShoppingNative';\n\nexport function shopHandoffParams(opts: {\n orgName?: string | null;\n query: string;\n files?: MessageAttachment[] | null;\n}): Record<string, unknown> {\n const params: Record<string, unknown> = {\n ...(opts.orgName ? { orgName: opts.orgName } : {}),\n initialAgentQuery: opts.query,\n openAgent: true,\n };\n if (opts.files?.length) params.initialAgentAttachments = opts.files;\n return params;\n}\n\nexport function isBareChatRoute(name: string): boolean {\n return /(^|\\.)Chat$/.test(name);\n}\n\n/** From Chat: swap Chat for Shop so Back returns to Home, not an empty thread. */\nexport function replaceWithShopNative(\n navigation: { dispatch: (action: unknown) => void; replace?: (name: string, params?: object) => void },\n params: Record<string, unknown>,\n) {\n if (typeof navigation.replace === 'function') {\n navigation.replace(SHOP_ROUTE, params);\n return;\n }\n navigation.dispatch(StackActions.replace(SHOP_ROUTE, params));\n}\n\n/** Push Shop on top of the current screen (keeps an existing Chat thread). */\nexport function pushShopNative(navigation: { dispatch: (action: unknown) => void }, params: Record<string, unknown>) {\n navigation.dispatch(CommonActions.navigate({ name: SHOP_ROUTE, params }));\n}\n\n/**\n * From Home: open Shop and drop leftover Chat routes so Back is Home,\n * not a blank Chat that never received the shopping message.\n */\nexport function openShopFromHome(navigation: { dispatch: (action: unknown) => void }, params: Record<string, unknown>) {\n navigation.dispatch((state: { routes: Array<{ name: string; params?: object }>; [key: string]: unknown }) => {\n const kept = state.routes.filter(\n (route) => !isBareChatRoute(route.name) && !/(^|\\.)ShoppingNative$/.test(route.name),\n );\n const routes = [...kept, { name: SHOP_ROUTE, params }];\n return CommonActions.reset({\n ...state,\n routes,\n index: routes.length - 1,\n });\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;AAEA,MAAM,UAAa,GAAA,0B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wB,IAAK,CAAA,KAAA,CAAM,IAAI,CAAC,CAAA;AACnH,IAAM,MAAA,MAAA,GAAS,CAAC,GAAG,IAAM,EAAA;AAAA,MACvB,IAAM,EAAA,UAAA;AAAA,MACN;AAAA,KACD,CAAA;AACD,IAAO,OAAA,aAAA,CAAc,KAAM,CAAA,aAAA,CAAA,cAAA,CAAA,EAAA,EACtB,KADsB,CAAA,EAAA;AAAA,MAEzB,MAAA;AAAA,MACA,KAAA,EAAO,OAAO,MAAS,GAAA;AAAA,KACxB,CAAA,CAAA;AAAA,GACF,CAAA;AACH"}
|
|
@@ -201,14 +201,16 @@ function useCdecliChannel(isConnected, accountId, channelId, callbacks, model, s
|
|
|
201
201
|
lastRunIdRef.current = null;
|
|
202
202
|
quickReplyShownRef.current = false;
|
|
203
203
|
const turn = ++turnSeqRef.current;
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
204
|
+
if (media.length === 0) {
|
|
205
|
+
void quickReplyViaBrain(text).then((answer) => {
|
|
206
|
+
var _a2, _b;
|
|
207
|
+
if (!answer) return;
|
|
208
|
+
if (turnSeqRef.current !== turn || !pendingRef.current) return;
|
|
209
|
+
if (hasReceivedDeltasRef.current || streamCompletedRef.current) return;
|
|
210
|
+
quickReplyShownRef.current = true;
|
|
211
|
+
(_b = (_a2 = cbRef.current).onQuickReply) == null ? void 0 : _b.call(_a2, answer);
|
|
212
|
+
});
|
|
213
|
+
}
|
|
212
214
|
try {
|
|
213
215
|
const result = await sendMutation({
|
|
214
216
|
variables: {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useCdecliChannel.js","sources":["../../src/hooks/useCdecliChannel.ts"],"sourcesContent":["/**\n * useCdecliChannel — wires the cdecli-serve messenger-gateway channel into the mobile chat UI.\n *\n * Kept in sync with `packages-modules/account/browser/src/hooks/useCdecliChannel.ts`.\n * When the CDeCLI channel is connected:\n * - `sendMessage(text, chatId, media)` calls `gatewaySendMessage`\n * - `MessengerStreamDelta` subscription delivers streaming chunks via `onChunk`\n * - `GatewayInboundMessageByChannel` delivers the final reply via `onComplete`\n */\n\nimport { useCallback, useEffect, useRef } from 'react';\nimport { AppState } from 'react-native';\nimport { gql, useApolloClient } from '@apollo/client';\nimport { quickReplyViaBrain } from '../services/brainQuickReply';\nimport {\n useGatewaySendMessageMutation,\n useGatewayInboundMessageByChannelSubscription,\n useMessengerStreamDeltaSubscription,\n} from 'common/graphql';\n\n/**\n * Resume snapshot for a channel's ACTIVE stream (server-owned).\n * Same document as browser `useCdecliChannel` — older backends error and we skip.\n */\nconst MESSENGER_ACTIVE_STREAM_QUERY = gql`\n query MessengerActiveStreamResume($channelId: String!) {\n messengerActiveStream(channelId: $channelId) {\n runId\n seq\n channelId\n text\n isFinal\n }\n }\n`;\n\nfunction stripModelCostHeader(content: string): string {\n const normalized = content.replace(/\\r\\n/g, '\\n');\n return normalized.replace(\n /^\\s*(?:[^\\w\\n]+\\s*)?[a-z0-9][a-z0-9._-]*\\s*\\(\\s*\\$[\\d.]+\\s*\\/\\s*MTok\\s+in\\s*\\)\\s*\\n+/i,\n '',\n );\n}\n\n// `error?: undefined` on the success arm keeps `result.error` reachable on the\n// union: with strictNullChecks off (repo-wide), TS will not narrow the\n// discriminated union after an `if (result.ok) continue`.\nexport type SteerResult = { ok: true; error?: undefined } | { ok: false; error: string };\n\nexport interface CdecliChannelCallbacks {\n onChunk: (text: string) => void;\n /**\n * A fast provisional answer from `yantra-brain`, painted while the real agent\n * is still bootstrapping. Distinct from onChunk on purpose: the UI shows it as\n * the reply-so-far and REPLACES it the moment real deltas arrive, so the brain\n * fills the silence without ever stacking on top of the agent's answer.\n */\n onQuickReply?: (text: string) => void;\n onComplete: (text: string) => void;\n onError: (error: string) => void;\n}\n\nexport function isNoActiveSessionError(message: string): boolean {\n return /no active session/i.test(message);\n}\n\n/**\n * Idle window, not a total budget. The timer is re-armed on every streamed\n * delta (a turn that is actively streaming is not stuck), and paused while the\n * app is backgrounded (iOS suspends the WebSocket + throttles JS timers, so a\n * wall-clock timer would otherwise fire a false \"did not respond\" the instant\n * the app returns to the foreground). It fires only after this much CONTINUOUS\n * silence with the app in the foreground.\n */\nconst CDECLI_RESPONSE_TIMEOUT_MS = 300_000;\n\nexport function useCdecliChannel(\n isConnected: boolean,\n accountId: string,\n channelId: string | undefined,\n callbacks: CdecliChannelCallbacks,\n model?: string,\n skill?: string,\n) {\n const [sendMutation] = useGatewaySendMessageMutation();\n const cbRef = useRef(callbacks);\n cbRef.current = callbacks;\n\n const pendingRef = useRef<{ text: string; sentAt: number } | null>(null);\n const hasReceivedDeltasRef = useRef(false);\n const reconnectedStreamRef = useRef(false);\n const streamCompletedRef = useRef(false);\n const accumulatedLenRef = useRef(0);\n const lastRunIdRef = useRef<string | null>(null);\n const apolloClient = useApolloClient();\n const seededChannelRef = useRef<string | null>(null);\n\n /**\n * Forward newly-accumulated stream text. Shared by live deltas and the\n * mount-time resume seed so neither gaps nor double-delivery happen when\n * the user leaves Chat for history and comes back mid-turn.\n */\n const ingestAccumulatedText = useCallback((accumulated: string) => {\n const fullText = stripModelCostHeader(accumulated);\n const newChunk = fullText.substring(accumulatedLenRef.current);\n accumulatedLenRef.current = fullText.length;\n if (newChunk) cbRef.current.onChunk(newChunk);\n }, []);\n // True while a brain quick-reply is what the user is looking at. The first\n // real delta clears the provisional text before painting, so the agent's\n // answer replaces the brain's rather than appending to it.\n const quickReplyShownRef = useRef(false);\n // Identity of the current turn for the brain race. A counter, not a\n // timestamp: two sends can share a millisecond, and a timestamp would then\n // let a brain answer for a superseded turn paint over the live one.\n const turnSeqRef = useRef(0);\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const streamSkip = !channelId;\n const streamChannelId = channelId || accountId;\n\n /** (Re)start the idle timer for the in-flight turn. No-op if none pending. */\n const armTimeout = useCallback(() => {\n if (timeoutRef.current) clearTimeout(timeoutRef.current);\n if (!pendingRef.current) {\n timeoutRef.current = null;\n return;\n }\n timeoutRef.current = setTimeout(() => {\n if (pendingRef.current) {\n pendingRef.current = null;\n hasReceivedDeltasRef.current = false;\n timeoutRef.current = null;\n cbRef.current.onError(\n 'CDeCLI agent did not respond within 300 seconds. The query may still be processing.',\n );\n }\n }, CDECLI_RESPONSE_TIMEOUT_MS);\n }, []);\n\n // Pause the idle timer in the background, re-arm fresh on return. iOS\n // suspends the streaming WebSocket and throttles JS timers while\n // backgrounded, so a running wall-clock timer either fires against a\n // connection that cannot deliver or fires the instant the app resumes -\n // both read to the user as a spurious timeout. On resume the subscription\n // reconnects and redelivers the final message if the turn finished while\n // away; if it is still pending, the fresh window starts counting from the\n // foreground.\n useEffect(() => {\n const sub = AppState.addEventListener('change', (next) => {\n if (next === 'active') {\n if (pendingRef.current && !streamCompletedRef.current) armTimeout();\n } else if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n });\n return () => sub.remove();\n }, [armTimeout]);\n\n useMessengerStreamDeltaSubscription({\n variables: { channelId: streamChannelId },\n skip: streamSkip,\n onData: ({ data }) => {\n const delta = data?.data?.messengerStreamDelta;\n if (!delta) return;\n\n if (delta.isFinal) return;\n\n if (delta.runId && delta.runId !== lastRunIdRef.current) {\n accumulatedLenRef.current = 0;\n }\n if (delta.runId) lastRunIdRef.current = delta.runId;\n\n if (streamCompletedRef.current) return;\n\n // Pick up a turn that kept running after the user left Chat for history.\n if (!pendingRef.current) {\n if (!reconnectedStreamRef.current) {\n reconnectedStreamRef.current = true;\n accumulatedLenRef.current = 0;\n }\n }\n\n if (quickReplyShownRef.current) {\n // The real answer has started: clear the brain's provisional reply\n // before the first chunk lands, so it is replaced, not appended to.\n quickReplyShownRef.current = false;\n cbRef.current.onQuickReply?.('');\n }\n hasReceivedDeltasRef.current = true;\n\n // Heartbeat: a turn that is actively streaming is not stuck, so\n // push the idle deadline out on every delta. The timer now fires\n // only after real silence, never mid-stream on a long query.\n armTimeout();\n\n ingestAccumulatedText(delta.text ?? '');\n },\n onError: (err) => {\n console.error('[useCdecliChannel] stream delta subscription error:', err);\n },\n });\n\n // Seed the in-flight reply when Chat remounts (history → chat) mid-stream.\n useEffect(() => {\n if (streamSkip || !streamChannelId) return undefined;\n if (seededChannelRef.current === streamChannelId) return undefined;\n seededChannelRef.current = streamChannelId;\n accumulatedLenRef.current = 0;\n streamCompletedRef.current = false;\n reconnectedStreamRef.current = false;\n lastRunIdRef.current = null;\n\n let cancelled = false;\n apolloClient\n .query({\n query: MESSENGER_ACTIVE_STREAM_QUERY,\n variables: { channelId: streamChannelId },\n fetchPolicy: 'network-only',\n errorPolicy: 'all',\n })\n .then(({ data }) => {\n if (cancelled) return;\n const snapshot = data?.messengerActiveStream as\n | { runId?: string; text?: string; isFinal?: boolean }\n | null\n | undefined;\n if (!snapshot?.text || snapshot.isFinal) return;\n if (streamCompletedRef.current) return;\n if (accumulatedLenRef.current > 0) return;\n reconnectedStreamRef.current = true;\n hasReceivedDeltasRef.current = true;\n if (snapshot.runId) lastRunIdRef.current = snapshot.runId;\n ingestAccumulatedText(snapshot.text);\n })\n .catch(() => {\n /* pre-#701 backend or transient failure — live deltas self-heal */\n });\n return () => {\n cancelled = true;\n };\n }, [streamChannelId, streamSkip, apolloClient, ingestAccumulatedText]);\n\n useGatewayInboundMessageByChannelSubscription({\n variables: { channelId: streamChannelId },\n skip: !isConnected || streamSkip,\n onData: ({ data }) => {\n const msg = data?.data?.gatewayInboundMessageByChannel;\n if (!msg?.text) return;\n const sanitizedText = stripModelCostHeader(msg.text);\n\n if (!hasReceivedDeltasRef.current) {\n if (quickReplyShownRef.current) {\n quickReplyShownRef.current = false;\n cbRef.current.onQuickReply?.('');\n }\n cbRef.current.onChunk(sanitizedText);\n }\n\n cbRef.current.onComplete(sanitizedText);\n pendingRef.current = null;\n hasReceivedDeltasRef.current = false;\n reconnectedStreamRef.current = false;\n streamCompletedRef.current = true;\n accumulatedLenRef.current = 0;\n lastRunIdRef.current = null;\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n },\n onError: (err) => {\n console.error('[useCdecliChannel] subscription error:', err);\n cbRef.current.onError(err.message || 'CDeCLI subscription error');\n },\n });\n\n const sendMessage = useCallback(\n async (\n text: string,\n chatId = 'messenger',\n media: Array<{ type: string; url: string; data?: string; mimeType?: string; filename?: string }> = [],\n ): Promise<boolean> => {\n if (!isConnected) return false;\n\n pendingRef.current = { text, sentAt: Date.now() };\n hasReceivedDeltasRef.current = false;\n reconnectedStreamRef.current = false;\n streamCompletedRef.current = false;\n accumulatedLenRef.current = 0;\n lastRunIdRef.current = null;\n quickReplyShownRef.current = false;\n\n // Ask the brain the same question in parallel with the send. On a cold\n // first turn the agent can take minutes before its first delta; the\n // brain answers in seconds. Its reply is painted only if nothing real\n // has arrived yet, and is replaced in place the moment it does. Fire\n // and forget: a brain failure changes nothing about the turn.\n const turn = ++turnSeqRef.current;\n void quickReplyViaBrain(text).then((answer) => {\n if (!answer) return;\n // Stale if the turn moved on, or the agent already spoke.\n if (turnSeqRef.current !== turn || !pendingRef.current) return;\n if (hasReceivedDeltasRef.current || streamCompletedRef.current) return;\n quickReplyShownRef.current = true;\n cbRef.current.onQuickReply?.(answer);\n });\n\n try {\n const result = await sendMutation({\n variables: {\n input: {\n channelType: 'cdecli-serve',\n accountId,\n chatId,\n text,\n ...(media.length > 0 ? { media: media as never } : {}),\n ...(model || skill\n ? { metadata: { ...(model && { model }), ...(skill && { skill }) } }\n : {}),\n },\n },\n });\n\n const payload = result.data?.gatewaySendMessage;\n if (!payload?.success) {\n const errMsg = payload?.error || 'CDeCLI send failed';\n cbRef.current.onError(errMsg);\n pendingRef.current = null;\n return false;\n }\n\n armTimeout();\n\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n cbRef.current.onError(msg);\n pendingRef.current = null;\n return false;\n }\n },\n [isConnected, accountId, channelId, sendMutation, model, skill, armTimeout],\n );\n\n useEffect(\n () => () => {\n pendingRef.current = null;\n hasReceivedDeltasRef.current = false;\n reconnectedStreamRef.current = false;\n streamCompletedRef.current = false;\n accumulatedLenRef.current = 0;\n lastRunIdRef.current = null;\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n },\n [],\n );\n\n /**\n * Inject a follow-up into the turn that is currently streaming.\n * Same `gatewaySendMessage` mutation with `metadata.steer = true` (browser\n * `useCdecliChannel.steer`). Do NOT reset streaming refs: the existing\n * delta subscription must keep running.\n *\n * \"Cannot steer: no active session\" is an expected race before cdecli has\n * started the turn. Callers should queue and retry; do not `console.error`\n * (that pops the RN LogBox and looks like a crash).\n */\n const steer = useCallback(\n async (text: string, chatId = 'messenger'): Promise<SteerResult> => {\n if (!isConnected) return { ok: false, error: 'CDeCLI is not connected.' };\n try {\n const result = await sendMutation({\n variables: {\n input: {\n channelType: 'cdecli-serve',\n accountId,\n chatId,\n text,\n metadata: { steer: true },\n },\n },\n });\n const payload = result.data?.gatewaySendMessage;\n if (!payload?.success) {\n const errMsg = payload?.error || 'CDeCLI steer failed';\n if (!isNoActiveSessionError(errMsg)) {\n console.warn('[useCdecliChannel] steer failed:', errMsg);\n }\n return { ok: false, error: errMsg };\n }\n return { ok: true };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.warn('[useCdecliChannel] steer mutation error:', msg);\n return { ok: false, error: msg };\n }\n },\n [isConnected, accountId, sendMutation],\n );\n\n /**\n * Abort the in-flight turn. `metadata.cancel = true` maps to\n * `POST /v1/chat/cancel` on cdecli-serve (browser parity).\n */\n const cancel = useCallback(\n async (chatId = 'messenger'): Promise<boolean> => {\n if (!isConnected) return false;\n pendingRef.current = null;\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n try {\n const result = await sendMutation({\n variables: {\n input: {\n channelType: 'cdecli-serve',\n accountId,\n chatId,\n text: '',\n metadata: { cancel: true },\n },\n },\n });\n const payload = result.data?.gatewaySendMessage;\n if (!payload?.success) {\n console.error('[useCdecliChannel] cancel failed:', payload?.error || 'CDeCLI cancel failed');\n return false;\n }\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error('[useCdecliChannel] cancel mutation error:', msg);\n return false;\n }\n },\n [isConnected, accountId, sendMutation],\n );\n\n return { sendMessage, steer, cancel };\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;AAoBA,MAAM,6BAAgC,GAAA,GAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AAWtC,SAAS,qBAAqB,OAAyB,EAAA;AACrD,EAAA,MAAM,UAAa,GAAA,OAAA,CAAQ,OAAQ,CAAA,OAAA,EAAS,IAAI,CAAA;AAChD,EAAO,OAAA,UAAA,CAAW,OAAQ,CAAA,uFAAA,EAAyF,EAAE,CAAA;AACvH;AAwBO,SAAS,uBAAuB,OAA0B,EAAA;AAC/D,EAAO,OAAA,oBAAA,CAAqB,KAAK,OAAO,CAAA;AAC1C;AAUA,MAAM,0BAA6B,GAAA,GAAA;AAC5B,SAAS,iBAAiB,WAAsB,EAAA,SAAA,EAAmB,SAA+B,EAAA,SAAA,EAAmC,OAAgB,KAAgB,EAAA;AAC1K,EAAM,MAAA,CAAC,YAAY,CAAA,GAAI,6BAA8B,EAAA;AACrD,EAAM,MAAA,KAAA,GAAQ,OAAO,SAAS,CAAA;AAC9B,EAAA,KAAA,CAAM,OAAU,GAAA,SAAA;AAChB,EAAM,MAAA,UAAA,GAAa,OAGT,IAAI,CAAA;AACd,EAAM,MAAA,oBAAA,GAAuB,OAAO,KAAK,CAAA;AACzC,EAAM,MAAA,oBAAA,GAAuB,OAAO,KAAK,CAAA;AACzC,EAAM,MAAA,kBAAA,GAAqB,OAAO,KAAK,CAAA;AACvC,EAAM,MAAA,iBAAA,GAAoB,OAAO,CAAC,CAAA;AAClC,EAAM,MAAA,YAAA,GAAe,OAAsB,IAAI,CAAA;AAC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A,KAAA;AAAA;AAET,MAAO,OAAA,IAAA;AAAA,aACA,GAAK,EAAA;AACZ,MAAA,MAAM,MAAM,GAAe,YAAA,KAAA,GAAQ,GAAI,CAAA,OAAA,GAAU,OAAO,GAAG,CAAA;AAC3D,MAAQ,OAAA,CAAA,KAAA,CAAM,6CAA6C,GAAG,CAAA;AAC9D,MAAO,OAAA,KAAA;AAAA;AACT,GACC,EAAA,CAAC,WAAa,EAAA,SAAA,EAAW,YAAY,CAAC,CAAA;AACzC,EAAO,OAAA;AAAA,IACL,WAAA;AAAA,IACA,KAAA;AAAA,IACA;AAAA,GACF;AACF"}
|
|
1
|
+
{"version":3,"file":"useCdecliChannel.js","sources":["../../src/hooks/useCdecliChannel.ts"],"sourcesContent":["/**\n * useCdecliChannel — wires the cdecli-serve messenger-gateway channel into the mobile chat UI.\n *\n * Kept in sync with `packages-modules/account/browser/src/hooks/useCdecliChannel.ts`.\n * When the CDeCLI channel is connected:\n * - `sendMessage(text, chatId, media)` calls `gatewaySendMessage`\n * - `MessengerStreamDelta` subscription delivers streaming chunks via `onChunk`\n * - `GatewayInboundMessageByChannel` delivers the final reply via `onComplete`\n */\n\nimport { useCallback, useEffect, useRef } from 'react';\nimport { AppState } from 'react-native';\nimport { gql, useApolloClient } from '@apollo/client';\nimport { quickReplyViaBrain } from '../services/brainQuickReply';\nimport {\n useGatewaySendMessageMutation,\n useGatewayInboundMessageByChannelSubscription,\n useMessengerStreamDeltaSubscription,\n} from 'common/graphql';\n\n/**\n * Resume snapshot for a channel's ACTIVE stream (server-owned).\n * Same document as browser `useCdecliChannel` — older backends error and we skip.\n */\nconst MESSENGER_ACTIVE_STREAM_QUERY = gql`\n query MessengerActiveStreamResume($channelId: String!) {\n messengerActiveStream(channelId: $channelId) {\n runId\n seq\n channelId\n text\n isFinal\n }\n }\n`;\n\nfunction stripModelCostHeader(content: string): string {\n const normalized = content.replace(/\\r\\n/g, '\\n');\n return normalized.replace(\n /^\\s*(?:[^\\w\\n]+\\s*)?[a-z0-9][a-z0-9._-]*\\s*\\(\\s*\\$[\\d.]+\\s*\\/\\s*MTok\\s+in\\s*\\)\\s*\\n+/i,\n '',\n );\n}\n\n// `error?: undefined` on the success arm keeps `result.error` reachable on the\n// union: with strictNullChecks off (repo-wide), TS will not narrow the\n// discriminated union after an `if (result.ok) continue`.\nexport type SteerResult = { ok: true; error?: undefined } | { ok: false; error: string };\n\nexport interface CdecliChannelCallbacks {\n onChunk: (text: string) => void;\n /**\n * A fast provisional answer from `yantra-brain`, painted while the real agent\n * is still bootstrapping. Distinct from onChunk on purpose: the UI shows it as\n * the reply-so-far and REPLACES it the moment real deltas arrive, so the brain\n * fills the silence without ever stacking on top of the agent's answer.\n */\n onQuickReply?: (text: string) => void;\n onComplete: (text: string) => void;\n onError: (error: string) => void;\n}\n\nexport function isNoActiveSessionError(message: string): boolean {\n return /no active session/i.test(message);\n}\n\n/**\n * Idle window, not a total budget. The timer is re-armed on every streamed\n * delta (a turn that is actively streaming is not stuck), and paused while the\n * app is backgrounded (iOS suspends the WebSocket + throttles JS timers, so a\n * wall-clock timer would otherwise fire a false \"did not respond\" the instant\n * the app returns to the foreground). It fires only after this much CONTINUOUS\n * silence with the app in the foreground.\n */\nconst CDECLI_RESPONSE_TIMEOUT_MS = 300_000;\n\nexport function useCdecliChannel(\n isConnected: boolean,\n accountId: string,\n channelId: string | undefined,\n callbacks: CdecliChannelCallbacks,\n model?: string,\n skill?: string,\n) {\n const [sendMutation] = useGatewaySendMessageMutation();\n const cbRef = useRef(callbacks);\n cbRef.current = callbacks;\n\n const pendingRef = useRef<{ text: string; sentAt: number } | null>(null);\n const hasReceivedDeltasRef = useRef(false);\n const reconnectedStreamRef = useRef(false);\n const streamCompletedRef = useRef(false);\n const accumulatedLenRef = useRef(0);\n const lastRunIdRef = useRef<string | null>(null);\n const apolloClient = useApolloClient();\n const seededChannelRef = useRef<string | null>(null);\n\n /**\n * Forward newly-accumulated stream text. Shared by live deltas and the\n * mount-time resume seed so neither gaps nor double-delivery happen when\n * the user leaves Chat for history and comes back mid-turn.\n */\n const ingestAccumulatedText = useCallback((accumulated: string) => {\n const fullText = stripModelCostHeader(accumulated);\n const newChunk = fullText.substring(accumulatedLenRef.current);\n accumulatedLenRef.current = fullText.length;\n if (newChunk) cbRef.current.onChunk(newChunk);\n }, []);\n // True while a brain quick-reply is what the user is looking at. The first\n // real delta clears the provisional text before painting, so the agent's\n // answer replaces the brain's rather than appending to it.\n const quickReplyShownRef = useRef(false);\n // Identity of the current turn for the brain race. A counter, not a\n // timestamp: two sends can share a millisecond, and a timestamp would then\n // let a brain answer for a superseded turn paint over the live one.\n const turnSeqRef = useRef(0);\n const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const streamSkip = !channelId;\n const streamChannelId = channelId || accountId;\n\n /** (Re)start the idle timer for the in-flight turn. No-op if none pending. */\n const armTimeout = useCallback(() => {\n if (timeoutRef.current) clearTimeout(timeoutRef.current);\n if (!pendingRef.current) {\n timeoutRef.current = null;\n return;\n }\n timeoutRef.current = setTimeout(() => {\n if (pendingRef.current) {\n pendingRef.current = null;\n hasReceivedDeltasRef.current = false;\n timeoutRef.current = null;\n cbRef.current.onError(\n 'CDeCLI agent did not respond within 300 seconds. The query may still be processing.',\n );\n }\n }, CDECLI_RESPONSE_TIMEOUT_MS);\n }, []);\n\n // Pause the idle timer in the background, re-arm fresh on return. iOS\n // suspends the streaming WebSocket and throttles JS timers while\n // backgrounded, so a running wall-clock timer either fires against a\n // connection that cannot deliver or fires the instant the app resumes -\n // both read to the user as a spurious timeout. On resume the subscription\n // reconnects and redelivers the final message if the turn finished while\n // away; if it is still pending, the fresh window starts counting from the\n // foreground.\n useEffect(() => {\n const sub = AppState.addEventListener('change', (next) => {\n if (next === 'active') {\n if (pendingRef.current && !streamCompletedRef.current) armTimeout();\n } else if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n });\n return () => sub.remove();\n }, [armTimeout]);\n\n useMessengerStreamDeltaSubscription({\n variables: { channelId: streamChannelId },\n skip: streamSkip,\n onData: ({ data }) => {\n const delta = data?.data?.messengerStreamDelta;\n if (!delta) return;\n\n if (delta.isFinal) return;\n\n if (delta.runId && delta.runId !== lastRunIdRef.current) {\n accumulatedLenRef.current = 0;\n }\n if (delta.runId) lastRunIdRef.current = delta.runId;\n\n if (streamCompletedRef.current) return;\n\n // Pick up a turn that kept running after the user left Chat for history.\n if (!pendingRef.current) {\n if (!reconnectedStreamRef.current) {\n reconnectedStreamRef.current = true;\n accumulatedLenRef.current = 0;\n }\n }\n\n if (quickReplyShownRef.current) {\n // The real answer has started: clear the brain's provisional reply\n // before the first chunk lands, so it is replaced, not appended to.\n quickReplyShownRef.current = false;\n cbRef.current.onQuickReply?.('');\n }\n hasReceivedDeltasRef.current = true;\n\n // Heartbeat: a turn that is actively streaming is not stuck, so\n // push the idle deadline out on every delta. The timer now fires\n // only after real silence, never mid-stream on a long query.\n armTimeout();\n\n ingestAccumulatedText(delta.text ?? '');\n },\n onError: (err) => {\n console.error('[useCdecliChannel] stream delta subscription error:', err);\n },\n });\n\n // Seed the in-flight reply when Chat remounts (history → chat) mid-stream.\n useEffect(() => {\n if (streamSkip || !streamChannelId) return undefined;\n if (seededChannelRef.current === streamChannelId) return undefined;\n seededChannelRef.current = streamChannelId;\n accumulatedLenRef.current = 0;\n streamCompletedRef.current = false;\n reconnectedStreamRef.current = false;\n lastRunIdRef.current = null;\n\n let cancelled = false;\n apolloClient\n .query({\n query: MESSENGER_ACTIVE_STREAM_QUERY,\n variables: { channelId: streamChannelId },\n fetchPolicy: 'network-only',\n errorPolicy: 'all',\n })\n .then(({ data }) => {\n if (cancelled) return;\n const snapshot = data?.messengerActiveStream as\n | { runId?: string; text?: string; isFinal?: boolean }\n | null\n | undefined;\n if (!snapshot?.text || snapshot.isFinal) return;\n if (streamCompletedRef.current) return;\n if (accumulatedLenRef.current > 0) return;\n reconnectedStreamRef.current = true;\n hasReceivedDeltasRef.current = true;\n if (snapshot.runId) lastRunIdRef.current = snapshot.runId;\n ingestAccumulatedText(snapshot.text);\n })\n .catch(() => {\n /* pre-#701 backend or transient failure — live deltas self-heal */\n });\n return () => {\n cancelled = true;\n };\n }, [streamChannelId, streamSkip, apolloClient, ingestAccumulatedText]);\n\n useGatewayInboundMessageByChannelSubscription({\n variables: { channelId: streamChannelId },\n skip: !isConnected || streamSkip,\n onData: ({ data }) => {\n const msg = data?.data?.gatewayInboundMessageByChannel;\n if (!msg?.text) return;\n const sanitizedText = stripModelCostHeader(msg.text);\n\n if (!hasReceivedDeltasRef.current) {\n if (quickReplyShownRef.current) {\n quickReplyShownRef.current = false;\n cbRef.current.onQuickReply?.('');\n }\n cbRef.current.onChunk(sanitizedText);\n }\n\n cbRef.current.onComplete(sanitizedText);\n pendingRef.current = null;\n hasReceivedDeltasRef.current = false;\n reconnectedStreamRef.current = false;\n streamCompletedRef.current = true;\n accumulatedLenRef.current = 0;\n lastRunIdRef.current = null;\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n },\n onError: (err) => {\n console.error('[useCdecliChannel] subscription error:', err);\n cbRef.current.onError(err.message || 'CDeCLI subscription error');\n },\n });\n\n const sendMessage = useCallback(\n async (\n text: string,\n chatId = 'messenger',\n media: Array<{ type: string; url: string; data?: string; mimeType?: string; filename?: string }> = [],\n ): Promise<boolean> => {\n if (!isConnected) return false;\n\n pendingRef.current = { text, sentAt: Date.now() };\n hasReceivedDeltasRef.current = false;\n reconnectedStreamRef.current = false;\n streamCompletedRef.current = false;\n accumulatedLenRef.current = 0;\n lastRunIdRef.current = null;\n quickReplyShownRef.current = false;\n\n // Ask the brain the same question in parallel with the send. On a cold\n // first turn the agent can take minutes before its first delta; the\n // brain answers in seconds. Its reply is painted only if nothing real\n // has arrived yet, and is replaced in place the moment it does. Fire\n // and forget: a brain failure changes nothing about the turn.\n // Never run it for media turns — the brain only sees `text`, so\n // \"what is this\" + a photo becomes a generic \"what are you referring to\".\n const turn = ++turnSeqRef.current;\n if (media.length === 0) {\n void quickReplyViaBrain(text).then((answer) => {\n if (!answer) return;\n // Stale if the turn moved on, or the agent already spoke.\n if (turnSeqRef.current !== turn || !pendingRef.current) return;\n if (hasReceivedDeltasRef.current || streamCompletedRef.current) return;\n quickReplyShownRef.current = true;\n cbRef.current.onQuickReply?.(answer);\n });\n }\n\n try {\n const result = await sendMutation({\n variables: {\n input: {\n channelType: 'cdecli-serve',\n accountId,\n chatId,\n text,\n ...(media.length > 0 ? { media: media as never } : {}),\n ...(model || skill\n ? { metadata: { ...(model && { model }), ...(skill && { skill }) } }\n : {}),\n },\n },\n });\n\n const payload = result.data?.gatewaySendMessage;\n if (!payload?.success) {\n const errMsg = payload?.error || 'CDeCLI send failed';\n cbRef.current.onError(errMsg);\n pendingRef.current = null;\n return false;\n }\n\n armTimeout();\n\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n cbRef.current.onError(msg);\n pendingRef.current = null;\n return false;\n }\n },\n [isConnected, accountId, channelId, sendMutation, model, skill, armTimeout],\n );\n\n useEffect(\n () => () => {\n pendingRef.current = null;\n hasReceivedDeltasRef.current = false;\n reconnectedStreamRef.current = false;\n streamCompletedRef.current = false;\n accumulatedLenRef.current = 0;\n lastRunIdRef.current = null;\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n },\n [],\n );\n\n /**\n * Inject a follow-up into the turn that is currently streaming.\n * Same `gatewaySendMessage` mutation with `metadata.steer = true` (browser\n * `useCdecliChannel.steer`). Do NOT reset streaming refs: the existing\n * delta subscription must keep running.\n *\n * \"Cannot steer: no active session\" is an expected race before cdecli has\n * started the turn. Callers should queue and retry; do not `console.error`\n * (that pops the RN LogBox and looks like a crash).\n */\n const steer = useCallback(\n async (text: string, chatId = 'messenger'): Promise<SteerResult> => {\n if (!isConnected) return { ok: false, error: 'CDeCLI is not connected.' };\n try {\n const result = await sendMutation({\n variables: {\n input: {\n channelType: 'cdecli-serve',\n accountId,\n chatId,\n text,\n metadata: { steer: true },\n },\n },\n });\n const payload = result.data?.gatewaySendMessage;\n if (!payload?.success) {\n const errMsg = payload?.error || 'CDeCLI steer failed';\n if (!isNoActiveSessionError(errMsg)) {\n console.warn('[useCdecliChannel] steer failed:', errMsg);\n }\n return { ok: false, error: errMsg };\n }\n return { ok: true };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.warn('[useCdecliChannel] steer mutation error:', msg);\n return { ok: false, error: msg };\n }\n },\n [isConnected, accountId, sendMutation],\n );\n\n /**\n * Abort the in-flight turn. `metadata.cancel = true` maps to\n * `POST /v1/chat/cancel` on cdecli-serve (browser parity).\n */\n const cancel = useCallback(\n async (chatId = 'messenger'): Promise<boolean> => {\n if (!isConnected) return false;\n pendingRef.current = null;\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current);\n timeoutRef.current = null;\n }\n try {\n const result = await sendMutation({\n variables: {\n input: {\n channelType: 'cdecli-serve',\n accountId,\n chatId,\n text: '',\n metadata: { cancel: true },\n },\n },\n });\n const payload = result.data?.gatewaySendMessage;\n if (!payload?.success) {\n console.error('[useCdecliChannel] cancel failed:', payload?.error || 'CDeCLI cancel failed');\n return false;\n }\n return true;\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n console.error('[useCdecliChannel] cancel mutation error:', msg);\n return false;\n }\n },\n [isConnected, accountId, sendMutation],\n );\n\n return { sendMessage, steer, cancel };\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;AAoBA,MAAM,6BAAgC,GAAA,GAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAAA;AAWtC,SAAS,qBAAqB,OAAyB,EAAA;AACrD,EAAA,MAAM,UAAa,GAAA,OAAA,CAAQ,OAAQ,CAAA,OAAA,EAAS,IAAI,CAAA;AAChD,EAAO,OAAA,UAAA,CAAW,OAAQ,CAAA,uFAAA,EAAyF,EAAE,CAAA;AACvH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ownloadLinksMutation}from'common/graphql';import {markChannelHistoryRunning,useChatMutations,useChatMessages,clearChannelHistoryRunning,patchChannelHistoryPreview}from'./useChatApi.js';import {useCdecliChannel,isNoActiveSessionError}from'./useCdecliChannel.js';import {usePrerequisiteIds}from'./usePrerequisiteIds.js';import {isAgentJwtRejected,shouldInlineGatewayMediaForHostedAgent}from'./systemTokenJwt.js';import {config}from'../config/env-config.js';import {buildGatewayMedia,buildGatewayMediaPreferUrls}from'../features/attachments/buildGatewayMedia.js';import {preserveAttachmentPreviews}from'../features/attachments/preserveAttachmentPreviews.js';import {appendOrReplaceAssistant,mergeOptimisticGatewayMessages,collapseConsecutiveAssistants}from'../state/chatThreadMerge.js';var __defProp = Object.defineProperty;
|
|
1
|
+
import {useState,useRef,useCallback,useEffect,useMemo}from'react';import {useCreateAccountChatFileUploadLinksMutation,useCreateAccountChatFileDownloadLinksMutation}from'common/graphql';import {markChannelHistoryRunning,useChatMutations,useChatMessages,clearChannelHistoryRunning,patchChannelHistoryPreview}from'./useChatApi.js';import {useCdecliChannel,isNoActiveSessionError}from'./useCdecliChannel.js';import {usePrerequisiteIds}from'./usePrerequisiteIds.js';import {isAgentJwtRejected,shouldInlineGatewayMediaForHostedAgent}from'./systemTokenJwt.js';import {config}from'../config/env-config.js';import {isImageAttachment}from'../features/attachments/isImageAttachment.js';import {buildGatewayMedia,buildGatewayMediaPreferUrls}from'../features/attachments/buildGatewayMedia.js';import {preserveAttachmentPreviews}from'../features/attachments/preserveAttachmentPreviews.js';import {appendOrReplaceAssistant,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;
|
|
@@ -333,6 +333,7 @@ function useChatStream(sessionId, routing = {
|
|
|
333
333
|
}
|
|
334
334
|
}, [sessionId, backendMessages, backendMessagesLoaded, clearPendingStream]);
|
|
335
335
|
const sendMessage = useCallback(async (content, attachments, sessionIdOverride, alreadyVisible = false) => {
|
|
336
|
+
var _a;
|
|
336
337
|
if (!content.trim() && !(attachments == null ? void 0 : attachments.length)) return;
|
|
337
338
|
const effectiveSessionId = sessionIdOverride !== void 0 ? sessionIdOverride : sessionId;
|
|
338
339
|
const rt = routingRef.current;
|
|
@@ -400,25 +401,31 @@ function useChatStream(sessionId, routing = {
|
|
|
400
401
|
});
|
|
401
402
|
}
|
|
402
403
|
const inlineForHostedAgent = shouldInlineGatewayMediaForHostedAgent(config.GRAPHQL_URL, config.CDECLI_AGENT_ENDPOINT);
|
|
403
|
-
const
|
|
404
|
+
const inlineImages = (attachments != null ? attachments : []).some(isImageAttachment) || inlineForHostedAgent;
|
|
405
|
+
let media = inlineImages ? buildGatewayMedia(attachments, {
|
|
404
406
|
includeData: true
|
|
405
407
|
}) : await buildGatewayMediaPreferUrls(attachments, async (filenames) => {
|
|
406
|
-
var
|
|
408
|
+
var _a2;
|
|
407
409
|
const result = await createAccountChatFileUploadLinksMutation({
|
|
408
410
|
variables: {
|
|
409
411
|
filenames
|
|
410
412
|
}
|
|
411
413
|
});
|
|
412
|
-
return ((
|
|
414
|
+
return ((_a2 = result.data) == null ? void 0 : _a2.createAccountChatFileUploadLinks) || [];
|
|
413
415
|
}, async (urls) => {
|
|
414
|
-
var
|
|
416
|
+
var _a2;
|
|
415
417
|
const result = await createAccountChatFileDownloadLinksMutation({
|
|
416
418
|
variables: {
|
|
417
419
|
urls
|
|
418
420
|
}
|
|
419
421
|
});
|
|
420
|
-
return ((
|
|
422
|
+
return ((_a2 = result.data) == null ? void 0 : _a2.createAccountChatFileDownloadLinks) || [];
|
|
421
423
|
});
|
|
424
|
+
if (((_a = attachments == null ? void 0 : attachments.length) != null ? _a : 0) > 0 && media.length === 0) {
|
|
425
|
+
media = buildGatewayMedia(attachments, {
|
|
426
|
+
includeData: true
|
|
427
|
+
});
|
|
428
|
+
}
|
|
422
429
|
const ok = await sendCdecliMessage(sendText, effectiveSessionId, media);
|
|
423
430
|
if (!ok && !cdecliRoundHandledRef.current && !recoveringAuthRef.current) {
|
|
424
431
|
cdecliRoundHandledRef.current = true;
|