catalyst-ai 0.1.0
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/README.md +30 -0
- package/android/.gradle/8.9/checksums/checksums.lock +0 -0
- package/android/.gradle/8.9/dependencies-accessors/gc.properties +0 -0
- package/android/.gradle/8.9/fileChanges/last-build.bin +0 -0
- package/android/.gradle/8.9/fileHashes/fileHashes.lock +0 -0
- package/android/.gradle/8.9/gc.properties +0 -0
- package/android/.gradle/9.2.0/checksums/checksums.lock +0 -0
- package/android/.gradle/9.2.0/fileChanges/last-build.bin +0 -0
- package/android/.gradle/9.2.0/fileHashes/fileHashes.bin +0 -0
- package/android/.gradle/9.2.0/fileHashes/fileHashes.lock +0 -0
- package/android/.gradle/9.2.0/gc.properties +0 -0
- package/android/.gradle/buildOutputCleanup/buildOutputCleanup.lock +0 -0
- package/android/.gradle/buildOutputCleanup/cache.properties +2 -0
- package/android/.gradle/vcs-1/gc.properties +0 -0
- package/android/build.gradle.kts +47 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/java/io/catalyst/nativeai/AIBridge.kt +24 -0
- package/android/src/main/java/io/catalyst/nativeai/CatalystAIBridge.kt +79 -0
- package/android/src/main/java/io/catalyst/nativeai/NativeBridgeAI.kt +293 -0
- package/android/src/main/resources/META-INF/services/io.catalyst.nativeai.AIBridge +1 -0
- package/package.json +27 -0
- package/scripts/check-peer.js +11 -0
- package/src/buildAttachmentSystemPrompt.js +19 -0
- package/src/index.js +4 -0
- package/src/metrics.js +210 -0
- package/src/pricing.js +14 -0
- package/src/route.js +529 -0
- package/src/useCloudAI.js +315 -0
- package/src/useNativeAI.js +308 -0
- package/src/useWebAI.js +385 -0
|
@@ -0,0 +1,315 @@
|
|
|
1
|
+
import { useState, useRef, useCallback, useMemo } from "react"
|
|
2
|
+
import { buildAttachmentSystemPrompt } from "./buildAttachmentSystemPrompt.js"
|
|
3
|
+
import { computeMetrics, aggregateSessionMetrics } from "./metrics.js"
|
|
4
|
+
|
|
5
|
+
const ATTACHMENT_TAG_RE = /<tool:create_attachment\s+component='([^']+)'([^>]*)>([\s\S]*?)<\/tool:create_attachment>/g
|
|
6
|
+
|
|
7
|
+
function parseAttachmentTag(_, component, attrStr, body) {
|
|
8
|
+
const attrs = {}
|
|
9
|
+
const attrRe = /(\w+)='([^']*)'/g
|
|
10
|
+
let m
|
|
11
|
+
while ((m = attrRe.exec(attrStr)) !== null) attrs[m[1]] = m[2]
|
|
12
|
+
return `\x00SATTACH:${JSON.stringify({ component, attrs, body: body.trim() })}\x00`
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function shallowEqual(a, b) {
|
|
16
|
+
if (a === b) return true
|
|
17
|
+
if (!a || !b) return false
|
|
18
|
+
const ka = Object.keys(a), kb = Object.keys(b)
|
|
19
|
+
if (ka.length !== kb.length) return false
|
|
20
|
+
return ka.every((k) => a[k] === b[k])
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const schedule = typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : (fn) => setTimeout(fn, 16)
|
|
24
|
+
const cancelSchedule = typeof cancelAnimationFrame !== "undefined" ? cancelAnimationFrame : clearTimeout
|
|
25
|
+
|
|
26
|
+
// Hard ceiling on a single generate/stream request — protects against a hung
|
|
27
|
+
// connection leaving loading/streaming state stuck forever.
|
|
28
|
+
const REQUEST_TIMEOUT_MS = 120_000
|
|
29
|
+
const ERROR_BODY_MAX_LEN = 500
|
|
30
|
+
|
|
31
|
+
async function readErrorBody(response) {
|
|
32
|
+
try {
|
|
33
|
+
const text = await response.text()
|
|
34
|
+
return text.length > ERROR_BODY_MAX_LEN ? text.slice(0, ERROR_BODY_MAX_LEN) + "…" : text
|
|
35
|
+
} catch {
|
|
36
|
+
return ""
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function useCloudAI({
|
|
41
|
+
basePath = "/ai",
|
|
42
|
+
provider: providerProp = "openai",
|
|
43
|
+
model: modelProp,
|
|
44
|
+
genConfig: genConfigProp = {},
|
|
45
|
+
attachmentComponents = {},
|
|
46
|
+
systemPrompt = "",
|
|
47
|
+
sessionMode = "stateless",
|
|
48
|
+
defaultGenConfig = {},
|
|
49
|
+
} = {}) {
|
|
50
|
+
// stable merged genConfig — only changes when values actually change
|
|
51
|
+
const mergedGenConfig = useMemo(
|
|
52
|
+
() => ({ ...defaultGenConfig, ...genConfigProp }),
|
|
53
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
54
|
+
[JSON.stringify(defaultGenConfig), JSON.stringify(genConfigProp)]
|
|
55
|
+
)
|
|
56
|
+
|
|
57
|
+
// stable attachmentComponents ref — avoid generate() churn when caller passes inline object
|
|
58
|
+
const attachmentComponentsRef = useRef(attachmentComponents)
|
|
59
|
+
if (!shallowEqual(attachmentComponentsRef.current, attachmentComponents)) {
|
|
60
|
+
attachmentComponentsRef.current = attachmentComponents
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const systemPromptRef = useRef(systemPrompt)
|
|
64
|
+
systemPromptRef.current = systemPrompt
|
|
65
|
+
|
|
66
|
+
const providerRef = useRef(providerProp)
|
|
67
|
+
providerRef.current = providerProp
|
|
68
|
+
|
|
69
|
+
const modelRef = useRef(modelProp)
|
|
70
|
+
modelRef.current = modelProp
|
|
71
|
+
|
|
72
|
+
const sessionModeRef = useRef(sessionMode)
|
|
73
|
+
sessionModeRef.current = sessionMode
|
|
74
|
+
|
|
75
|
+
const [output, setOutput] = useState("")
|
|
76
|
+
const [streaming, setStreaming] = useState(false)
|
|
77
|
+
const [loading, setLoading] = useState(false)
|
|
78
|
+
const [error, setError] = useState(null)
|
|
79
|
+
const [metrics, setMetrics] = useState(null)
|
|
80
|
+
|
|
81
|
+
const abortControllerRef = useRef(null)
|
|
82
|
+
const outputAccRef = useRef("")
|
|
83
|
+
const rafRef = useRef(null)
|
|
84
|
+
const conversationIdRef = useRef(null)
|
|
85
|
+
const activeGenerationRef = useRef(0)
|
|
86
|
+
const historyRef = useRef([])
|
|
87
|
+
|
|
88
|
+
const generate = useCallback(
|
|
89
|
+
async ({ messages, genConfig: callGenConfig = {} }) => {
|
|
90
|
+
if (abortControllerRef.current) abortControllerRef.current.abort()
|
|
91
|
+
|
|
92
|
+
const generationId = ++activeGenerationRef.current
|
|
93
|
+
const controller = new AbortController()
|
|
94
|
+
abortControllerRef.current = controller
|
|
95
|
+
const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
|
|
96
|
+
|
|
97
|
+
const genConfig = { ...mergedGenConfig, ...callGenConfig }
|
|
98
|
+
const provider = providerRef.current
|
|
99
|
+
const isStreamMode = genConfig.stream !== false
|
|
100
|
+
|
|
101
|
+
setLoading(true)
|
|
102
|
+
setOutput("")
|
|
103
|
+
setError(null)
|
|
104
|
+
setMetrics(null)
|
|
105
|
+
outputAccRef.current = ""
|
|
106
|
+
if (rafRef.current) { cancelSchedule(rafRef.current); rafRef.current = null }
|
|
107
|
+
|
|
108
|
+
const builtSystemPrompt = buildAttachmentSystemPrompt(systemPromptRef.current, attachmentComponentsRef.current)
|
|
109
|
+
const messagesWithSystem = builtSystemPrompt
|
|
110
|
+
? [{ role: "system", content: builtSystemPrompt }, ...messages]
|
|
111
|
+
: messages
|
|
112
|
+
|
|
113
|
+
const t0 = performance.now()
|
|
114
|
+
let tokenCount = 0
|
|
115
|
+
let ttftMs = null
|
|
116
|
+
let usage = null
|
|
117
|
+
let completed = false
|
|
118
|
+
|
|
119
|
+
try {
|
|
120
|
+
if (!isStreamMode) {
|
|
121
|
+
// non-streaming: POST /:provider/generate → JSON
|
|
122
|
+
const url = `${basePath}/${provider}/generate`
|
|
123
|
+
const body = { messages: messagesWithSystem, genConfig }
|
|
124
|
+
if (sessionModeRef.current === "stateful") body.conversationId = conversationIdRef.current ?? null
|
|
125
|
+
if (modelRef.current) body.model = modelRef.current
|
|
126
|
+
|
|
127
|
+
const response = await fetch(url, {
|
|
128
|
+
method: "POST",
|
|
129
|
+
headers: { "Content-Type": "application/json" },
|
|
130
|
+
body: JSON.stringify(body),
|
|
131
|
+
signal: controller.signal,
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
if (!response.ok) {
|
|
135
|
+
const errBody = await readErrorBody(response)
|
|
136
|
+
throw new Error(`HTTP error! Status: ${response.status}${errBody ? ` — ${errBody}` : ""}`)
|
|
137
|
+
}
|
|
138
|
+
setLoading(false)
|
|
139
|
+
|
|
140
|
+
const data = await response.json()
|
|
141
|
+
if (activeGenerationRef.current !== generationId) return
|
|
142
|
+
|
|
143
|
+
if (sessionModeRef.current === "stateful" && data.conversationId) {
|
|
144
|
+
conversationIdRef.current = data.conversationId
|
|
145
|
+
}
|
|
146
|
+
const genMs = Math.round(performance.now() - t0)
|
|
147
|
+
setOutput(data.output ?? "")
|
|
148
|
+
const generateUsage = data.usage ? { ...data.usage, provider } : null
|
|
149
|
+
const generateMetrics = computeMetrics(generateUsage, { ttftMs: genMs, genMs })
|
|
150
|
+
setMetrics(generateMetrics)
|
|
151
|
+
if (generateMetrics) historyRef.current.push(generateMetrics)
|
|
152
|
+
return
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// streaming: POST /:provider/stream → SSE
|
|
156
|
+
const url = `${basePath}/${provider}/stream`
|
|
157
|
+
const body = { messages: messagesWithSystem, genConfig }
|
|
158
|
+
if (sessionModeRef.current === "stateful") body.conversationId = conversationIdRef.current ?? null
|
|
159
|
+
if (modelRef.current) body.model = modelRef.current
|
|
160
|
+
|
|
161
|
+
const response = await fetch(url, {
|
|
162
|
+
method: "POST",
|
|
163
|
+
headers: { "Content-Type": "application/json" },
|
|
164
|
+
body: JSON.stringify(body),
|
|
165
|
+
signal: controller.signal,
|
|
166
|
+
})
|
|
167
|
+
|
|
168
|
+
if (!response.ok) {
|
|
169
|
+
const errBody = await readErrorBody(response)
|
|
170
|
+
throw new Error(`HTTP error! Status: ${response.status}${errBody ? ` — ${errBody}` : ""}`)
|
|
171
|
+
}
|
|
172
|
+
if (!response.body) throw new Error("Response has no body to stream")
|
|
173
|
+
|
|
174
|
+
setLoading(false)
|
|
175
|
+
setStreaming(true)
|
|
176
|
+
|
|
177
|
+
const reader = response.body.getReader()
|
|
178
|
+
const decoder = new TextDecoder()
|
|
179
|
+
let buffer = ""
|
|
180
|
+
|
|
181
|
+
try {
|
|
182
|
+
while (true) {
|
|
183
|
+
const { done, value } = await reader.read()
|
|
184
|
+
if (done) break
|
|
185
|
+
|
|
186
|
+
buffer += decoder.decode(value, { stream: true })
|
|
187
|
+
const lines = buffer.split("\n")
|
|
188
|
+
buffer = lines.pop() || ""
|
|
189
|
+
|
|
190
|
+
for (const line of lines) {
|
|
191
|
+
if (!line.startsWith("data: ")) continue
|
|
192
|
+
const payload = line.slice(6).trim()
|
|
193
|
+
if (payload === "[DONE]") {
|
|
194
|
+
// flush any pending RAF before marking done
|
|
195
|
+
if (rafRef.current) { cancelSchedule(rafRef.current); rafRef.current = null }
|
|
196
|
+
setOutput(outputAccRef.current)
|
|
197
|
+
setStreaming(false)
|
|
198
|
+
completed = true
|
|
199
|
+
return
|
|
200
|
+
}
|
|
201
|
+
try {
|
|
202
|
+
const data = JSON.parse(payload)
|
|
203
|
+
if (sessionModeRef.current === "stateful" && data.conversationId && activeGenerationRef.current === generationId) {
|
|
204
|
+
conversationIdRef.current = data.conversationId
|
|
205
|
+
}
|
|
206
|
+
if (typeof data.token === "string") {
|
|
207
|
+
if (ttftMs === null) ttftMs = Math.round(performance.now() - t0)
|
|
208
|
+
tokenCount++
|
|
209
|
+
outputAccRef.current += data.token
|
|
210
|
+
outputAccRef.current = outputAccRef.current.replace(ATTACHMENT_TAG_RE, parseAttachmentTag)
|
|
211
|
+
if (!rafRef.current) {
|
|
212
|
+
rafRef.current = schedule(() => {
|
|
213
|
+
rafRef.current = null
|
|
214
|
+
setOutput(outputAccRef.current)
|
|
215
|
+
})
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
if (data.usage) {
|
|
219
|
+
usage = { ...data.usage, provider }
|
|
220
|
+
}
|
|
221
|
+
} catch (_) {}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
} finally {
|
|
225
|
+
await reader.cancel().catch(() => {})
|
|
226
|
+
reader.releaseLock()
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// stream ended without [DONE] — flush and finalize
|
|
230
|
+
if (rafRef.current) { cancelSchedule(rafRef.current); rafRef.current = null }
|
|
231
|
+
setOutput(outputAccRef.current)
|
|
232
|
+
setStreaming(false)
|
|
233
|
+
completed = true
|
|
234
|
+
} catch (err) {
|
|
235
|
+
if (err.name === "AbortError") return
|
|
236
|
+
setError(err)
|
|
237
|
+
setStreaming(false)
|
|
238
|
+
setLoading(false)
|
|
239
|
+
} finally {
|
|
240
|
+
clearTimeout(timeoutId)
|
|
241
|
+
if (activeGenerationRef.current === generationId) {
|
|
242
|
+
if (completed) {
|
|
243
|
+
const genMs = Math.round(performance.now() - t0)
|
|
244
|
+
if (usage) {
|
|
245
|
+
const streamMetrics = computeMetrics(usage, { ttftMs, genMs })
|
|
246
|
+
setMetrics(streamMetrics)
|
|
247
|
+
if (streamMetrics) historyRef.current.push(streamMetrics)
|
|
248
|
+
} else if (tokenCount > 0) {
|
|
249
|
+
// usage frame never arrived (e.g. unverified Interactions API usage shape) —
|
|
250
|
+
// fall back to our own token-count-based tps so the UI isn't left blank
|
|
251
|
+
const tps = parseFloat((tokenCount / (genMs / 1000)).toFixed(1))
|
|
252
|
+
const fallbackMetrics = {
|
|
253
|
+
provider, model: modelRef.current, ttftMs, genMs, tps,
|
|
254
|
+
promptTokens: null, cachedTokens: null, completionTokens: tokenCount,
|
|
255
|
+
reasoningTokens: null, totalTokens: tokenCount, cost: null, cacheSavings: null,
|
|
256
|
+
device: null, dtype: null, loadMs: null, downloadBytes: null,
|
|
257
|
+
}
|
|
258
|
+
setMetrics(fallbackMetrics)
|
|
259
|
+
historyRef.current.push(fallbackMetrics)
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
if (abortControllerRef.current === controller) abortControllerRef.current = null
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
},
|
|
266
|
+
[basePath, mergedGenConfig]
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
const cancel = useCallback(() => {
|
|
270
|
+
if (rafRef.current) { cancelSchedule(rafRef.current); rafRef.current = null }
|
|
271
|
+
if (abortControllerRef.current) { abortControllerRef.current.abort(); abortControllerRef.current = null }
|
|
272
|
+
setStreaming(false)
|
|
273
|
+
setLoading(false)
|
|
274
|
+
}, [])
|
|
275
|
+
|
|
276
|
+
const reset = useCallback(() => {
|
|
277
|
+
if (rafRef.current) { cancelSchedule(rafRef.current); rafRef.current = null }
|
|
278
|
+
outputAccRef.current = ""
|
|
279
|
+
if (abortControllerRef.current) { abortControllerRef.current.abort(); abortControllerRef.current = null }
|
|
280
|
+
conversationIdRef.current = null
|
|
281
|
+
setOutput("")
|
|
282
|
+
setError(null)
|
|
283
|
+
setMetrics(null)
|
|
284
|
+
setStreaming(false)
|
|
285
|
+
setLoading(false)
|
|
286
|
+
}, [])
|
|
287
|
+
|
|
288
|
+
const getSessionMetrics = useCallback(() => aggregateSessionMetrics(historyRef.current), [])
|
|
289
|
+
|
|
290
|
+
const resetSessionMetrics = useCallback(() => {
|
|
291
|
+
historyRef.current = []
|
|
292
|
+
}, [])
|
|
293
|
+
|
|
294
|
+
return {
|
|
295
|
+
output,
|
|
296
|
+
streaming,
|
|
297
|
+
loading,
|
|
298
|
+
error,
|
|
299
|
+
metrics,
|
|
300
|
+
modelReady: true,
|
|
301
|
+
downloadProgress: null,
|
|
302
|
+
nativeDownloadProgress: null,
|
|
303
|
+
nativeLogs: [],
|
|
304
|
+
isLocal: false,
|
|
305
|
+
isNative: false,
|
|
306
|
+
isWeb: true,
|
|
307
|
+
generate,
|
|
308
|
+
cancel,
|
|
309
|
+
reset,
|
|
310
|
+
getSessionMetrics,
|
|
311
|
+
resetSessionMetrics,
|
|
312
|
+
clearError: useCallback(() => setError(null), []),
|
|
313
|
+
get conversationId() { return conversationIdRef.current },
|
|
314
|
+
}
|
|
315
|
+
}
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
import { useState, useRef, useCallback, useEffect } from "react"
|
|
2
|
+
import { aggregateNativeSessionMetrics } from "./metrics.js"
|
|
3
|
+
|
|
4
|
+
const ATTACHMENT_TAG_RE = /<tool:create_attachment\s+component='([^']+)'([^>]*)>([\s\S]*?)<\/tool:create_attachment>/g
|
|
5
|
+
|
|
6
|
+
function parseAttachmentTag(_, component, attrStr, body) {
|
|
7
|
+
const attrs = {}
|
|
8
|
+
const attrRe = /(\w+)='([^']*)'/g
|
|
9
|
+
let m
|
|
10
|
+
while ((m = attrRe.exec(attrStr)) !== null) attrs[m[1]] = m[2]
|
|
11
|
+
return `\x00SATTACH:${JSON.stringify({ component, attrs, body: body.trim() })}\x00`
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
// NATIVE_CALLBACKS mirrors the constants in catalyst-core NativeInterfaces.js
|
|
15
|
+
const NATIVE_CALLBACKS = {
|
|
16
|
+
ON_AI_READY: "ON_AI_READY",
|
|
17
|
+
ON_AI_PROGRESS: "ON_AI_PROGRESS",
|
|
18
|
+
ON_AI_LOG: "ON_AI_LOG",
|
|
19
|
+
ON_AI_ERROR: "ON_AI_ERROR",
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function useNativeAI({
|
|
23
|
+
genConfig: genConfigProp = {},
|
|
24
|
+
attachmentComponents = {},
|
|
25
|
+
systemPrompt = "",
|
|
26
|
+
sessionMode = "stateless",
|
|
27
|
+
defaultGenConfig = {},
|
|
28
|
+
enabled = true,
|
|
29
|
+
} = {}) {
|
|
30
|
+
const hookGenConfig = { ...defaultGenConfig, ...genConfigProp }
|
|
31
|
+
|
|
32
|
+
const [output, setOutput] = useState("")
|
|
33
|
+
const [streaming, setStreaming] = useState(false)
|
|
34
|
+
const [loading, setLoading] = useState(false)
|
|
35
|
+
const [error, setError] = useState(null)
|
|
36
|
+
const [modelReady, setModelReady] = useState(false)
|
|
37
|
+
const [nativeDownloadProgress, setNativeDownloadProgress] = useState(null)
|
|
38
|
+
const [nativeLogs, setNativeLogs] = useState([])
|
|
39
|
+
const [metrics, setMetrics] = useState(null)
|
|
40
|
+
|
|
41
|
+
const abortControllerRef = useRef(null)
|
|
42
|
+
const outputAccRef = useRef("")
|
|
43
|
+
const rafRef = useRef(null)
|
|
44
|
+
const nativeStreamUrlRef = useRef(null)
|
|
45
|
+
const conversationIdRef = useRef(null)
|
|
46
|
+
const historyRef = useRef([])
|
|
47
|
+
|
|
48
|
+
useEffect(() => () => {
|
|
49
|
+
if (rafRef.current) {
|
|
50
|
+
typeof cancelAnimationFrame !== "undefined" ? cancelAnimationFrame(rafRef.current) : clearTimeout(rafRef.current)
|
|
51
|
+
rafRef.current = null
|
|
52
|
+
}
|
|
53
|
+
if (abortControllerRef.current) { abortControllerRef.current.abort(); abortControllerRef.current = null }
|
|
54
|
+
}, [])
|
|
55
|
+
|
|
56
|
+
useEffect(() => {
|
|
57
|
+
if (!enabled) return
|
|
58
|
+
|
|
59
|
+
if (!window.NativeBridge?.initAI) {
|
|
60
|
+
setError(new Error(
|
|
61
|
+
"[catalyst-ai/useNativeAI] window.NativeBridge.initAI not found. " +
|
|
62
|
+
"Update catalyst-core to >=0.2.0 and add the android module to settings.gradle.kts."
|
|
63
|
+
))
|
|
64
|
+
return
|
|
65
|
+
}
|
|
66
|
+
if (!window.WebBridge) {
|
|
67
|
+
setError(new Error("[catalyst-ai/useNativeAI] WebBridge not initialized — call WebBridge.init() before mounting useNativeAI"))
|
|
68
|
+
return
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const onReady = (data) => {
|
|
72
|
+
try {
|
|
73
|
+
const parsed = typeof data === "string" ? JSON.parse(data) : data
|
|
74
|
+
if (parsed?.url) {
|
|
75
|
+
nativeStreamUrlRef.current = parsed.url
|
|
76
|
+
setModelReady(true)
|
|
77
|
+
setNativeDownloadProgress(null)
|
|
78
|
+
}
|
|
79
|
+
} catch (_) {}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const onProgress = (data) => {
|
|
83
|
+
try {
|
|
84
|
+
const parsed = typeof data === "string" ? JSON.parse(data) : data
|
|
85
|
+
setNativeDownloadProgress(parsed)
|
|
86
|
+
} catch (_) {}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const onLog = (data) => {
|
|
90
|
+
try {
|
|
91
|
+
const parsed = typeof data === "string" ? JSON.parse(data) : data
|
|
92
|
+
const msg = parsed?.message ?? String(data)
|
|
93
|
+
setNativeLogs((prev) => [...prev.slice(-99), msg])
|
|
94
|
+
} catch (_) {}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const onError = (data) => {
|
|
98
|
+
try {
|
|
99
|
+
const parsed = typeof data === "string" ? JSON.parse(data) : data
|
|
100
|
+
const msg = parsed?.message ?? String(data)
|
|
101
|
+
setError(new Error(msg))
|
|
102
|
+
} catch (_) {
|
|
103
|
+
setError(new Error(String(data)))
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
window.WebBridge.register(NATIVE_CALLBACKS.ON_AI_READY, onReady)
|
|
108
|
+
window.WebBridge.register(NATIVE_CALLBACKS.ON_AI_PROGRESS, onProgress)
|
|
109
|
+
window.WebBridge.register(NATIVE_CALLBACKS.ON_AI_LOG, onLog)
|
|
110
|
+
window.WebBridge.register(NATIVE_CALLBACKS.ON_AI_ERROR, onError)
|
|
111
|
+
window.NativeBridge.initAI(JSON.stringify({ attachmentComponents, systemPrompt }))
|
|
112
|
+
|
|
113
|
+
return () => {
|
|
114
|
+
window.WebBridge.unregister(NATIVE_CALLBACKS.ON_AI_READY)
|
|
115
|
+
window.WebBridge.unregister(NATIVE_CALLBACKS.ON_AI_PROGRESS)
|
|
116
|
+
window.WebBridge.unregister(NATIVE_CALLBACKS.ON_AI_LOG)
|
|
117
|
+
window.WebBridge.unregister(NATIVE_CALLBACKS.ON_AI_ERROR)
|
|
118
|
+
}
|
|
119
|
+
}, [enabled])
|
|
120
|
+
|
|
121
|
+
const generate = useCallback(
|
|
122
|
+
async ({ messages, genConfig: callGenConfig = {} }) => {
|
|
123
|
+
const url = nativeStreamUrlRef.current
|
|
124
|
+
if (!url) {
|
|
125
|
+
setError(new Error("[catalyst-ai/useNativeAI] stream URL not ready — did initAI fire?"))
|
|
126
|
+
return
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if (abortControllerRef.current) abortControllerRef.current.abort()
|
|
130
|
+
const controller = new AbortController()
|
|
131
|
+
abortControllerRef.current = controller
|
|
132
|
+
|
|
133
|
+
const genConfig = { ...hookGenConfig, ...callGenConfig }
|
|
134
|
+
const prompt = messages.map((m) => `${m.role}: ${m.content}`).join("\n")
|
|
135
|
+
const isStreamMode = genConfig.stream !== false
|
|
136
|
+
|
|
137
|
+
setLoading(true)
|
|
138
|
+
setOutput("")
|
|
139
|
+
setError(null)
|
|
140
|
+
setMetrics(null)
|
|
141
|
+
outputAccRef.current = ""
|
|
142
|
+
|
|
143
|
+
const t0 = performance.now()
|
|
144
|
+
let tokenCount = 0
|
|
145
|
+
let ttftMs = null
|
|
146
|
+
|
|
147
|
+
try {
|
|
148
|
+
const nativeBody = { prompt, genConfig }
|
|
149
|
+
if (sessionMode === "stateful" && conversationIdRef.current) {
|
|
150
|
+
nativeBody.conversationId = conversationIdRef.current
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (!isStreamMode) {
|
|
154
|
+
const generateUrl = url.replace(/\/ai\/stream$/, "/ai/generate")
|
|
155
|
+
const response = await fetch(generateUrl, {
|
|
156
|
+
method: "POST",
|
|
157
|
+
headers: { "Content-Type": "application/json" },
|
|
158
|
+
body: JSON.stringify(nativeBody),
|
|
159
|
+
signal: controller.signal,
|
|
160
|
+
})
|
|
161
|
+
|
|
162
|
+
if (!response.ok) throw new Error(`Native AI HTTP error: ${response.status}`)
|
|
163
|
+
setLoading(false)
|
|
164
|
+
|
|
165
|
+
const data = await response.json()
|
|
166
|
+
if (data.error) throw new Error(data.error)
|
|
167
|
+
|
|
168
|
+
if (sessionMode === "stateful" && data.conversationId) {
|
|
169
|
+
conversationIdRef.current = data.conversationId
|
|
170
|
+
}
|
|
171
|
+
const genMs = Math.round(performance.now() - t0)
|
|
172
|
+
setOutput(data.output ?? "")
|
|
173
|
+
const tokenCountOut = data.tokenCount ?? 0
|
|
174
|
+
const tps = tokenCountOut > 0 ? parseFloat((tokenCountOut / (genMs / 1000)).toFixed(1)) : 0
|
|
175
|
+
const generateMetrics = { device: "native", ttftMs: genMs, tps, totalTokens: tokenCountOut, genMs }
|
|
176
|
+
setMetrics(generateMetrics)
|
|
177
|
+
historyRef.current.push(generateMetrics)
|
|
178
|
+
return
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const response = await fetch(url, {
|
|
182
|
+
method: "POST",
|
|
183
|
+
headers: { "Content-Type": "application/json" },
|
|
184
|
+
body: JSON.stringify(nativeBody),
|
|
185
|
+
signal: controller.signal,
|
|
186
|
+
})
|
|
187
|
+
|
|
188
|
+
if (!response.ok) throw new Error(`Native AI HTTP error: ${response.status}`)
|
|
189
|
+
|
|
190
|
+
setLoading(false)
|
|
191
|
+
setStreaming(true)
|
|
192
|
+
|
|
193
|
+
const reader = response.body.getReader()
|
|
194
|
+
const decoder = new TextDecoder()
|
|
195
|
+
let buffer = ""
|
|
196
|
+
|
|
197
|
+
try {
|
|
198
|
+
while (true) {
|
|
199
|
+
const { done, value } = await reader.read()
|
|
200
|
+
if (done) break
|
|
201
|
+
buffer += decoder.decode(value, { stream: true })
|
|
202
|
+
const lines = buffer.split("\n")
|
|
203
|
+
buffer = lines.pop() || ""
|
|
204
|
+
for (const line of lines) {
|
|
205
|
+
if (!line.startsWith("data: ")) continue
|
|
206
|
+
try {
|
|
207
|
+
const data = JSON.parse(line.slice(6))
|
|
208
|
+
if (data.done) {
|
|
209
|
+
setStreaming(false)
|
|
210
|
+
const genMs = Math.round(performance.now() - t0)
|
|
211
|
+
const tps = tokenCount > 0 ? parseFloat((tokenCount / (genMs / 1000)).toFixed(1)) : 0
|
|
212
|
+
const streamMetrics = { device: "native", ttftMs, tps, totalTokens: tokenCount, genMs }
|
|
213
|
+
setMetrics(streamMetrics)
|
|
214
|
+
historyRef.current.push(streamMetrics)
|
|
215
|
+
return
|
|
216
|
+
}
|
|
217
|
+
if (sessionMode === "stateful" && data.conversationId) {
|
|
218
|
+
conversationIdRef.current = data.conversationId
|
|
219
|
+
}
|
|
220
|
+
if (typeof data.token === "string") {
|
|
221
|
+
if (ttftMs === null) ttftMs = Math.round(performance.now() - t0)
|
|
222
|
+
tokenCount++
|
|
223
|
+
outputAccRef.current += data.token
|
|
224
|
+
outputAccRef.current = outputAccRef.current.replace(ATTACHMENT_TAG_RE, parseAttachmentTag)
|
|
225
|
+
if (!rafRef.current) {
|
|
226
|
+
const schedule = typeof requestAnimationFrame !== "undefined" ? requestAnimationFrame : (fn) => setTimeout(fn, 16)
|
|
227
|
+
rafRef.current = schedule(() => {
|
|
228
|
+
rafRef.current = null
|
|
229
|
+
setOutput(outputAccRef.current)
|
|
230
|
+
})
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
if (data.error) throw new Error(data.error)
|
|
234
|
+
} catch (_) {}
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
} finally {
|
|
238
|
+
reader.releaseLock()
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// flush any pending RAF before marking done
|
|
242
|
+
if (rafRef.current) {
|
|
243
|
+
typeof cancelAnimationFrame !== "undefined" ? cancelAnimationFrame(rafRef.current) : clearTimeout(rafRef.current)
|
|
244
|
+
rafRef.current = null
|
|
245
|
+
setOutput(outputAccRef.current)
|
|
246
|
+
}
|
|
247
|
+
setStreaming(false)
|
|
248
|
+
} catch (err) {
|
|
249
|
+
if (err.name === "AbortError") return
|
|
250
|
+
setError(err)
|
|
251
|
+
setStreaming(false)
|
|
252
|
+
setLoading(false)
|
|
253
|
+
} finally {
|
|
254
|
+
if (abortControllerRef.current === controller) abortControllerRef.current = null
|
|
255
|
+
}
|
|
256
|
+
},
|
|
257
|
+
[hookGenConfig, sessionMode]
|
|
258
|
+
)
|
|
259
|
+
|
|
260
|
+
const cancelRaf = () => {
|
|
261
|
+
if (!rafRef.current) return
|
|
262
|
+
typeof cancelAnimationFrame !== "undefined" ? cancelAnimationFrame(rafRef.current) : clearTimeout(rafRef.current)
|
|
263
|
+
rafRef.current = null
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const cancel = useCallback(() => {
|
|
267
|
+
cancelRaf()
|
|
268
|
+
if (abortControllerRef.current) { abortControllerRef.current.abort(); abortControllerRef.current = null }
|
|
269
|
+
setStreaming(false)
|
|
270
|
+
}, [])
|
|
271
|
+
|
|
272
|
+
const reset = useCallback(() => {
|
|
273
|
+
cancelRaf()
|
|
274
|
+
outputAccRef.current = ""
|
|
275
|
+
if (abortControllerRef.current) { abortControllerRef.current.abort(); abortControllerRef.current = null }
|
|
276
|
+
conversationIdRef.current = null
|
|
277
|
+
if (window.NativeBridge?.clearNativeConversation) {
|
|
278
|
+
window.NativeBridge.clearNativeConversation()
|
|
279
|
+
}
|
|
280
|
+
setOutput("")
|
|
281
|
+
setError(null)
|
|
282
|
+
setMetrics(null)
|
|
283
|
+
setStreaming(false)
|
|
284
|
+
setLoading(false)
|
|
285
|
+
}, [])
|
|
286
|
+
|
|
287
|
+
return {
|
|
288
|
+
output,
|
|
289
|
+
streaming,
|
|
290
|
+
loading,
|
|
291
|
+
error,
|
|
292
|
+
modelReady,
|
|
293
|
+
downloadProgress: null,
|
|
294
|
+
nativeDownloadProgress,
|
|
295
|
+
nativeLogs,
|
|
296
|
+
metrics,
|
|
297
|
+
isLocal: false,
|
|
298
|
+
isNative: true,
|
|
299
|
+
isWeb: false,
|
|
300
|
+
generate,
|
|
301
|
+
cancel,
|
|
302
|
+
reset,
|
|
303
|
+
clearError: useCallback(() => setError(null), []),
|
|
304
|
+
get conversationId() { return conversationIdRef.current },
|
|
305
|
+
getSessionMetrics: useCallback(() => aggregateNativeSessionMetrics(historyRef.current), []),
|
|
306
|
+
resetSessionMetrics: useCallback(() => { historyRef.current = [] }, []),
|
|
307
|
+
}
|
|
308
|
+
}
|