@adminide-stack/yantra-mobile 12.0.64-alpha.4 → 12.0.64
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/features/attachments/releasePreviewBytes.js +32 -0
- package/lib/features/attachments/releasePreviewBytes.js.map +1 -0
- package/lib/features/attachments/useImageAttachments.js +266 -40
- package/lib/features/attachments/useImageAttachments.js.map +1 -1
- package/lib/hooks/useChatStream.js +5 -2
- package/lib/hooks/useChatStream.js.map +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
|
|
3
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
4
|
+
var __propIsEnum = Object.prototype.propertyIsEnumerable;
|
|
5
|
+
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
|
|
6
|
+
var __spreadValues = (a, b) => {
|
|
7
|
+
for (var prop in b || (b = {}))
|
|
8
|
+
if (__hasOwnProp.call(b, prop))
|
|
9
|
+
__defNormalProp(a, prop, b[prop]);
|
|
10
|
+
if (__getOwnPropSymbols)
|
|
11
|
+
for (var prop of __getOwnPropSymbols(b)) {
|
|
12
|
+
if (__propIsEnum.call(b, prop))
|
|
13
|
+
__defNormalProp(a, prop, b[prop]);
|
|
14
|
+
}
|
|
15
|
+
return a;
|
|
16
|
+
};
|
|
17
|
+
const LOCAL_URI_RE = /^(file:|content:|ph:|assets-library:)/i;
|
|
18
|
+
function canPaintWithoutBytes(attachment) {
|
|
19
|
+
var _a;
|
|
20
|
+
const url = (_a = attachment.url) == null ? void 0 : _a.trim();
|
|
21
|
+
return Boolean(url && LOCAL_URI_RE.test(url));
|
|
22
|
+
}
|
|
23
|
+
function releasePreviewBytes(attachments) {
|
|
24
|
+
if (!(attachments == null ? void 0 : attachments.length)) return attachments;
|
|
25
|
+
if (!attachments.some((a) => a.dataUrl && canPaintWithoutBytes(a))) return attachments;
|
|
26
|
+
return attachments.map((attachment) => {
|
|
27
|
+
if (!attachment.dataUrl || !canPaintWithoutBytes(attachment)) return attachment;
|
|
28
|
+
const rest = __spreadValues({}, attachment);
|
|
29
|
+
delete rest.dataUrl;
|
|
30
|
+
return rest;
|
|
31
|
+
});
|
|
32
|
+
}export{releasePreviewBytes};//# sourceMappingURL=releasePreviewBytes.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"releasePreviewBytes.js","sources":["../../../src/features/attachments/releasePreviewBytes.ts"],"sourcesContent":["/**\n * Keeping a sent attachment's base64 out of the transcript.\n *\n * A `dataUrl` is the whole image as a JS string - a shrunk photo is ~1.4MB, a\n * document can be tens of MB, and `messages` holds every turn for the life of\n * the session. iOS picks the largest just-suspended process when it needs\n * memory back, so those strings are charged against us on every background,\n * long after the bytes have been sent and are never read again.\n *\n * They are also redundant: `attachmentPreviewUri` prefers the local `file:`\n * URI over the data URL, so the bubble paints identically without them. The\n * bytes are only genuinely needed until the send completes, and that copy lives\n * in `userMsgForSaveRef` for the duration of the turn, not in the transcript.\n *\n * The one thing that must not change is which turns render. `hasLiveLocalPreview`\n * (displayUserMessageText) counts a *local* URI or a data URL, deliberately not\n * an https one - so the bytes are only released when a local URI survives to\n * stand in for them.\n */\n\n/** Local URIs the native Image component can paint without the base64. */\nconst LOCAL_URI_RE = /^(file:|content:|ph:|assets-library:)/i;\n\ntype Releasable = { url?: string; dataUrl?: string };\n\nfunction canPaintWithoutBytes(attachment: Releasable): boolean {\n const url = attachment.url?.trim();\n return Boolean(url && LOCAL_URI_RE.test(url));\n}\n\n/**\n * Strip `dataUrl` from attachments about to be retained for the session,\n * leaving anything that would otherwise lose its preview untouched.\n */\nexport function releasePreviewBytes<T extends Releasable>(attachments: T[] | undefined): T[] | undefined {\n if (!attachments?.length) return attachments;\n if (!attachments.some((a) => a.dataUrl && canPaintWithoutBytes(a))) return attachments;\n return attachments.map((attachment) => {\n if (!attachment.dataUrl || !canPaintWithoutBytes(attachment)) return attachment;\n const rest = { ...attachment };\n delete rest.dataUrl;\n return rest;\n });\n}\n\n/** Bytes a set of attachments is holding in `dataUrl` strings. Diagnostics only. */\nexport function retainedPreviewBytes(attachments: Releasable[] | undefined): number {\n return (attachments ?? []).reduce((total, a) => total + (a.dataUrl?.length ?? 0), 0);\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAqBA,MAAM,YAAe,GAAA,wCAAA;AAKrB,SAAS,qBAAqB,UAAiC,EAAA;AA1B/D,EAAA,IAAA,EAAA;AA2BE,EAAM,MAAA,GAAA,GAAA,CAAM,EAAW,GAAA,UAAA,CAAA,GAAA,KAAX,IAAgB,GAAA,MAAA,GAAA,EAAA,CAAA,IAAA,EAAA;AAC5B,EAAA,OAAO,OAAQ,CAAA,GAAA,IAAO,YAAa,CAAA,IAAA,CAAK,GAAG,CAAC,CAAA;AAC9C;AAMO,SAAS,oBAA0C,WAA+C,EAAA;AACvG,EAAI,IAAA,EAAC,WAAa,IAAA,IAAA,GAAA,MAAA,GAAA,WAAA,CAAA,MAAA,CAAA,EAAe,OAAA,WAAA;AACjC,EAAI,IAAA,CAAC,WAAY,CAAA,IAAA,CAAK,CAAK,CAAA,KAAA,CAAA,CAAE,WAAW,oBAAqB,CAAA,CAAC,CAAC,CAAA,EAAU,OAAA,WAAA;AACzE,EAAO,OAAA,WAAA,CAAY,IAAI,CAAc,UAAA,KAAA;AACnC,IAAA,IAAI,CAAC,UAAW,CAAA,OAAA,IAAW,CAAC,oBAAqB,CAAA,UAAU,GAAU,OAAA,UAAA;AACrE,IAAA,MAAM,OAAO,cACR,CAAA,EAAA,EAAA,UAAA,CAAA;AAEL,IAAA,OAAO,IAAK,CAAA,OAAA;AACZ,IAAO,OAAA,IAAA;AAAA,GACR,CAAA;AACH"}
|
|
@@ -17,8 +17,25 @@ var __spreadValues = (a, b) => {
|
|
|
17
17
|
return a;
|
|
18
18
|
};
|
|
19
19
|
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
|
|
20
|
+
const MAX_EDGE = 2576;
|
|
21
|
+
const FALLBACK_EDGE = 1568;
|
|
20
22
|
const PICKER_QUALITY = 0.7;
|
|
21
|
-
const
|
|
23
|
+
const RESIZE_QUALITY = 0.8;
|
|
24
|
+
const FALLBACK_QUALITY = 0.6;
|
|
25
|
+
const TARGET_BYTES = 5 * 1024 * 1024;
|
|
26
|
+
const MAX_INLINE_BYTES = 10 * 1024 * 1024;
|
|
27
|
+
const MAX_SOURCE_BYTES = 50 * 1024 * 1024;
|
|
28
|
+
const SHRINK_PASSES = [{
|
|
29
|
+
edge: MAX_EDGE,
|
|
30
|
+
quality: RESIZE_QUALITY
|
|
31
|
+
}, {
|
|
32
|
+
edge: FALLBACK_EDGE,
|
|
33
|
+
quality: FALLBACK_QUALITY
|
|
34
|
+
}, {
|
|
35
|
+
edge: 1024,
|
|
36
|
+
quality: 0.5
|
|
37
|
+
}];
|
|
38
|
+
const MAX_PENDING_BYTES = 32 * 1024 * 1024;
|
|
22
39
|
const MIN_BYTES = 64;
|
|
23
40
|
function base64Bytes(base64) {
|
|
24
41
|
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
|
|
@@ -55,25 +72,174 @@ async function readUriBase64(uri) {
|
|
|
55
72
|
})).trim();
|
|
56
73
|
return base64 || null;
|
|
57
74
|
}
|
|
75
|
+
function loadImageManipulator() {
|
|
76
|
+
try {
|
|
77
|
+
return require("expo-image-manipulator");
|
|
78
|
+
} catch (e) {
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
async function shrinkForTransport(asset, knownBytes) {
|
|
83
|
+
var _a, _b, _c;
|
|
84
|
+
const uri = (_a = asset.uri) == null ? void 0 : _a.trim();
|
|
85
|
+
if (!uri) return null;
|
|
86
|
+
const width = (_b = asset.width) != null ? _b : 0;
|
|
87
|
+
const height = (_c = asset.height) != null ? _c : 0;
|
|
88
|
+
const longEdge = Math.max(width, height);
|
|
89
|
+
if (longEdge <= MAX_EDGE && knownBytes <= TARGET_BYTES) return null;
|
|
90
|
+
const manipulator = loadImageManipulator();
|
|
91
|
+
const manipulate = manipulator == null ? void 0 : manipulator.manipulateAsync;
|
|
92
|
+
if (typeof manipulate !== "function") return null;
|
|
93
|
+
const encode = async (edge, quality) => {
|
|
94
|
+
var _a2, _b2, _c2;
|
|
95
|
+
const capped = longEdge > 0 ? Math.min(edge, longEdge) : edge;
|
|
96
|
+
const resize = height > width ? {
|
|
97
|
+
height: capped
|
|
98
|
+
} : {
|
|
99
|
+
width: capped
|
|
100
|
+
};
|
|
101
|
+
const out = await manipulate(uri, [{
|
|
102
|
+
resize
|
|
103
|
+
}], {
|
|
104
|
+
compress: quality,
|
|
105
|
+
format: (_b2 = (_a2 = manipulator == null ? void 0 : manipulator.SaveFormat) == null ? void 0 : _a2.JPEG) != null ? _b2 : "jpeg",
|
|
106
|
+
base64: true
|
|
107
|
+
});
|
|
108
|
+
const base64 = ((_c2 = out.base64) == null ? void 0 : _c2.trim()) || (out.uri ? await readUriBase64(out.uri) : null);
|
|
109
|
+
return base64 ? {
|
|
110
|
+
base64,
|
|
111
|
+
uri: out.uri || uri,
|
|
112
|
+
mimeType: "image/jpeg"
|
|
113
|
+
} : null;
|
|
114
|
+
};
|
|
115
|
+
let best = null;
|
|
116
|
+
let bestBytes = Number.POSITIVE_INFINITY;
|
|
117
|
+
for (const pass of SHRINK_PASSES) {
|
|
118
|
+
const out = await encode(pass.edge, pass.quality);
|
|
119
|
+
if (out) {
|
|
120
|
+
const bytes = base64Bytes(out.base64);
|
|
121
|
+
if (bytes < bestBytes) {
|
|
122
|
+
best = out;
|
|
123
|
+
bestBytes = bytes;
|
|
124
|
+
}
|
|
125
|
+
if (bytes <= TARGET_BYTES) break;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return best;
|
|
129
|
+
}
|
|
130
|
+
function mb(bytes) {
|
|
131
|
+
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
132
|
+
}
|
|
133
|
+
function stagedBytes(attachments) {
|
|
134
|
+
return attachments.reduce((total, a) => {
|
|
135
|
+
var _a;
|
|
136
|
+
return total + ((_a = a.size) != null ? _a : 0);
|
|
137
|
+
}, 0);
|
|
138
|
+
}
|
|
139
|
+
function withinPendingBudget(existing, incoming) {
|
|
140
|
+
var _a;
|
|
141
|
+
let used = stagedBytes(existing);
|
|
142
|
+
const accepted = [];
|
|
143
|
+
const rejected = [];
|
|
144
|
+
for (const attachment of incoming) {
|
|
145
|
+
const size = (_a = attachment.size) != null ? _a : 0;
|
|
146
|
+
if (used + size > MAX_PENDING_BYTES) {
|
|
147
|
+
rejected.push(attachment);
|
|
148
|
+
} else {
|
|
149
|
+
used += size;
|
|
150
|
+
accepted.push(attachment);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
return {
|
|
154
|
+
accepted,
|
|
155
|
+
rejected
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
function failureMessage(failures, noun) {
|
|
159
|
+
const unshrunk = failures.find((f) => f.reason === "unshrunk");
|
|
160
|
+
if (unshrunk) {
|
|
161
|
+
return `This app version cannot resize a ${mb(unshrunk.bytes)} ${noun} before sending. Update the app, or attach a smaller one.`;
|
|
162
|
+
}
|
|
163
|
+
const oversize = failures.find((f) => f.reason === "oversize");
|
|
164
|
+
if (oversize) {
|
|
165
|
+
return `That ${noun} is ${mb(oversize.bytes)} and the limit is ${mb(oversize.limit)}. Try a smaller one.`;
|
|
166
|
+
}
|
|
167
|
+
if (noun === "image") {
|
|
168
|
+
return "Could not read that photo. Try another one, or save it to Recents first.";
|
|
169
|
+
}
|
|
170
|
+
return "Could not read that file. Try another one.";
|
|
171
|
+
}
|
|
58
172
|
async function assetToAttachment(asset, index, kind = "file") {
|
|
59
173
|
var _a, _b, _c, _d;
|
|
60
|
-
let
|
|
61
|
-
|
|
62
|
-
|
|
174
|
+
let mimeType = guessImageMime(asset);
|
|
175
|
+
let uri = ((_a = asset.uri) == null ? void 0 : _a.trim()) || void 0;
|
|
176
|
+
let base64 = "";
|
|
177
|
+
let resized = false;
|
|
178
|
+
const inline = ((_b = asset.base64) == null ? void 0 : _b.trim()) || "";
|
|
179
|
+
const knownBytes = inline ? base64Bytes(inline) : (_c = asset.fileSize) != null ? _c : 0;
|
|
180
|
+
if (knownBytes > MAX_SOURCE_BYTES) {
|
|
181
|
+
return {
|
|
182
|
+
status: "failed",
|
|
183
|
+
reason: "oversize",
|
|
184
|
+
bytes: knownBytes,
|
|
185
|
+
limit: MAX_SOURCE_BYTES
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
const smaller = await shrinkForTransport(asset, knownBytes);
|
|
190
|
+
if (smaller) {
|
|
191
|
+
({
|
|
192
|
+
base64,
|
|
193
|
+
uri,
|
|
194
|
+
mimeType
|
|
195
|
+
} = smaller);
|
|
196
|
+
resized = true;
|
|
197
|
+
}
|
|
198
|
+
} catch (e) {
|
|
199
|
+
}
|
|
200
|
+
const limit = resized ? MAX_SOURCE_BYTES : MAX_INLINE_BYTES;
|
|
201
|
+
if (!resized && !inline && knownBytes > limit) {
|
|
202
|
+
return {
|
|
203
|
+
status: "failed",
|
|
204
|
+
reason: "unshrunk",
|
|
205
|
+
bytes: knownBytes,
|
|
206
|
+
limit
|
|
207
|
+
};
|
|
63
208
|
}
|
|
64
|
-
if (!base64)
|
|
209
|
+
if (!base64) base64 = inline;
|
|
210
|
+
if (!base64 && uri) base64 = await readUriBase64(uri) || "";
|
|
211
|
+
if (!base64) return {
|
|
212
|
+
status: "failed",
|
|
213
|
+
reason: "unreadable",
|
|
214
|
+
bytes: 0,
|
|
215
|
+
limit
|
|
216
|
+
};
|
|
65
217
|
const size = base64Bytes(base64);
|
|
66
|
-
if (size < MIN_BYTES
|
|
67
|
-
|
|
68
|
-
|
|
218
|
+
if (size < MIN_BYTES) return {
|
|
219
|
+
status: "failed",
|
|
220
|
+
reason: "empty",
|
|
221
|
+
bytes: size,
|
|
222
|
+
limit
|
|
223
|
+
};
|
|
224
|
+
if (size > limit) return {
|
|
225
|
+
status: "failed",
|
|
226
|
+
reason: "oversize",
|
|
227
|
+
bytes: size,
|
|
228
|
+
limit
|
|
229
|
+
};
|
|
230
|
+
const picked = ((_d = asset.fileName) == null ? void 0 : _d.trim()) || `image-${Date.now()}-${index}.jpg`;
|
|
231
|
+
const name = resized ? picked.replace(/\.(heic|heif|png|webp)$/i, ".jpg") : picked;
|
|
69
232
|
return {
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
233
|
+
status: "ok",
|
|
234
|
+
attachment: {
|
|
235
|
+
id: `img-${Date.now()}-${index}`,
|
|
236
|
+
name,
|
|
237
|
+
type: kind,
|
|
238
|
+
mimeType,
|
|
239
|
+
dataUrl: `data:${mimeType};base64,${base64}`,
|
|
240
|
+
url: uri,
|
|
241
|
+
size
|
|
242
|
+
}
|
|
77
243
|
};
|
|
78
244
|
}
|
|
79
245
|
function loadPicker() {
|
|
@@ -109,8 +275,8 @@ function loadFileSystem() {
|
|
|
109
275
|
return require("expo-file-system");
|
|
110
276
|
}
|
|
111
277
|
const DOCUMENT_MIME_TYPES = ["application/pdf", "text/plain", "text/markdown", "text/csv", "application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", "image/*"];
|
|
112
|
-
const MAX_FILES =
|
|
113
|
-
const MAX_DOCUMENT_BYTES =
|
|
278
|
+
const MAX_FILES = 8;
|
|
279
|
+
const MAX_DOCUMENT_BYTES = 25 * 1024 * 1024;
|
|
114
280
|
function normalizeDocumentAssets(result) {
|
|
115
281
|
if (!result || result.canceled || result.type === "cancel") return [];
|
|
116
282
|
if (Array.isArray(result.assets) && result.assets.length > 0) return result.assets;
|
|
@@ -126,28 +292,65 @@ function normalizeDocumentAssets(result) {
|
|
|
126
292
|
}
|
|
127
293
|
async function documentToAttachment(asset, index) {
|
|
128
294
|
var _a, _b, _c, _d, _e;
|
|
295
|
+
const limit = MAX_DOCUMENT_BYTES;
|
|
129
296
|
const uri = (_a = asset.uri) == null ? void 0 : _a.trim();
|
|
130
|
-
if (!uri) return
|
|
131
|
-
|
|
297
|
+
if (!uri) return {
|
|
298
|
+
status: "failed",
|
|
299
|
+
reason: "unreadable",
|
|
300
|
+
bytes: 0,
|
|
301
|
+
limit
|
|
302
|
+
};
|
|
303
|
+
if (typeof asset.size === "number" && asset.size > limit) {
|
|
304
|
+
return {
|
|
305
|
+
status: "failed",
|
|
306
|
+
reason: "oversize",
|
|
307
|
+
bytes: asset.size,
|
|
308
|
+
limit
|
|
309
|
+
};
|
|
310
|
+
}
|
|
132
311
|
const fs = loadFileSystem();
|
|
133
312
|
const encoding = (_c = (_b = fs.EncodingType) == null ? void 0 : _b.Base64) != null ? _c : "base64";
|
|
134
|
-
if (typeof fs.readAsStringAsync !== "function") return
|
|
313
|
+
if (typeof fs.readAsStringAsync !== "function") return {
|
|
314
|
+
status: "failed",
|
|
315
|
+
reason: "unreadable",
|
|
316
|
+
bytes: 0,
|
|
317
|
+
limit
|
|
318
|
+
};
|
|
135
319
|
const base64 = (await fs.readAsStringAsync(uri, {
|
|
136
320
|
encoding
|
|
137
321
|
})).trim();
|
|
138
|
-
if (!base64) return
|
|
322
|
+
if (!base64) return {
|
|
323
|
+
status: "failed",
|
|
324
|
+
reason: "unreadable",
|
|
325
|
+
bytes: 0,
|
|
326
|
+
limit
|
|
327
|
+
};
|
|
139
328
|
const size = typeof asset.size === "number" && asset.size > 0 ? asset.size : base64Bytes(base64);
|
|
140
|
-
if (size < MIN_BYTES
|
|
329
|
+
if (size < MIN_BYTES) return {
|
|
330
|
+
status: "failed",
|
|
331
|
+
reason: "empty",
|
|
332
|
+
bytes: size,
|
|
333
|
+
limit
|
|
334
|
+
};
|
|
335
|
+
if (size > limit) return {
|
|
336
|
+
status: "failed",
|
|
337
|
+
reason: "oversize",
|
|
338
|
+
bytes: size,
|
|
339
|
+
limit
|
|
340
|
+
};
|
|
141
341
|
const mimeType = ((_d = asset.mimeType) == null ? void 0 : _d.trim()) || "application/octet-stream";
|
|
142
342
|
const name = ((_e = asset.name) == null ? void 0 : _e.trim()) || `file-${Date.now()}-${index}`;
|
|
143
343
|
return {
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
344
|
+
status: "ok",
|
|
345
|
+
attachment: {
|
|
346
|
+
id: `file-${Date.now()}-${index}`,
|
|
347
|
+
name,
|
|
348
|
+
type: "file",
|
|
349
|
+
mimeType,
|
|
350
|
+
dataUrl: `data:${mimeType};base64,${base64}`,
|
|
351
|
+
url: uri,
|
|
352
|
+
size
|
|
353
|
+
}
|
|
151
354
|
};
|
|
152
355
|
}
|
|
153
356
|
function useImageAttachments() {
|
|
@@ -155,7 +358,7 @@ function useImageAttachments() {
|
|
|
155
358
|
const [busyKind, setBusyKind] = useState(null);
|
|
156
359
|
const [error, setError] = useState(null);
|
|
157
360
|
const run = useCallback(async (mode) => {
|
|
158
|
-
var _a, _b, _c, _d;
|
|
361
|
+
var _a, _b, _c, _d, _e;
|
|
159
362
|
setError(null);
|
|
160
363
|
try {
|
|
161
364
|
const picker = loadPicker();
|
|
@@ -166,13 +369,14 @@ function useImageAttachments() {
|
|
|
166
369
|
}
|
|
167
370
|
setBusyKind(mode);
|
|
168
371
|
const representation = (_b = (_a = picker.UIImagePickerPreferredAssetRepresentationMode) == null ? void 0 : _a.Current) != null ? _b : "current";
|
|
372
|
+
const canShrink = typeof ((_c = loadImageManipulator()) == null ? void 0 : _c.manipulateAsync) === "function";
|
|
169
373
|
const options = __spreadValues(__spreadValues(__spreadValues({
|
|
170
|
-
base64:
|
|
374
|
+
base64: !canShrink,
|
|
171
375
|
allowsMultipleSelection: mode === "library",
|
|
172
376
|
mediaTypes: ["images"],
|
|
173
|
-
selectionLimit:
|
|
377
|
+
selectionLimit: MAX_FILES,
|
|
174
378
|
exif: false
|
|
175
|
-
}, ((
|
|
379
|
+
}, ((_d = picker.UIImagePickerPresentationStyle) == null ? void 0 : _d.OVER_FULL_SCREEN) ? {
|
|
176
380
|
presentationStyle: picker.UIImagePickerPresentationStyle.OVER_FULL_SCREEN
|
|
177
381
|
} : {}), mode === "camera" ? {
|
|
178
382
|
quality: PICKER_QUALITY
|
|
@@ -191,17 +395,28 @@ function useImageAttachments() {
|
|
|
191
395
|
}));
|
|
192
396
|
}
|
|
193
397
|
if (result.canceled) return;
|
|
194
|
-
const picked = (
|
|
398
|
+
const picked = (_e = result.assets) != null ? _e : [];
|
|
195
399
|
const mapped = [];
|
|
400
|
+
const failures = [];
|
|
196
401
|
for (let i = 0; i < picked.length; i += 1) {
|
|
197
402
|
const next = await assetToAttachment(picked[i], i, mode === "camera" ? "screenshot" : "file");
|
|
198
|
-
if (next) mapped.push(next);
|
|
403
|
+
if (next.status === "ok") mapped.push(next.attachment);
|
|
404
|
+
else failures.push(next);
|
|
199
405
|
}
|
|
200
406
|
if (mapped.length === 0) {
|
|
201
|
-
setError("
|
|
407
|
+
setError(failureMessage(failures, "image"));
|
|
202
408
|
return;
|
|
203
409
|
}
|
|
204
|
-
setPending((prev) =>
|
|
410
|
+
setPending((prev) => {
|
|
411
|
+
const {
|
|
412
|
+
accepted,
|
|
413
|
+
rejected
|
|
414
|
+
} = withinPendingBudget(prev, mapped);
|
|
415
|
+
if (rejected.length > 0) {
|
|
416
|
+
setError(`Only ${mb(MAX_PENDING_BYTES)} of attachments can be staged at once. ${rejected.length} left off.`);
|
|
417
|
+
}
|
|
418
|
+
return [...prev, ...accepted].slice(0, MAX_FILES);
|
|
419
|
+
});
|
|
205
420
|
} catch (e) {
|
|
206
421
|
setError(attachErrorMessage(e));
|
|
207
422
|
} finally {
|
|
@@ -223,15 +438,26 @@ function useImageAttachments() {
|
|
|
223
438
|
const assets = normalizeDocumentAssets(result);
|
|
224
439
|
if (assets.length === 0) return;
|
|
225
440
|
const mapped = [];
|
|
441
|
+
const failures = [];
|
|
226
442
|
for (let i = 0; i < assets.length; i += 1) {
|
|
227
443
|
const next = await documentToAttachment(assets[i], i);
|
|
228
|
-
if (next) mapped.push(next);
|
|
444
|
+
if (next.status === "ok") mapped.push(next.attachment);
|
|
445
|
+
else failures.push(next);
|
|
229
446
|
}
|
|
230
447
|
if (mapped.length === 0) {
|
|
231
|
-
setError("
|
|
448
|
+
setError(failureMessage(failures, "file"));
|
|
232
449
|
return;
|
|
233
450
|
}
|
|
234
|
-
setPending((prev) =>
|
|
451
|
+
setPending((prev) => {
|
|
452
|
+
const {
|
|
453
|
+
accepted,
|
|
454
|
+
rejected
|
|
455
|
+
} = withinPendingBudget(prev, mapped);
|
|
456
|
+
if (rejected.length > 0) {
|
|
457
|
+
setError(`Only ${mb(MAX_PENDING_BYTES)} of attachments can be staged at once. ${rejected.length} left off.`);
|
|
458
|
+
}
|
|
459
|
+
return [...prev, ...accepted].slice(0, MAX_FILES);
|
|
460
|
+
});
|
|
235
461
|
} catch (e) {
|
|
236
462
|
setError(e instanceof Error ? e.message : "Could not attach that file.");
|
|
237
463
|
} finally {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useImageAttachments.js","sources":["../../../src/features/attachments/useImageAttachments.ts"],"sourcesContent":["/**\n * Image attachments for the native composer.\n *\n * The transport was already there — `useChatStream.sendMessage(content,\n * attachments)` carries `MessageAttachment[]` and the gateway media lane is\n * covered by `aiwork/e2e-tests/gateway-media-upload.spec.ts`. What was missing\n * was any way to produce one on a phone: the composer shipped with\n * `image`/`camera`/`attach` hard-disabled, and nothing in the mobile package\n * touched `expo-image-picker` even though it is a dependency and the photo and\n * camera permission strings are already declared in `app.json`.\n *\n * Payload size is the whole game here. A modern iPhone photo is ~3-5 MB and\n * ~4000px wide; base64 inflates that by a third, and it travels inline on the\n * chat message. Camera captures can be JPEG-compressed via `quality`. Library\n * picks must NOT pass `quality`: that asks iOS for `public.jpeg` and fails on\n * HEIC / iCloud photos with \"Cannot load representation of type public.jpeg\".\n * The canvas picker already uses `Current` for that reason.\n */\nimport { useCallback, useMemo, useState } from 'react';\nimport type { MessageAttachment } from '../../hooks/useChatStream';\n\n/** Longest edge, in px, we send. Plenty for a model to read; ~10x smaller than source. */\nconst MAX_EDGE = 1280;\n/** JPEG quality handed to the picker (0-1). */\nconst PICKER_QUALITY = 0.7;\n/** Refuse anything above this after re-encoding — a send is better failed than hung. */\nconst MAX_BYTES = 4 * 1024 * 1024;\n/** Nothing sensible is this small; treat as a failed decode. */\nconst MIN_BYTES = 64;\n\nexport type AttachmentBusyKind = 'camera' | 'library' | 'documents' | null;\n\nexport interface ImageAttachmentsApi {\n /** Attachments staged for the next send. */\n pending: MessageAttachment[];\n /** True while any picker/encode is in flight. */\n busy: boolean;\n /** Which toolbar control is waiting — only that one should spin. */\n busyKind: AttachmentBusyKind;\n /** Human-readable failure for the composer's error banner, or null. */\n error: string | null;\n pickFromLibrary: () => Promise<void>;\n captureFromCamera: () => Promise<void>;\n pickDocuments: () => Promise<void>;\n remove: (id: string) => void;\n clear: () => void;\n /** Pass to `sendMessage` — undefined when empty, which is what it expects. */\n forSend: () => MessageAttachment[] | undefined;\n}\n\ntype PickedAsset = {\n uri?: string | null;\n base64?: string | null;\n mimeType?: string | null;\n fileName?: string | null;\n fileSize?: number | null;\n width?: number | null;\n height?: number | null;\n};\n\n/** Base64 decodes to 3 bytes per 4 chars, minus `=` padding. */\nfunction base64Bytes(base64: string): number {\n const padding = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0;\n return Math.floor((base64.length * 3) / 4) - padding;\n}\n\nfunction isJpegRepresentationError(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : String(err ?? '');\n return /public\\.jpeg|Failed to read picked image/i.test(msg);\n}\n\nfunction attachErrorMessage(err: unknown): string {\n if (isJpegRepresentationError(err)) {\n return 'Could not read that photo. Try another one, or save it to Recents first.';\n }\n return err instanceof Error ? err.message : 'Could not attach that image.';\n}\n\nfunction guessImageMime(asset: PickedAsset): string {\n const mime = asset.mimeType?.trim();\n if (mime) return mime;\n const name = `${asset.fileName ?? ''} ${asset.uri ?? ''}`;\n if (/\\.png(\\?|$)/i.test(name)) return 'image/png';\n if (/\\.gif(\\?|$)/i.test(name)) return 'image/gif';\n if (/\\.webp(\\?|$)/i.test(name)) return 'image/webp';\n if (/\\.(heic|heif)(\\?|$)/i.test(name)) return 'image/heic';\n return 'image/jpeg';\n}\n\nasync function readUriBase64(uri: string): Promise<string | null> {\n const fs = loadFileSystem() as {\n readAsStringAsync?: (uri: string, options?: { encoding?: string }) => Promise<string>;\n EncodingType?: { Base64?: string };\n };\n if (typeof fs.readAsStringAsync !== 'function') return null;\n const encoding = fs.EncodingType?.Base64 ?? 'base64';\n const base64 = (await fs.readAsStringAsync(uri, { encoding })).trim();\n return base64 || null;\n}\n\nasync function assetToAttachment(\n asset: PickedAsset,\n index: number,\n kind: MessageAttachment['type'] = 'file',\n): Promise<MessageAttachment | null> {\n let base64 = asset.base64?.trim() || '';\n if (!base64 && asset.uri?.trim()) {\n base64 = (await readUriBase64(asset.uri.trim())) || '';\n }\n if (!base64) return null;\n const size = base64Bytes(base64);\n if (size < MIN_BYTES || size > MAX_BYTES) return null;\n const mimeType = guessImageMime(asset);\n const name = asset.fileName?.trim() || `image-${Date.now()}-${index}.jpg`;\n return {\n id: `img-${Date.now()}-${index}`,\n name,\n type: kind,\n mimeType,\n dataUrl: `data:${mimeType};base64,${base64}`,\n url: asset.uri?.trim() || undefined,\n size,\n };\n}\n\ntype PickedDocument = {\n uri?: string | null;\n name?: string | null;\n mimeType?: string | null;\n size?: number | null;\n};\n\n/**\n * Lazily required so a unit test or a non-Expo bundle importing this hook does\n * not hard-fail on the native module.\n */\nfunction loadPicker() {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require\n return require('expo-image-picker') as typeof import('expo-image-picker');\n}\n\nfunction loadDocumentPicker(): {\n getDocumentAsync: (options: {\n type?: string | string[];\n multiple?: boolean;\n copyToCacheDirectory?: boolean;\n }) => Promise<{\n canceled?: boolean;\n type?: string;\n uri?: string;\n name?: string;\n mimeType?: string;\n size?: number;\n assets?: PickedDocument[];\n }>;\n} {\n // Staging/dev-client binaries only include modules that are dependencies +\n // autolinked at EAS/prebuild time. Expo Go already ships ExpoDocumentPicker,\n // which is why paperclip works locally without that native rebuild.\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require\n const core = require('expo-modules-core') as {\n requireOptionalNativeModule?: (name: string) => { getDocumentAsync?: Function } | null;\n };\n const native = core.requireOptionalNativeModule?.('ExpoDocumentPicker');\n if (native?.getDocumentAsync) {\n return {\n getDocumentAsync: (options) =>\n native.getDocumentAsync({\n type: Array.isArray(options.type) ? options.type : [options.type ?? '*/*'],\n multiple: options.multiple ?? false,\n copyToCacheDirectory: options.copyToCacheDirectory ?? true,\n }) as Promise<{\n canceled?: boolean;\n type?: string;\n uri?: string;\n name?: string;\n mimeType?: string;\n size?: number;\n assets?: PickedDocument[];\n }>,\n };\n }\n // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require\n return require('expo-document-picker') as typeof import('expo-document-picker');\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err ?? '');\n if (/Cannot find native module|ExpoDocumentPicker|Cannot find module/i.test(msg)) {\n throw new Error(\n 'File picker is not included in this app build. Use Photos, or install a staging build that includes expo-document-picker.',\n );\n }\n throw err;\n }\n}\n\nfunction loadFileSystem() {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require\n return require('expo-file-system') as typeof import('expo-file-system');\n}\n\n/** Web `ACCEPTED_FILE_TYPES` — docs + images. */\nconst DOCUMENT_MIME_TYPES = [\n 'application/pdf',\n 'text/plain',\n 'text/markdown',\n 'text/csv',\n 'application/msword',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'image/*',\n];\nconst MAX_FILES = 6;\nconst MAX_DOCUMENT_BYTES = 15 * 1024 * 1024;\n\nfunction normalizeDocumentAssets(result: {\n canceled?: boolean;\n type?: string;\n uri?: string;\n name?: string;\n mimeType?: string;\n size?: number;\n assets?: PickedDocument[];\n}): PickedDocument[] {\n if (!result || result.canceled || result.type === 'cancel') return [];\n if (Array.isArray(result.assets) && result.assets.length > 0) return result.assets;\n if (result.uri) {\n return [{ uri: result.uri, name: result.name, mimeType: result.mimeType, size: result.size }];\n }\n return [];\n}\n\nasync function documentToAttachment(asset: PickedDocument, index: number): Promise<MessageAttachment | null> {\n const uri = asset.uri?.trim();\n if (!uri) return null;\n if (typeof asset.size === 'number' && asset.size > MAX_DOCUMENT_BYTES) return null;\n\n const fs = loadFileSystem() as {\n readAsStringAsync?: (uri: string, options?: { encoding?: string }) => Promise<string>;\n EncodingType?: { Base64?: string };\n };\n const encoding = fs.EncodingType?.Base64 ?? 'base64';\n if (typeof fs.readAsStringAsync !== 'function') return null;\n const base64 = (await fs.readAsStringAsync(uri, { encoding })).trim();\n if (!base64) return null;\n const size = typeof asset.size === 'number' && asset.size > 0 ? asset.size : base64Bytes(base64);\n if (size < MIN_BYTES || size > MAX_DOCUMENT_BYTES) return null;\n const mimeType = asset.mimeType?.trim() || 'application/octet-stream';\n const name = asset.name?.trim() || `file-${Date.now()}-${index}`;\n return {\n id: `file-${Date.now()}-${index}`,\n name,\n type: 'file',\n mimeType,\n dataUrl: `data:${mimeType};base64,${base64}`,\n url: uri,\n size,\n };\n}\n\nexport function useImageAttachments(): ImageAttachmentsApi {\n const [pending, setPending] = useState<MessageAttachment[]>([]);\n const [busyKind, setBusyKind] = useState<AttachmentBusyKind>(null);\n const [error, setError] = useState<string | null>(null);\n\n const run = useCallback(async (mode: 'library' | 'camera') => {\n setError(null);\n try {\n const picker = loadPicker();\n\n const permission =\n mode === 'camera'\n ? await picker.requestCameraPermissionsAsync()\n : await picker.requestMediaLibraryPermissionsAsync();\n if (!permission.granted) {\n setError(\n mode === 'camera'\n ? 'Camera access is off for Yantra. Turn it on in Settings to attach a photo.'\n : 'Photo access is off for Yantra. Turn it on in Settings to attach an image.',\n );\n return;\n }\n\n // Spin only the control that was tapped, and only after permission\n // so the iOS prompt does not turn camera+gallery+attach into loaders.\n setBusyKind(mode);\n const representation =\n picker.UIImagePickerPreferredAssetRepresentationMode?.Current ?? ('current' as never);\n const options: import('expo-image-picker').ImagePickerOptions = {\n base64: true,\n allowsMultipleSelection: mode === 'library',\n mediaTypes: ['images'],\n selectionLimit: 4,\n exif: false,\n ...(picker.UIImagePickerPresentationStyle?.OVER_FULL_SCREEN\n ? { presentationStyle: picker.UIImagePickerPresentationStyle.OVER_FULL_SCREEN }\n : {}),\n ...(mode === 'camera' ? { quality: PICKER_QUALITY } : {}),\n ...(mode === 'library' ? { preferredAssetRepresentationMode: representation } : {}),\n };\n\n let result: import('expo-image-picker').ImagePickerResult;\n try {\n result =\n mode === 'camera'\n ? await picker.launchCameraAsync({ ...options, allowsMultipleSelection: false })\n : await picker.launchImageLibraryAsync(options);\n } catch (e) {\n if (mode !== 'library' || !isJpegRepresentationError(e)) throw e;\n result = await picker.launchImageLibraryAsync({ ...options, base64: false });\n }\n\n if (result.canceled) return;\n\n const picked = result.assets ?? [];\n const mapped: MessageAttachment[] = [];\n for (let i = 0; i < picked.length; i += 1) {\n const next = await assetToAttachment(\n picked[i] as PickedAsset,\n i,\n mode === 'camera' ? 'screenshot' : 'file',\n );\n if (next) mapped.push(next);\n }\n\n if (mapped.length === 0) {\n setError('That image was too large to attach. Try a smaller one.');\n return;\n }\n setPending((prev) => [...prev, ...mapped].slice(0, MAX_FILES));\n } catch (e) {\n setError(attachErrorMessage(e));\n } finally {\n setBusyKind(null);\n }\n }, []);\n\n const pickFromLibrary = useCallback(() => run('library'), [run]);\n const captureFromCamera = useCallback(() => run('camera'), [run]);\n const pickDocuments = useCallback(async () => {\n setError(null);\n try {\n const picker = loadDocumentPicker();\n setBusyKind('documents');\n const result = await picker.getDocumentAsync({\n type: DOCUMENT_MIME_TYPES,\n multiple: true,\n copyToCacheDirectory: true,\n });\n const assets = normalizeDocumentAssets(result as Parameters<typeof normalizeDocumentAssets>[0]);\n if (assets.length === 0) return;\n\n const mapped: MessageAttachment[] = [];\n for (let i = 0; i < assets.length; i += 1) {\n const next = await documentToAttachment(assets[i], i);\n if (next) mapped.push(next);\n }\n if (mapped.length === 0) {\n setError('That file was too large to attach. Try a smaller one.');\n return;\n }\n setPending((prev) => [...prev, ...mapped].slice(0, MAX_FILES));\n } catch (e) {\n setError(e instanceof Error ? e.message : 'Could not attach that file.');\n } finally {\n setBusyKind(null);\n }\n }, []);\n const remove = useCallback((id: string) => setPending((prev) => prev.filter((a) => a.id !== id)), []);\n const clear = useCallback(() => setPending([]), []);\n const forSend = useCallback(() => (pending.length > 0 ? pending.map((a) => ({ ...a })) : undefined), [pending]);\n const busy = busyKind !== null;\n\n return useMemo(\n () => ({\n pending,\n busy,\n busyKind,\n error,\n pickFromLibrary,\n captureFromCamera,\n pickDocuments,\n remove,\n clear,\n forSend,\n }),\n [pending, busy, busyKind, error, pickFromLibrary, captureFromCamera, pickDocuments, remove, clear, forSend],\n );\n}\n\nexport const IMAGE_ATTACHMENT_LIMITS = { MAX_EDGE, MAX_BYTES, PICKER_QUALITY } as const;\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;AAwBA,MAAM,cAAiB,GAAA,GAAA;AAEvB,MAAM,SAAA,GAAY,IAAI,IAAO,GAAA,IAAA;AAE7B,MAAM,SAAY,GAAA,EAAA;AA8BlB,SAAS,YAAY,MAAwB,EAAA;AAC3C,EAAM,MAAA,OAAA,GAAU,MAAO,CAAA,QAAA,CAAS,IAAI,CAAA,GAAI,IAAI,MAAO,CAAA,QAAA,CAAS,GAAG,CAAA,GAAI,CAAI,GAAA,CAAA;AACvE,EAAA,OAAO,KAAK,KAAM,CAAA,MAAA,CAAO,MAAS,GAAA,CAAA,GAAI,CAAC,CAAI,GAAA,OAAA;AAC7C;AACA,SAAS,0BAA0B,GAAuB,EAA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,EAAA,KAAe,WAAW,CAAQ,IAAA,KAAA,IAAA,CAAK,MAAO,CAAA,CAAA,CAAA,KAAK,EAAE,EAAO,KAAA,EAAE,CAAC,CAAA,EAAG,EAAE,CAAA;AAChG,EAAM,MAAA,KAAA,GAAQ,YAAY,MAAM,UAAA,CAAW,EAAE,CAAA,EAAG,EAAE,CAAA;AAClD,EAAA,MAAM,OAAU,GAAA,WAAA,CAAY,MAAM,OAAA,CAAQ,SAAS,CAAI,GAAA,OAAA,CAAQ,GAAI,CAAA,CAAA,CAAA,KAAM,mBACpE,CACH,CAAA,CAAA,GAAI,MAAW,EAAA,CAAC,OAAO,CAAC,CAAA;AAC1B,EAAA,MAAM,OAAO,QAAa,KAAA,IAAA;AAC1B,EAAA,OAAO,QAAQ,OAAO;AAAA,IACpB,OAAA;AAAA,IACA,IAAA;AAAA,IACA,QAAA;AAAA,IACA,KAAA;AAAA,IACA,eAAA;AAAA,IACA,iBAAA;AAAA,IACA,aAAA;AAAA,IACA,MAAA;AAAA,IACA,KAAA;AAAA,IACA;AAAA,GACE,CAAA,EAAA,CAAC,OAAS,EAAA,IAAA,EAAM,QAAU,EAAA,KAAA,EAAO,eAAiB,EAAA,iBAAA,EAAmB,aAAe,EAAA,MAAA,EAAQ,KAAO,EAAA,OAAO,CAAC,CAAA;AACjH"}
|
|
1
|
+
{"version":3,"file":"useImageAttachments.js","sources":["../../../src/features/attachments/useImageAttachments.ts"],"sourcesContent":["/**\n * Image attachments for the native composer.\n *\n * The transport was already there — `useChatStream.sendMessage(content,\n * attachments)` carries `MessageAttachment[]` and the gateway media lane is\n * covered by `aiwork/e2e-tests/gateway-media-upload.spec.ts`. What was missing\n * was any way to produce one on a phone: the composer shipped with\n * `image`/`camera`/`attach` hard-disabled, and nothing in the mobile package\n * touched `expo-image-picker` even though it is a dependency and the photo and\n * camera permission strings are already declared in `app.json`.\n *\n * Payload size is the whole game here. A modern iPhone photo is ~3-5 MB and\n * ~4000px wide; base64 inflates that by a third, and it travels inline on the\n * chat message. Camera captures can be JPEG-compressed via `quality`. Library\n * picks must NOT pass `quality`: that asks iOS for `public.jpeg` and fails on\n * HEIC / iCloud photos with \"Cannot load representation of type public.jpeg\".\n * The canvas picker already uses `Current` for that reason.\n *\n * `MAX_EDGE` is not our invention, it is the resize the models apply anyway.\n * Claude keeps 2576px on the long edge (4.7+ high-resolution tier, 1568px on\n * older models) and downscales everything above it before it ever sees the\n * image; OpenAI caps the long edge at 2000px. So a 4032px capture spends 3x\n * the bytes on pixels that are thrown away upstream. Downscaling on the device\n * is free fidelity-wise and is what keeps us clear of every byte ceiling in\n * the chain: measured on real 12MP iPhone photos, 2.9MB -> 1.4MB.\n *\n * The resize is therefore what decides whether a photo can be attached at all,\n * not the byte ceiling - so it triggers on bytes as well as pixels (a 2000px\n * PNG screenshot is inside `MAX_EDGE` and can still be 12MB) and keeps\n * tightening until it fits rather than giving up.\n *\n * The contract this file owes a person: hand it anything a phone can produce,\n * up to `MAX_SOURCE_BYTES`, and sizing is our problem, not theirs. Nobody\n * should be told to go find a smaller photo. That means shrinking is attempted\n * before any ceiling is consulted, and the only refusals left are \"bigger than\n * we will even open\" and \"this build has no resizer and the raw bytes cannot\n * fit inline\" - the second disappears once `expo-image-manipulator` is in the\n * binary.\n */\nimport { useCallback, useMemo, useState } from 'react';\nimport type { MessageAttachment } from '../../hooks/useChatStream';\n\n/** Longest edge, in px, we send. Matches Claude's high-resolution tier ceiling. */\nconst MAX_EDGE = 2576;\n/**\n * Long edge for a second, tighter pass when one resize still will not fit.\n * Claude's standard tier, so every model keeps all of it.\n */\nconst FALLBACK_EDGE = 1568;\n/** JPEG quality handed to the picker for a camera capture (0-1). */\nconst PICKER_QUALITY = 0.7;\n/**\n * JPEG quality for our own re-encode. Higher than the picker's: a 2576px frame\n * is already small, and the camera's headline use per `app.json` is \"a photo of\n * a document you want help with\" - text is the first thing heavy JPEG\n * compression destroys.\n */\nconst RESIZE_QUALITY = 0.8;\n/** Harder compress for the second pass. Still readable; the point is to fit. */\nconst FALLBACK_QUALITY = 0.6;\n/**\n * What one image should weigh by the time it is on the wire. This is not our\n * number: an image turn always takes the inline-bytes lane (`useChatStream`\n * sends `buildGatewayMedia(..., includeData)` whenever any attachment is an\n * image), and cdecli's resolver drops anything heavier - `chat_media.go`\n * `defaultChatMediaLimits` is 5MB per image and 8 images, tunable with\n * `CDECLI_CHAT_MAX_IMAGE_BYTES` / `CDECLI_CHAT_MAX_IMAGES`. Raising the number\n * here alone would not make a bigger photo arrive.\n */\nconst TARGET_BYTES = 5 * 1024 * 1024;\n/**\n * Absolute ceiling for bytes travelling inline, which is every image turn and\n * any document sharing one. `buildGatewayMedia`'s inline cap is 14e6 base64\n * chars, so ~10MB decoded is the most that can survive the trip. Only reached\n * when nothing shrank the image.\n */\nconst MAX_INLINE_BYTES = 10 * 1024 * 1024;\n/**\n * What a person is allowed to hand us. Deliberately far above anything a phone\n * camera produces (a 48MP JPEG is ~10MB, an iPhone ProRAW ~25MB) so that taking\n * a picture and attaching it never involves thinking about bytes. Everything up\n * to here is ours to shrink. Above it we refuse rather than pull the file into\n * a JS string, because that is how a memory-tight phone loses the app mid-pick.\n */\nconst MAX_SOURCE_BYTES = 50 * 1024 * 1024;\n/**\n * Tried in order until one lands under `TARGET_BYTES`. Three passes take even a\n * 50MB panorama well under it; the last is deliberately small because arriving\n * readable beats not arriving.\n */\nconst SHRINK_PASSES: Array<{ edge: number; quality: number }> = [\n { edge: MAX_EDGE, quality: RESIZE_QUALITY },\n { edge: FALLBACK_EDGE, quality: FALLBACK_QUALITY },\n { edge: 1024, quality: 0.5 },\n];\n/**\n * Ceiling on everything staged at once. Per-file limits do not bound the peak -\n * `MAX_FILES` of them do - and this is the number that decides whether the\n * composer can push the process into the range iOS reclaims from.\n */\nconst MAX_PENDING_BYTES = 32 * 1024 * 1024;\n/** Nothing sensible is this small; treat as a failed decode. */\nconst MIN_BYTES = 64;\n\nexport type AttachmentBusyKind = 'camera' | 'library' | 'documents' | null;\n\nexport interface ImageAttachmentsApi {\n /** Attachments staged for the next send. */\n pending: MessageAttachment[];\n /** True while any picker/encode is in flight. */\n busy: boolean;\n /** Which toolbar control is waiting — only that one should spin. */\n busyKind: AttachmentBusyKind;\n /** Human-readable failure for the composer's error banner, or null. */\n error: string | null;\n pickFromLibrary: () => Promise<void>;\n captureFromCamera: () => Promise<void>;\n pickDocuments: () => Promise<void>;\n remove: (id: string) => void;\n clear: () => void;\n /** Pass to `sendMessage` — undefined when empty, which is what it expects. */\n forSend: () => MessageAttachment[] | undefined;\n}\n\ntype PickedAsset = {\n uri?: string | null;\n base64?: string | null;\n mimeType?: string | null;\n fileName?: string | null;\n fileSize?: number | null;\n width?: number | null;\n height?: number | null;\n};\n\n/** Base64 decodes to 3 bytes per 4 chars, minus `=` padding. */\nfunction base64Bytes(base64: string): number {\n const padding = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0;\n return Math.floor((base64.length * 3) / 4) - padding;\n}\n\nfunction isJpegRepresentationError(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : String(err ?? '');\n return /public\\.jpeg|Failed to read picked image/i.test(msg);\n}\n\nfunction attachErrorMessage(err: unknown): string {\n if (isJpegRepresentationError(err)) {\n return 'Could not read that photo. Try another one, or save it to Recents first.';\n }\n return err instanceof Error ? err.message : 'Could not attach that image.';\n}\n\nfunction guessImageMime(asset: PickedAsset): string {\n const mime = asset.mimeType?.trim();\n if (mime) return mime;\n const name = `${asset.fileName ?? ''} ${asset.uri ?? ''}`;\n if (/\\.png(\\?|$)/i.test(name)) return 'image/png';\n if (/\\.gif(\\?|$)/i.test(name)) return 'image/gif';\n if (/\\.webp(\\?|$)/i.test(name)) return 'image/webp';\n if (/\\.(heic|heif)(\\?|$)/i.test(name)) return 'image/heic';\n return 'image/jpeg';\n}\n\nasync function readUriBase64(uri: string): Promise<string | null> {\n const fs = loadFileSystem() as {\n readAsStringAsync?: (uri: string, options?: { encoding?: string }) => Promise<string>;\n EncodingType?: { Base64?: string };\n };\n if (typeof fs.readAsStringAsync !== 'function') return null;\n const encoding = fs.EncodingType?.Base64 ?? 'base64';\n const base64 = (await fs.readAsStringAsync(uri, { encoding })).trim();\n return base64 || null;\n}\n\n/**\n * Lazily required like the pickers. A binary built before this module became a\n * dependency has no native side, so a miss is expected, not exceptional - the\n * caller falls back to sending the original bytes under `MAX_INLINE_BYTES`.\n */\nfunction loadImageManipulator(): {\n manipulateAsync?: (\n uri: string,\n actions: Array<{ resize: { width?: number; height?: number } }>,\n options: { compress?: number; format?: unknown; base64?: boolean },\n ) => Promise<{ uri?: string; base64?: string | null }>;\n SaveFormat?: { JPEG?: string };\n} | null {\n try {\n // import/no-unresolved: optional by design - the require is allowed to\n // miss on a binary that predates the dependency, which is the whole\n // reason this is a lazy require rather than a top-level import.\n // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require, import/no-unresolved\n return require('expo-image-manipulator');\n } catch {\n return null;\n }\n}\n\ntype Resized = { base64: string; uri: string; mimeType: string };\n\n/**\n * Shrink until the image fits the wire. Null means \"send the original as-is\":\n * either the module is missing or the photo is already small enough, both of\n * which are fine. Re-encoding also transcodes HEIC, so a resized pick stops\n * depending on the agent understanding `image/heic`.\n *\n * `knownBytes` is 0 when the picker reported neither a size nor inline bytes;\n * pixels alone then decide, which is the pre-existing behaviour.\n */\nasync function shrinkForTransport(asset: PickedAsset, knownBytes: number): Promise<Resized | null> {\n const uri = asset.uri?.trim();\n if (!uri) return null;\n\n const width = asset.width ?? 0;\n const height = asset.height ?? 0;\n const longEdge = Math.max(width, height);\n if (longEdge <= MAX_EDGE && knownBytes <= TARGET_BYTES) return null;\n\n const manipulator = loadImageManipulator();\n const manipulate = manipulator?.manipulateAsync;\n if (typeof manipulate !== 'function') return null;\n\n // Constrain the long edge only, so the other one follows the aspect ratio.\n // Never above the source: when it is bytes rather than pixels that put us\n // here, the re-encode is there to compress, not to invent resolution.\n const encode = async (edge: number, quality: number): Promise<Resized | null> => {\n const capped = longEdge > 0 ? Math.min(edge, longEdge) : edge;\n const resize = height > width ? { height: capped } : { width: capped };\n const out = await manipulate(uri, [{ resize }], {\n compress: quality,\n format: manipulator?.SaveFormat?.JPEG ?? 'jpeg',\n base64: true,\n });\n const base64 = out.base64?.trim() || (out.uri ? await readUriBase64(out.uri) : null);\n return base64 ? { base64, uri: out.uri || uri, mimeType: 'image/jpeg' } : null;\n };\n\n // Keep tightening until it fits. Refusing a photo we could obviously have\n // carried is the one outcome this function exists to prevent.\n let best: Resized | null = null;\n let bestBytes = Number.POSITIVE_INFINITY;\n for (const pass of SHRINK_PASSES) {\n // Sequential on purpose: each pass exists only because the previous one\n // came back too heavy, and running them together would encode a 50MB\n // photo three times over on a phone.\n const out = await encode(pass.edge, pass.quality);\n if (out) {\n const bytes = base64Bytes(out.base64);\n if (bytes < bestBytes) {\n best = out;\n bestBytes = bytes;\n }\n if (bytes <= TARGET_BYTES) break;\n }\n }\n return best;\n}\n\n/**\n * Why an asset did not become an attachment. The composer used to collapse all\n * of these into \"too large\", which sent people hunting for a smaller photo when\n * the bytes were never the problem.\n */\n// A string discriminant, not a boolean: this repo compiles without\n// `strictNullChecks`, and TS only narrows boolean discriminants under it.\ntype AttachFailure = {\n status: 'failed';\n reason: 'unreadable' | 'empty' | 'oversize' | 'unshrunk';\n bytes: number;\n limit: number;\n};\ntype AttachOutcome = { status: 'ok'; attachment: MessageAttachment } | AttachFailure;\n\nfunction mb(bytes: number): string {\n return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;\n}\n\n/** Bytes already staged, so a pick cannot walk the process into eviction range. */\nfunction stagedBytes(attachments: MessageAttachment[]): number {\n return attachments.reduce((total, a) => total + (a.size ?? 0), 0);\n}\n\n/**\n * Take attachments while they fit the shared budget. Whatever does not fit is\n * reported rather than silently dropped.\n */\nfunction withinPendingBudget(\n existing: MessageAttachment[],\n incoming: MessageAttachment[],\n): { accepted: MessageAttachment[]; rejected: MessageAttachment[] } {\n let used = stagedBytes(existing);\n const accepted: MessageAttachment[] = [];\n const rejected: MessageAttachment[] = [];\n for (const attachment of incoming) {\n const size = attachment.size ?? 0;\n if (used + size > MAX_PENDING_BYTES) {\n rejected.push(attachment);\n } else {\n used += size;\n accepted.push(attachment);\n }\n }\n return { accepted, rejected };\n}\n\nfunction failureMessage(failures: AttachFailure[], noun: 'image' | 'file'): string {\n // Not the person's fault and not about their photo: this build simply has no\n // resizer, so say that instead of sending them hunting for a smaller one.\n const unshrunk = failures.find((f) => f.reason === 'unshrunk');\n if (unshrunk) {\n return `This app version cannot resize a ${mb(unshrunk.bytes)} ${noun} before sending. Update the app, or attach a smaller one.`;\n }\n const oversize = failures.find((f) => f.reason === 'oversize');\n if (oversize) {\n return `That ${noun} is ${mb(oversize.bytes)} and the limit is ${mb(oversize.limit)}. Try a smaller one.`;\n }\n if (noun === 'image') {\n return 'Could not read that photo. Try another one, or save it to Recents first.';\n }\n return 'Could not read that file. Try another one.';\n}\n\nasync function assetToAttachment(\n asset: PickedAsset,\n index: number,\n kind: MessageAttachment['type'] = 'file',\n): Promise<AttachOutcome> {\n let mimeType = guessImageMime(asset);\n let uri = asset.uri?.trim() || undefined;\n let base64 = '';\n let resized = false;\n\n const inline = asset.base64?.trim() || '';\n // Feed the shrink decision whatever the picker already told us, so size can\n // trigger it even when the pixel count looks innocent.\n const knownBytes = inline ? base64Bytes(inline) : (asset.fileSize ?? 0);\n\n if (knownBytes > MAX_SOURCE_BYTES) {\n return { status: 'failed', reason: 'oversize', bytes: knownBytes, limit: MAX_SOURCE_BYTES };\n }\n\n try {\n const smaller = await shrinkForTransport(asset, knownBytes);\n if (smaller) {\n ({ base64, uri, mimeType } = smaller);\n resized = true;\n }\n } catch {\n // A manipulator failure is never fatal - the original bytes still send.\n }\n\n // Nothing shrank it, so the original has to travel as-is. That is the only\n // case where the inline ceiling is the person's problem, and it goes away\n // once the binary carries a resizer.\n const limit = resized ? MAX_SOURCE_BYTES : MAX_INLINE_BYTES;\n if (!resized && !inline && knownBytes > limit) {\n return { status: 'failed', reason: 'unshrunk', bytes: knownBytes, limit };\n }\n\n if (!base64) base64 = inline;\n if (!base64 && uri) base64 = (await readUriBase64(uri)) || '';\n\n if (!base64) return { status: 'failed', reason: 'unreadable', bytes: 0, limit };\n const size = base64Bytes(base64);\n if (size < MIN_BYTES) return { status: 'failed', reason: 'empty', bytes: size, limit };\n if (size > limit) return { status: 'failed', reason: 'oversize', bytes: size, limit };\n\n const picked = asset.fileName?.trim() || `image-${Date.now()}-${index}.jpg`;\n // A resized asset is JPEG now, so a carried-over .HEIC name would lie.\n const name = resized ? picked.replace(/\\.(heic|heif|png|webp)$/i, '.jpg') : picked;\n return {\n status: 'ok',\n attachment: {\n id: `img-${Date.now()}-${index}`,\n name,\n type: kind,\n mimeType,\n dataUrl: `data:${mimeType};base64,${base64}`,\n url: uri,\n size,\n },\n };\n}\n\ntype PickedDocument = {\n uri?: string | null;\n name?: string | null;\n mimeType?: string | null;\n size?: number | null;\n};\n\n/**\n * Lazily required so a unit test or a non-Expo bundle importing this hook does\n * not hard-fail on the native module.\n */\nfunction loadPicker() {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require\n return require('expo-image-picker') as typeof import('expo-image-picker');\n}\n\nfunction loadDocumentPicker(): {\n getDocumentAsync: (options: {\n type?: string | string[];\n multiple?: boolean;\n copyToCacheDirectory?: boolean;\n }) => Promise<{\n canceled?: boolean;\n type?: string;\n uri?: string;\n name?: string;\n mimeType?: string;\n size?: number;\n assets?: PickedDocument[];\n }>;\n} {\n // Staging/dev-client binaries only include modules that are dependencies +\n // autolinked at EAS/prebuild time. Expo Go already ships ExpoDocumentPicker,\n // which is why paperclip works locally without that native rebuild.\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require\n const core = require('expo-modules-core') as {\n requireOptionalNativeModule?: (name: string) => { getDocumentAsync?: Function } | null;\n };\n const native = core.requireOptionalNativeModule?.('ExpoDocumentPicker');\n if (native?.getDocumentAsync) {\n return {\n getDocumentAsync: (options) =>\n native.getDocumentAsync({\n type: Array.isArray(options.type) ? options.type : [options.type ?? '*/*'],\n multiple: options.multiple ?? false,\n copyToCacheDirectory: options.copyToCacheDirectory ?? true,\n }) as Promise<{\n canceled?: boolean;\n type?: string;\n uri?: string;\n name?: string;\n mimeType?: string;\n size?: number;\n assets?: PickedDocument[];\n }>,\n };\n }\n // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require\n return require('expo-document-picker') as typeof import('expo-document-picker');\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err ?? '');\n if (/Cannot find native module|ExpoDocumentPicker|Cannot find module/i.test(msg)) {\n throw new Error(\n 'File picker is not included in this app build. Use Photos, or install a staging build that includes expo-document-picker.',\n );\n }\n throw err;\n }\n}\n\nfunction loadFileSystem() {\n // eslint-disable-next-line @typescript-eslint/no-require-imports, global-require\n return require('expo-file-system') as typeof import('expo-file-system');\n}\n\n/** Web `ACCEPTED_FILE_TYPES` — docs + images. */\nconst DOCUMENT_MIME_TYPES = [\n 'application/pdf',\n 'text/plain',\n 'text/markdown',\n 'text/csv',\n 'application/msword',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'image/*',\n];\n/** Matches cdecli's `chat_media.go` `maxImages`, so every slot can reach the model. */\nconst MAX_FILES = 8;\n/**\n * Lower than a photo's `MAX_SOURCE_BYTES`, and deliberately so: a photo is\n * shrunk to ~1.4MB before anything retains it, while a document has nothing to\n * shrink and is held whole as a base64 string. At 50MB x `MAX_FILES` that is\n * ~500MB resident on a phone that iOS is already evicting for its footprint\n * ([[mobile-app-terminated-on-background]]). 25MB per file, bounded by\n * `MAX_PENDING_BYTES` in total, is the most this lane can actually carry.\n */\nconst MAX_DOCUMENT_BYTES = 25 * 1024 * 1024;\n\nfunction normalizeDocumentAssets(result: {\n canceled?: boolean;\n type?: string;\n uri?: string;\n name?: string;\n mimeType?: string;\n size?: number;\n assets?: PickedDocument[];\n}): PickedDocument[] {\n if (!result || result.canceled || result.type === 'cancel') return [];\n if (Array.isArray(result.assets) && result.assets.length > 0) return result.assets;\n if (result.uri) {\n return [{ uri: result.uri, name: result.name, mimeType: result.mimeType, size: result.size }];\n }\n return [];\n}\n\nasync function documentToAttachment(asset: PickedDocument, index: number): Promise<AttachOutcome> {\n const limit = MAX_DOCUMENT_BYTES;\n const uri = asset.uri?.trim();\n if (!uri) return { status: 'failed', reason: 'unreadable', bytes: 0, limit };\n if (typeof asset.size === 'number' && asset.size > limit) {\n return { status: 'failed', reason: 'oversize', bytes: asset.size, limit };\n }\n\n const fs = loadFileSystem() as {\n readAsStringAsync?: (uri: string, options?: { encoding?: string }) => Promise<string>;\n EncodingType?: { Base64?: string };\n };\n const encoding = fs.EncodingType?.Base64 ?? 'base64';\n if (typeof fs.readAsStringAsync !== 'function') return { status: 'failed', reason: 'unreadable', bytes: 0, limit };\n const base64 = (await fs.readAsStringAsync(uri, { encoding })).trim();\n if (!base64) return { status: 'failed', reason: 'unreadable', bytes: 0, limit };\n const size = typeof asset.size === 'number' && asset.size > 0 ? asset.size : base64Bytes(base64);\n if (size < MIN_BYTES) return { status: 'failed', reason: 'empty', bytes: size, limit };\n if (size > limit) return { status: 'failed', reason: 'oversize', bytes: size, limit };\n const mimeType = asset.mimeType?.trim() || 'application/octet-stream';\n const name = asset.name?.trim() || `file-${Date.now()}-${index}`;\n return {\n status: 'ok',\n attachment: {\n id: `file-${Date.now()}-${index}`,\n name,\n type: 'file',\n mimeType,\n dataUrl: `data:${mimeType};base64,${base64}`,\n url: uri,\n size,\n },\n };\n}\n\nexport function useImageAttachments(): ImageAttachmentsApi {\n const [pending, setPending] = useState<MessageAttachment[]>([]);\n const [busyKind, setBusyKind] = useState<AttachmentBusyKind>(null);\n const [error, setError] = useState<string | null>(null);\n\n const run = useCallback(async (mode: 'library' | 'camera') => {\n setError(null);\n try {\n const picker = loadPicker();\n\n const permission =\n mode === 'camera'\n ? await picker.requestCameraPermissionsAsync()\n : await picker.requestMediaLibraryPermissionsAsync();\n if (!permission.granted) {\n setError(\n mode === 'camera'\n ? 'Camera access is off for Yantra. Turn it on in Settings to attach a photo.'\n : 'Photo access is off for Yantra. Turn it on in Settings to attach an image.',\n );\n return;\n }\n\n // Spin only the control that was tapped, and only after permission\n // so the iOS prompt does not turn camera+gallery+attach into loaders.\n setBusyKind(mode);\n const representation =\n picker.UIImagePickerPreferredAssetRepresentationMode?.Current ?? ('current' as never);\n // Asking the picker for base64 materialises the WHOLE original as a\n // JS string - ~67MB for a 50MB pick, before anything has shrunk it.\n // When we can resize we only need the URI; the manipulator reads the\n // file natively and hands back base64 of the small result instead.\n const canShrink = typeof loadImageManipulator()?.manipulateAsync === 'function';\n const options: import('expo-image-picker').ImagePickerOptions = {\n base64: !canShrink,\n allowsMultipleSelection: mode === 'library',\n mediaTypes: ['images'],\n selectionLimit: MAX_FILES,\n exif: false,\n ...(picker.UIImagePickerPresentationStyle?.OVER_FULL_SCREEN\n ? { presentationStyle: picker.UIImagePickerPresentationStyle.OVER_FULL_SCREEN }\n : {}),\n ...(mode === 'camera' ? { quality: PICKER_QUALITY } : {}),\n ...(mode === 'library' ? { preferredAssetRepresentationMode: representation } : {}),\n };\n\n let result: import('expo-image-picker').ImagePickerResult;\n try {\n result =\n mode === 'camera'\n ? await picker.launchCameraAsync({ ...options, allowsMultipleSelection: false })\n : await picker.launchImageLibraryAsync(options);\n } catch (e) {\n if (mode !== 'library' || !isJpegRepresentationError(e)) throw e;\n result = await picker.launchImageLibraryAsync({ ...options, base64: false });\n }\n\n if (result.canceled) return;\n\n const picked = result.assets ?? [];\n const mapped: MessageAttachment[] = [];\n const failures: AttachFailure[] = [];\n for (let i = 0; i < picked.length; i += 1) {\n const next = await assetToAttachment(\n picked[i] as PickedAsset,\n i,\n mode === 'camera' ? 'screenshot' : 'file',\n );\n if (next.status === 'ok') mapped.push(next.attachment);\n else failures.push(next);\n }\n\n if (mapped.length === 0) {\n setError(failureMessage(failures, 'image'));\n return;\n }\n setPending((prev) => {\n const { accepted, rejected } = withinPendingBudget(prev, mapped);\n if (rejected.length > 0) {\n setError(\n `Only ${mb(MAX_PENDING_BYTES)} of attachments can be staged at once. ${rejected.length} left off.`,\n );\n }\n return [...prev, ...accepted].slice(0, MAX_FILES);\n });\n } catch (e) {\n setError(attachErrorMessage(e));\n } finally {\n setBusyKind(null);\n }\n }, []);\n\n const pickFromLibrary = useCallback(() => run('library'), [run]);\n const captureFromCamera = useCallback(() => run('camera'), [run]);\n const pickDocuments = useCallback(async () => {\n setError(null);\n try {\n const picker = loadDocumentPicker();\n setBusyKind('documents');\n const result = await picker.getDocumentAsync({\n type: DOCUMENT_MIME_TYPES,\n multiple: true,\n copyToCacheDirectory: true,\n });\n const assets = normalizeDocumentAssets(result as Parameters<typeof normalizeDocumentAssets>[0]);\n if (assets.length === 0) return;\n\n const mapped: MessageAttachment[] = [];\n const failures: AttachFailure[] = [];\n for (let i = 0; i < assets.length; i += 1) {\n const next = await documentToAttachment(assets[i], i);\n if (next.status === 'ok') mapped.push(next.attachment);\n else failures.push(next);\n }\n if (mapped.length === 0) {\n setError(failureMessage(failures, 'file'));\n return;\n }\n setPending((prev) => {\n const { accepted, rejected } = withinPendingBudget(prev, mapped);\n if (rejected.length > 0) {\n setError(\n `Only ${mb(MAX_PENDING_BYTES)} of attachments can be staged at once. ${rejected.length} left off.`,\n );\n }\n return [...prev, ...accepted].slice(0, MAX_FILES);\n });\n } catch (e) {\n setError(e instanceof Error ? e.message : 'Could not attach that file.');\n } finally {\n setBusyKind(null);\n }\n }, []);\n const remove = useCallback((id: string) => setPending((prev) => prev.filter((a) => a.id !== id)), []);\n const clear = useCallback(() => setPending([]), []);\n const forSend = useCallback(() => (pending.length > 0 ? pending.map((a) => ({ ...a })) : undefined), [pending]);\n const busy = busyKind !== null;\n\n return useMemo(\n () => ({\n pending,\n busy,\n busyKind,\n error,\n pickFromLibrary,\n captureFromCamera,\n pickDocuments,\n remove,\n clear,\n forSend,\n }),\n [pending, busy, busyKind, error, pickFromLibrary, captureFromCamera, pickDocuments, remove, clear, forSend],\n );\n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AA,KAAA,IAAA,CAAK,MAAO,CAAA,CAAA,CAAA,KAAK,EAAE,EAAO,KAAA,EAAE,CAAC,CAAA,EAAG,EAAE,CAAA;AAChG,EAAM,MAAA,KAAA,GAAQ,YAAY,MAAM,UAAA,CAAW,EAAE,CAAA,EAAG,EAAE,CAAA;AAClD,EAAA,MAAM,OAAU,GAAA,WAAA,CAAY,MAAM,OAAA,CAAQ,SAAS,CAAI,GAAA,OAAA,CAAQ,GAAI,CAAA,CAAA,CAAA,KAAM,mBACpE,CACH,CAAA,CAAA,GAAI,MAAW,EAAA,CAAC,OAAO,CAAC,CAAA;AAC1B,EAAA,MAAM,OAAO,QAAa,KAAA,IAAA;AAC1B,EAAA,OAAO,QAAQ,OAAO;AAAA,IACpB,OAAA;AAAA,IACA,IAAA;AAAA,IACA,QAAA;AAAA,IACA,KAAA;AAAA,IACA,eAAA;AAAA,IACA,iBAAA;AAAA,IACA,aAAA;AAAA,IACA,MAAA;AAAA,IACA,KAAA;AAAA,IACA;AAAA,GACE,CAAA,EAAA,CAAC,OAAS,EAAA,IAAA,EAAM,QAAU,EAAA,KAAA,EAAO,eAAiB,EAAA,iBAAA,EAAmB,aAAe,EAAA,MAAA,EAAQ,KAAO,EAAA,OAAO,CAAC,CAAA;AACjH"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {useState,useRef,useCallback,useEffect,useMemo,useSyncExternalStore}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 {queueGatewayMessage,MAX_QUEUED_MESSAGES,dropQueuedGatewayMessage,queuedGatewayMessages,subscribeQueuedGatewayMessages,restoreQueuedGatewayMessages,clearQueuedGatewayMessages}from'../services/queuedGatewayMessages.js';import {isImageAttachment}from'../features/attachments/isImageAttachment.js';import {buildGatewayMedia,buildGatewayMediaPreferUrls}from'../features/attachments/buildGatewayMedia.js';import {preserveAttachmentPreviews}from'../features/attachments/preserveAttachmentPreviews.js';import {resolveAssistantReply}from'../features/chat/emptyChatResponse.js';import {appendOrReplaceAssistant,mergeOptimisticGatewayMessages,collapseConsecutiveAssistants}from'../state/chatThreadMerge.js';var __defProp = Object.defineProperty;
|
|
1
|
+
import {useState,useRef,useCallback,useEffect,useMemo,useSyncExternalStore}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 {queueGatewayMessage,MAX_QUEUED_MESSAGES,dropQueuedGatewayMessage,queuedGatewayMessages,subscribeQueuedGatewayMessages,restoreQueuedGatewayMessages,clearQueuedGatewayMessages}from'../services/queuedGatewayMessages.js';import {isImageAttachment}from'../features/attachments/isImageAttachment.js';import {buildGatewayMedia,buildGatewayMediaPreferUrls}from'../features/attachments/buildGatewayMedia.js';import {preserveAttachmentPreviews}from'../features/attachments/preserveAttachmentPreviews.js';import {releasePreviewBytes}from'../features/attachments/releasePreviewBytes.js';import {resolveAssistantReply}from'../features/chat/emptyChatResponse.js';import {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;
|
|
@@ -410,7 +410,10 @@ function useChatStream(sessionId, routing = {
|
|
|
410
410
|
markChannelHistoryRunning(effectiveSessionId);
|
|
411
411
|
}
|
|
412
412
|
if (!alreadyVisible) {
|
|
413
|
-
|
|
413
|
+
const retained = __spreadProps(__spreadValues({}, userMessage), {
|
|
414
|
+
attachments: releasePreviewBytes(userMessage.attachments)
|
|
415
|
+
});
|
|
416
|
+
setMessages((prev) => [...prev, retained]);
|
|
414
417
|
authRetryUsedRef.current = false;
|
|
415
418
|
}
|
|
416
419
|
setResponse("");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useChatStream.js","sources":["../../src/hooks/useChatStream.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport {\n useCreateAccountChatFileDownloadLinksMutation,\n useCreateAccountChatFileUploadLinksMutation,\n} from 'common/graphql';\nimport {\n clearChannelHistoryRunning,\n markChannelHistoryRunning,\n patchChannelHistoryPreview,\n useChatMutations,\n useChatMessages,\n} from './useChatApi';\nimport { isNoActiveSessionError, useCdecliChannel } from './useCdecliChannel';\nimport { usePrerequisiteIds } from './usePrerequisiteIds';\nimport { isAgentJwtRejected, shouldInlineGatewayMediaForHostedAgent } from './systemTokenJwt';\nimport { config } from '../config';\nimport {\n MAX_QUEUED_MESSAGES,\n clearQueuedGatewayMessages,\n dropQueuedGatewayMessage,\n queueGatewayMessage,\n queuedGatewayMessages,\n restoreQueuedGatewayMessages,\n subscribeQueuedGatewayMessages,\n} from '../services/queuedGatewayMessages';\nimport { isImageAttachment } from '../features/attachments/isImageAttachment';\nimport { buildGatewayMedia, buildGatewayMediaPreferUrls } from '../features/attachments/buildGatewayMedia';\nimport { preserveAttachmentPreviews } from '../features/attachments/preserveAttachmentPreviews';\nimport { resolveAssistantReply } from '../features/chat/emptyChatResponse';\nimport {\n appendOrReplaceAssistant,\n collapseConsecutiveAssistants,\n mergeOptimisticGatewayMessages,\n} from '../state/chatThreadMerge';\n\n/** Agent returned an error while the cdecli-serve channel stayed connected (e.g. bad LLM API key). */\nfunction isCdecliAgentFailureOutput(text: string): boolean {\n const t = text.trim();\n if (!t) return false;\n return (\n /⚠\\s*Error:/.test(t) ||\n /LLM stream error/i.test(t) ||\n /Incorrect API key/i.test(t) ||\n /invalid_api_key/i.test(t) ||\n /authentication_error/i.test(t) ||\n isAgentJwtRejected(t)\n );\n}\n\nexport interface MessageAttachment {\n id: string;\n name: string;\n type: 'file' | 'screenshot';\n dataUrl?: string;\n mimeType?: string;\n size?: number;\n url?: string;\n}\n\nexport interface ChatMessage {\n role: 'user' | 'assistant';\n content: string;\n attachments?: MessageAttachment[];\n metadata?: {\n tokenUsage?: { inputTokens: number; outputTokens: number; totalTokens: number };\n model?: string;\n };\n}\n\n/** The queued row renders this turn now, so the optimistic bubble must not stay behind it. */\nfunction withoutTrailingUserMessage(prev: ChatMessage[], text: string): ChatMessage[] {\n const last = prev[prev.length - 1];\n return last?.role === 'user' && last.content === text ? prev.slice(0, -1) : prev;\n}\n\n/** What became of a send: delivered to the gateway, parked in the outbox, or refused outright. */\nexport type SendOutcome = 'sent' | 'queued' | 'failed';\n\nfunction formatBackendThread(\n backendMessages: Array<{\n role: string;\n content?: string;\n // The generated `ChatMessageUI` types `type` as a plain string; it is narrowed\n // to the UI union in the map below, so take it wide rather than cast at the call.\n attachments?: Array<{ id: string; name: string; type: string; mimeType?: string; size?: number; url?: string }>;\n tokenCount?: number;\n model?: string;\n }>,\n): ChatMessage[] {\n return collapseConsecutiveAssistants(\n backendMessages.map((msg) => ({\n role: msg.role as 'user' | 'assistant',\n content: msg.content ?? '',\n attachments: msg.attachments?.map((a) => ({\n id: a.id,\n name: a.name,\n type: a.type === 'screenshot' ? 'screenshot' : 'file',\n mimeType: a.mimeType,\n size: a.size,\n url: a.url,\n })),\n metadata: msg.tokenCount\n ? {\n tokenUsage: {\n inputTokens: 0,\n outputTokens: msg.tokenCount,\n totalTokens: msg.tokenCount,\n },\n model: msg.model,\n }\n : undefined,\n })),\n );\n}\n\n/** Mobile chat routes exclusively through CDeCLI (messenger-gateway). */\nexport interface UseChatStreamRouting {\n channelConnected: boolean;\n accountId: string;\n /** When `'backend'`, the gateway persists posts — skip client `saveMessages`. */\n persistenceMode?: 'backend' | 'frontend';\n /** Remint the system JWT and reconnect after cdecli-agent 401s the session. */\n recoverAgentAuth?: () => Promise<boolean>;\n}\n\nexport function useChatStream(\n sessionId: string | null,\n routing: UseChatStreamRouting = {\n channelConnected: false,\n accountId: 'default',\n persistenceMode: 'backend',\n },\n) {\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [response, setResponse] = useState('');\n /** Brain assist — never the published agent stream. Shown as a Quick answer strip. */\n const [quickReply, setQuickReply] = useState('');\n const [isLoading, setIsLoading] = useState(false);\n const [isStreaming, setIsStreaming] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const isSendingRef = useRef(false);\n /** Follow-ups typed before cdecli has an active session. Flushed after the first token. */\n const pendingSteersRef = useRef<string[]>([]);\n /** True once this turn has produced at least one stream chunk (steer is valid). */\n const sessionLiveRef = useRef(false);\n const flushPendingSteersRef = useRef<() => Promise<void>>(async () => {});\n const sendMessageRef = useRef<\n (\n content: string,\n attachments?: MessageAttachment[],\n sessionIdOverride?: string | null,\n alreadyVisible?: boolean,\n queuedId?: string,\n ) => Promise<SendOutcome>\n >(async () => 'failed');\n\n /** Ensures GraphQL stream subscriptions use the id from createChannel+send before the next parent render. */\n const [cdecliStreamOverrideId, setCdecliStreamOverrideId] = useState<string | undefined>(undefined);\n const userMsgForSaveRef = useRef<ChatMessage | null>(null);\n const saveSessionIdRef = useRef<string | null>(null);\n const sessionIdRef = useRef<string | null>(sessionId);\n sessionIdRef.current = sessionId || cdecliStreamOverrideId || null;\n /** Blocks duplicate cdecli `onComplete` from appending assistant twice / saving twice per send. */\n const cdecliRoundHandledRef = useRef(false);\n /** One remint+resend per turn when cdecli-agent 401s the JWT. */\n const authRetryUsedRef = useRef(false);\n const recoveringAuthRef = useRef(false);\n const routingRef = useRef(routing);\n routingRef.current = routing;\n\n const tryRecoverAndResendRef = useRef<(reason: string) => Promise<boolean>>(async () => false);\n\n /** Coalesce token deltas so Fabric is not committing a native tree every chunk. */\n const pendingStreamRef = useRef('');\n const streamFlushTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const clearPendingStream = useCallback(() => {\n if (streamFlushTimerRef.current != null) {\n clearTimeout(streamFlushTimerRef.current);\n streamFlushTimerRef.current = null;\n }\n pendingStreamRef.current = '';\n }, []);\n\n const flushPendingStream = useCallback(() => {\n streamFlushTimerRef.current = null;\n const pending = pendingStreamRef.current;\n if (!pending) return;\n pendingStreamRef.current = '';\n setResponse((r) => {\n const next = r + pending;\n const sid = sessionIdRef.current;\n if (sid) markChannelHistoryRunning(sid, next);\n return next;\n });\n }, []);\n\n useEffect(() => () => clearPendingStream(), [clearPendingStream]);\n\n const { saveMessages, patchChannelTitle } = useChatMutations();\n const titlePatchedChannelsRef = useRef(new Set<string>());\n const { accountUserId } = usePrerequisiteIds();\n const [createAccountChatFileUploadLinksMutation] = useCreateAccountChatFileUploadLinksMutation();\n const [createAccountChatFileDownloadLinksMutation] = useCreateAccountChatFileDownloadLinksMutation();\n const {\n messages: backendMessages,\n loading: backendMessagesLoading,\n messagesLoaded: backendMessagesLoaded,\n } = useChatMessages(sessionId);\n const lastHydratedSessionIdRef = useRef<string | null>(null);\n /** Trash-clear: do not re-hydrate gateway history until the next send. */\n const ignoreHydrationRef = useRef(false);\n\n const streamChannelId = sessionId || cdecliStreamOverrideId;\n\n const finalizeCdecliRound = useCallback(\n (assistantContent?: string) => {\n const previewSid = saveSessionIdRef.current || sessionIdRef.current;\n clearPendingStream();\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n sessionLiveRef.current = false;\n setResponse('');\n setQuickReply('');\n setIsLoading(false);\n setIsStreaming(false);\n isSendingRef.current = false;\n if (previewSid) clearChannelHistoryRunning(previewSid);\n if (assistantContent !== undefined) {\n setMessages((prev) =>\n appendOrReplaceAssistant(prev, { role: 'assistant' as const, content: assistantContent }),\n );\n if (previewSid) patchChannelHistoryPreview(previewSid, assistantContent);\n }\n },\n [clearPendingStream],\n );\n\n const cdecliCallbacks = useMemo(\n () => ({\n onChunk: (text: string) => {\n if (!isSendingRef.current) {\n isSendingRef.current = true;\n cdecliRoundHandledRef.current = false;\n saveSessionIdRef.current = sessionIdRef.current;\n setIsLoading(true);\n setIsStreaming(true);\n setError(null);\n const sid = sessionIdRef.current;\n if (sid) markChannelHistoryRunning(sid, text);\n }\n pendingStreamRef.current += text;\n if (!sessionLiveRef.current) {\n sessionLiveRef.current = true;\n void flushPendingSteersRef.current();\n }\n if (streamFlushTimerRef.current == null) {\n streamFlushTimerRef.current = setTimeout(flushPendingStream, 50);\n }\n },\n // The brain's provisional answer is the WHOLE reply-so-far, not a chunk:\n // it is set outright, and set to '' when the real stream supersedes it.\n // It deliberately does not mark the session live - steers wait for the\n // agent, which is the only side that can act on them.\n onQuickReply: (text: string) => {\n setQuickReply(text);\n },\n onStreamRestart: () => {\n clearPendingStream();\n pendingStreamRef.current = '';\n setResponse('');\n },\n onComplete: (text: string) => {\n clearPendingStream();\n if (cdecliRoundHandledRef.current) {\n return;\n }\n\n if (isCdecliAgentFailureOutput(text)) {\n void (async () => {\n if (await tryRecoverAndResendRef.current(text)) return;\n if (cdecliRoundHandledRef.current) return;\n cdecliRoundHandledRef.current = true;\n pendingSteersRef.current = [];\n setError(\n isAgentJwtRejected(text)\n ? text\n : 'CDeCLI agent error. Check gateway status and server-side LLM configuration.',\n );\n finalizeCdecliRound(isAgentJwtRejected(text) ? undefined : text);\n })();\n return;\n }\n\n cdecliRoundHandledRef.current = true;\n authRetryUsedRef.current = false;\n\n const reply = resolveAssistantReply(text);\n const sid = saveSessionIdRef.current;\n const um = userMsgForSaveRef.current;\n const leftover = pendingSteersRef.current;\n pendingSteersRef.current = [];\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n sessionLiveRef.current = false;\n\n setMessages((prev) => appendOrReplaceAssistant(prev, { role: 'assistant' as const, content: reply }));\n const previewSid = sid || sessionIdRef.current;\n if (previewSid) {\n clearChannelHistoryRunning(previewSid);\n patchChannelHistoryPreview(previewSid, reply);\n }\n setResponse('');\n setQuickReply('');\n setIsLoading(false);\n setIsStreaming(false);\n isSendingRef.current = false;\n\n const rt = routingRef.current;\n const persistClientSide = rt.persistenceMode !== 'backend';\n\n if (sid && um && persistClientSide) {\n saveMessages({\n sessionId: sid,\n ...(accountUserId ? { createdBy: accountUserId } : {}),\n userMessage: {\n content: um.content,\n attachments: um.attachments?.map((a) => ({\n id: a.id,\n name: a.name,\n type: a.type,\n mimeType: a.mimeType,\n size: a.size,\n url: a.url,\n })),\n },\n assistantMessage: {\n content: reply,\n tokenCount: undefined,\n model: 'cdecli-serve',\n },\n }).catch((e) => {\n console.error('[useChatStream] saveMessages (cdecli):', e);\n });\n }\n\n if (leftover.length > 0) {\n const [first, ...rest] = leftover;\n pendingSteersRef.current = rest;\n queueMicrotask(() => {\n void sendMessageRef.current(first, undefined, sid, true);\n });\n }\n },\n onError: (err: string) => {\n if (cdecliRoundHandledRef.current) return;\n void (async () => {\n if (await tryRecoverAndResendRef.current(err)) return;\n if (cdecliRoundHandledRef.current) return;\n cdecliRoundHandledRef.current = true;\n pendingSteersRef.current = [];\n setError(err || 'CDeCLI stream error.');\n finalizeCdecliRound(resolveAssistantReply(''));\n })();\n },\n }),\n [saveMessages, accountUserId, finalizeCdecliRound, flushPendingStream, clearPendingStream],\n );\n\n const {\n sendMessage: sendCdecliMessage,\n steer: steerCdecliMessage,\n cancel: cancelCdecliTurn,\n } = useCdecliChannel(routing.channelConnected, routing.accountId, streamChannelId, cdecliCallbacks);\n\n const flushPendingSteers = useCallback(async () => {\n if (!sessionLiveRef.current || !isSendingRef.current) return;\n const sid = saveSessionIdRef.current;\n if (!sid) return;\n\n while (pendingSteersRef.current.length > 0 && sessionLiveRef.current && isSendingRef.current) {\n const next = pendingSteersRef.current[0];\n const result = await steerCdecliMessage(next, sid);\n if (result.ok) {\n pendingSteersRef.current.shift();\n continue;\n }\n if (isNoActiveSessionError(result.error)) {\n return;\n }\n pendingSteersRef.current.shift();\n setError(result.error || 'Could not send follow-up. Try again.');\n return;\n }\n }, [steerCdecliMessage]);\n\n flushPendingSteersRef.current = flushPendingSteers;\n\n useEffect(() => {\n if (sessionId && cdecliStreamOverrideId && sessionId === cdecliStreamOverrideId) {\n setCdecliStreamOverrideId(undefined);\n }\n }, [sessionId, cdecliStreamOverrideId]);\n\n useEffect(() => {\n const prevSid = lastHydratedSessionIdRef.current;\n if (prevSid && sessionId && prevSid !== sessionId && isSendingRef.current) {\n // Switching threads: drop local send flags so this view can hydrate.\n // The previous channel's agent keeps running server-side; history still\n // shows it as running until that turn completes or we reopen it.\n clearPendingStream();\n pendingSteersRef.current = [];\n isSendingRef.current = false;\n sessionLiveRef.current = false;\n cdecliRoundHandledRef.current = false;\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n setIsLoading(false);\n setIsStreaming(false);\n setResponse('');\n setQuickReply('');\n }\n\n if (!sessionId) {\n setMessages([]);\n setResponse('');\n setQuickReply('');\n lastHydratedSessionIdRef.current = null;\n return;\n }\n\n const stampHistoryPreview = (msgs: ChatMessage[]) => {\n const last = msgs[msgs.length - 1];\n const lastAssistant = [...msgs].reverse().find((msg) => msg.role === 'assistant' && msg.content.trim());\n if (lastAssistant && !isSendingRef.current) {\n patchChannelHistoryPreview(sessionId, lastAssistant.content);\n }\n // Finished thread (last post is assistant) — drop the history \"Running\" badge.\n // A live turn ends with a user post until the assistant lands.\n if (!isSendingRef.current && last?.role === 'assistant') {\n clearChannelHistoryRunning(sessionId);\n }\n };\n\n if (ignoreHydrationRef.current) {\n return;\n }\n\n const keepStream = isSendingRef.current;\n const sessionChanged = lastHydratedSessionIdRef.current !== sessionId;\n if (sessionChanged) {\n lastHydratedSessionIdRef.current = sessionId;\n // Do not merge the previous channel's in-memory thread into this one.\n if (!backendMessagesLoaded) {\n if (!keepStream) {\n setMessages([]);\n setResponse('');\n setQuickReply('');\n }\n return;\n }\n const formatted = formatBackendThread(backendMessages ?? []);\n stampHistoryPreview(formatted);\n setMessages((prev) => (keepStream ? mergeOptimisticGatewayMessages(prev, formatted) : formatted));\n if (!keepStream) {\n setResponse('');\n setQuickReply('');\n }\n return;\n }\n\n if (backendMessagesLoaded) {\n const formatted = formatBackendThread(backendMessages ?? []);\n stampHistoryPreview(formatted);\n // Positional merge first so assistant replies the gateway never persisted\n // (cdecli skill turns emit no chatMessageAdded) survive this snapshot instead\n // of being dropped, then preserve in-memory attachment previews on the result.\n setMessages((prev) => preserveAttachmentPreviews(prev, mergeOptimisticGatewayMessages(prev, formatted)));\n if (!keepStream) {\n setResponse('');\n setQuickReply('');\n }\n }\n }, [sessionId, backendMessages, backendMessagesLoaded, clearPendingStream]);\n\n const sendMessage = useCallback(\n async (\n content: string,\n attachments?: MessageAttachment[],\n sessionIdOverride?: string | null,\n alreadyVisible = false,\n /** Set when this send is the release of an outbox entry; it owns that entry's fate. */\n queuedId: string | undefined = undefined,\n ): Promise<SendOutcome> => {\n if (!content.trim() && !attachments?.length) return 'failed';\n\n const effectiveSessionId = sessionIdOverride !== undefined ? sessionIdOverride : sessionId;\n const rt = routingRef.current;\n const trimmed = content.trim();\n const sendText =\n trimmed ||\n (attachments?.length\n ? `Attached: ${attachments\n .map((a) => a.name)\n .filter(Boolean)\n .join(', ')}`\n : '');\n\n const userMessage: ChatMessage = {\n role: 'user',\n content: sendText,\n attachments,\n };\n\n /**\n * The gateway is down. The turn is remembered, not erased: it stays in the\n * thread as a queued bubble and the outbox releases it in order the moment\n * the channel reports connected. Losing what the user typed here is the\n * whole reason this lane exists.\n */\n if (!rt.channelConnected) {\n if (!effectiveSessionId) {\n setError('Missing chat session id.');\n return 'failed';\n }\n // A release that raced the connection dropping stays where it is.\n if (queuedId) return 'queued';\n const result = queueGatewayMessage({\n channelId: effectiveSessionId,\n accountId: rt.accountId,\n text: sendText,\n attachments,\n });\n if (!result.ok) {\n setError(\n result.reason === 'full'\n ? `${MAX_QUEUED_MESSAGES} messages are already waiting for the gateway. They send as soon as it connects.`\n : 'Nothing to send.',\n );\n return 'failed';\n }\n if (alreadyVisible) setMessages((prev) => withoutTrailingUserMessage(prev, sendText));\n setError(null);\n return 'queued';\n }\n\n /**\n * A turn is already in flight. Keep the follow-up visible and queue it.\n * cdecli rejects steer until the agent session exists (\"no active session\"),\n * which is after the first token. Flush then. Never error/LogBox for that race.\n */\n if (isSendingRef.current) {\n if (!effectiveSessionId) {\n setError('Missing chat session id.');\n return 'failed';\n }\n if (!alreadyVisible) setMessages((prev) => [...prev, userMessage]);\n setError(null);\n pendingSteersRef.current = [...pendingSteersRef.current, sendText];\n if (queuedId) dropQueuedGatewayMessage(queuedId);\n void flushPendingSteers();\n return 'sent';\n }\n\n isSendingRef.current = true;\n sessionLiveRef.current = false;\n ignoreHydrationRef.current = false;\n if (effectiveSessionId && sendText) {\n titlePatchedChannelsRef.current.add(effectiveSessionId);\n patchChannelTitle(effectiveSessionId, sendText, true);\n markChannelHistoryRunning(effectiveSessionId);\n }\n if (!alreadyVisible) {\n setMessages((prev) => [...prev, userMessage]);\n authRetryUsedRef.current = false;\n }\n setResponse('');\n setQuickReply('');\n setIsLoading(true);\n setIsStreaming(true);\n setError(null);\n userMsgForSaveRef.current = userMessage;\n saveSessionIdRef.current = effectiveSessionId ?? null;\n cdecliRoundHandledRef.current = false;\n\n if (!effectiveSessionId) {\n setError('Missing chat session id.');\n if (!alreadyVisible) setMessages((p) => p.slice(0, -1));\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n userMsgForSaveRef.current = null;\n saveSessionIdRef.current = null;\n return 'failed';\n }\n\n if (sessionIdOverride) {\n setCdecliStreamOverrideId(sessionIdOverride);\n await new Promise<void>((resolve) => {\n setTimeout(resolve, 0);\n });\n }\n\n const inlineForHostedAgent = shouldInlineGatewayMediaForHostedAgent(\n config.GRAPHQL_URL,\n config.CDECLI_AGENT_ENDPOINT,\n );\n // Vision turns must carry inline bytes. URL-only media is what made\n // \"what is this\" + a photo look like a text-only question.\n const inlineImages = (attachments ?? []).some(isImageAttachment) || inlineForHostedAgent;\n let media = inlineImages\n ? buildGatewayMedia(attachments, { includeData: true })\n : await buildGatewayMediaPreferUrls(\n attachments,\n async (filenames) => {\n const result = await createAccountChatFileUploadLinksMutation({\n variables: { filenames },\n });\n return result.data?.createAccountChatFileUploadLinks || [];\n },\n async (urls) => {\n const result = await createAccountChatFileDownloadLinksMutation({\n variables: { urls },\n });\n return result.data?.createAccountChatFileDownloadLinks || [];\n },\n );\n if ((attachments?.length ?? 0) > 0 && media.length === 0) {\n media = buildGatewayMedia(attachments, { includeData: true });\n }\n const ok = await sendCdecliMessage(sendText, effectiveSessionId, media);\n if (!ok && !cdecliRoundHandledRef.current && !recoveringAuthRef.current) {\n cdecliRoundHandledRef.current = true;\n // The send never reached the agent. Park it rather than drop it - a\n // release keeps its place at the head of its own queue.\n const parked = queuedId\n ? { ok: true as const }\n : queueGatewayMessage({\n channelId: effectiveSessionId,\n accountId: rt.accountId,\n text: sendText,\n attachments,\n });\n setError(\n parked.ok\n ? 'Gateway unreachable - message queued. It sends as soon as the connection is back.'\n : 'Failed to send message via CDeCLI. Check gateway connection.',\n );\n // Queued: the queued row renders the turn, so the optimistic bubble goes.\n // Not queued: only drop a bubble this call put there.\n setMessages((p) => {\n if (parked.ok) return withoutTrailingUserMessage(p, sendText);\n return alreadyVisible ? p : p.slice(0, -1);\n });\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n userMsgForSaveRef.current = null;\n saveSessionIdRef.current = null;\n clearChannelHistoryRunning(effectiveSessionId);\n return parked.ok ? 'queued' : 'failed';\n }\n if (ok && queuedId) dropQueuedGatewayMessage(queuedId);\n return ok ? 'sent' : 'failed';\n },\n [\n sessionId,\n sendCdecliMessage,\n patchChannelTitle,\n flushPendingSteers,\n createAccountChatFileUploadLinksMutation,\n createAccountChatFileDownloadLinksMutation,\n ],\n );\n\n sendMessageRef.current = sendMessage;\n\n /* ---------------------------------------------------------------------- *\n * Outbox: turns typed while the gateway was down.\n * ---------------------------------------------------------------------- */\n\n const queuedChannelId = sessionId || cdecliStreamOverrideId || null;\n const queuedSnapshot = useCallback(\n () => queuedGatewayMessages(queuedChannelId, routing.accountId),\n [queuedChannelId, routing.accountId],\n );\n const queuedMessages = useSyncExternalStore(subscribeQueuedGatewayMessages, queuedSnapshot, queuedSnapshot);\n\n useEffect(() => {\n void restoreQueuedGatewayMessages();\n }, []);\n\n /** One release at a time; a send that fails leaves its entry at the head for the next reconnect. */\n const flushingRef = useRef(false);\n const flushQueuedMessages = useCallback(async () => {\n if (flushingRef.current) return;\n flushingRef.current = true;\n try {\n // Bounded: the outbox can never hand out more than its own depth.\n for (let i = 0; i <= MAX_QUEUED_MESSAGES; i += 1) {\n const rt = routingRef.current;\n const sid = sessionIdRef.current;\n if (!rt.channelConnected || !sid) return;\n const next = queuedGatewayMessages(sid, rt.accountId)[0];\n if (!next) return;\n const outcome = await sendMessageRef.current(\n next.text,\n next.attachments,\n next.channelId,\n false,\n next.id,\n );\n if (outcome !== 'sent') return;\n }\n } finally {\n flushingRef.current = false;\n }\n }, []);\n\n /**\n * Release on the disconnected→connected edge, and when a channel with a queue\n * is opened on an already-live gateway. Deliberately not keyed on queue depth:\n * a send that fails puts its turn back, and depth would spin that into a loop.\n */\n const wasConnectedRef = useRef(routing.channelConnected);\n useEffect(() => {\n const connected = routing.channelConnected;\n const reconnected = connected && !wasConnectedRef.current;\n wasConnectedRef.current = connected;\n if (!connected || !queuedChannelId) return;\n if (!reconnected && queuedGatewayMessages(queuedChannelId, routing.accountId).length === 0) return;\n void flushQueuedMessages();\n }, [routing.channelConnected, routing.accountId, queuedChannelId, flushQueuedMessages]);\n\n const discardQueuedMessages = useCallback(() => {\n if (!queuedChannelId) return;\n clearQueuedGatewayMessages(queuedChannelId);\n setError(null);\n }, [queuedChannelId]);\n\n tryRecoverAndResendRef.current = async (reason: string) => {\n if (authRetryUsedRef.current || cdecliRoundHandledRef.current) return false;\n if (!isAgentJwtRejected(reason)) return false;\n const recover = routingRef.current.recoverAgentAuth;\n if (!recover) return false;\n authRetryUsedRef.current = true;\n recoveringAuthRef.current = true;\n try {\n setError('Refreshing CDeCLI credentials…');\n const recovered = await recover();\n if (!recovered) return false;\n const um = userMsgForSaveRef.current;\n const sid = saveSessionIdRef.current;\n cdecliRoundHandledRef.current = false;\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n setError(null);\n if (um && sid) {\n queueMicrotask(() => {\n void sendMessageRef.current(um.content, um.attachments, sid, true);\n });\n }\n return true;\n } catch (err) {\n console.error('[useChatStream] recoverAgentAuth failed:', err);\n return false;\n } finally {\n recoveringAuthRef.current = false;\n }\n };\n\n const cancel = useCallback(() => {\n clearPendingStream();\n pendingSteersRef.current = [];\n sessionLiveRef.current = false;\n const sid = saveSessionIdRef.current ?? sessionId;\n void cancelCdecliTurn(sid ?? 'messenger');\n if (!cdecliRoundHandledRef.current) {\n cdecliRoundHandledRef.current = true;\n finalizeCdecliRound(resolveAssistantReply(''));\n }\n }, [cancelCdecliTurn, finalizeCdecliRound, sessionId, clearPendingStream]);\n\n const clearMessages = useCallback(() => {\n clearPendingStream();\n pendingSteersRef.current = [];\n const hadActiveTurn = isSendingRef.current || sessionLiveRef.current;\n const sid = saveSessionIdRef.current ?? sessionId;\n sessionLiveRef.current = false;\n isSendingRef.current = false;\n cdecliRoundHandledRef.current = true;\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n // Only hit /cancel when a turn was live — otherwise cdecli logs\n // \"Cannot cancel: no active session\" (Research greet + trash).\n if (hadActiveTurn) {\n void cancelCdecliTurn(sid ?? 'messenger');\n }\n ignoreHydrationRef.current = true;\n // Emptying the thread empties its outbox too: a queued turn released after\n // the user cleared the chat would answer a conversation they threw away.\n if (sid) clearQueuedGatewayMessages(sid);\n setMessages([]);\n setResponse('');\n setQuickReply('');\n setError(null);\n setIsLoading(false);\n setIsStreaming(false);\n if (sid) clearChannelHistoryRunning(sid);\n }, [cancelCdecliTurn, clearPendingStream, sessionId]);\n\n const messagesLoading = !!sessionId && backendMessagesLoading && !backendMessagesLoaded;\n\n return {\n messages,\n response,\n quickReply,\n error,\n isLoading,\n isStreaming,\n messagesLoading,\n hasMessages: messages.length > 0 || !!response || !!quickReply || queuedMessages.length > 0,\n /** Turns waiting on the gateway, oldest first. Rendered as queued bubbles. */\n queuedMessages,\n /** Send the queue now (the notice's retry), independent of the reconnect edge. */\n flushQueuedMessages,\n discardQueuedMessages,\n sendMessage,\n cancel,\n clearMessages,\n };\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;AAeA,SAAS,2BAA2B,IAAuB,EAAA;AACzD,EAAM,MAAA,CAAA,GAAI,KAAK,IAAK,EAAA;AACpB,EAAI,IAAA,CAAC,GAAU,OAAA,KAAA;AACf,EAAO,OAAA,YAAA,CAAa,KAAK,CAAC,CAAA,IAAK,oBAAoB,IAAK,CAAA,CAAC,KAAK,oBAAqB,CAAA,IAAA,CAAK,CAAC,CAAK,IAAA,kBAAA,CAAmB,KAAK,CAAC,CAAA,IAAK,wBAAwB,IAAK,CAAA,CAAC,CAAK,IAAA,kBAAA,CAAmB,CAAC,CAAA;AACrL;AAyBA,SAAS,0BAAA,CAA2B,MAAqB,IAA6B,EAAA;AACpF,EAAA,MAAM,IAAO,GAAA,IAAA,CAAK,IAAK,CAAA,MAAA,GAAS,CAAC,CAAA;AACjC,EAAO,OAAA,CAAA,IAAA,IAAA,IAAA,GAAA,MAAA,GAAA,IAAA,CAAM,IAAS,MAAA,MAAA,IAAU,IAAK,CAAA,OAAA,KAAY,OAAO,IAAK,CAAA,KAAA,CAAM,CAAG,EAAA,EAAE,CAAI,GAAA,IAAA;AAC9E;AAIA,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A,iBAAA,CAAkB,OAAU,GAAA,IAAA;AAG5B,IAAA,IAAI,aAAe,EAAA;AACjB,MAAK,KAAA,gBAAA,CAAiB,oBAAO,WAAW,CAAA;AAAA;AAE1C,IAAA,kBAAA,CAAmB,OAAU,GAAA,IAAA;AAG7B,IAAI,IAAA,GAAA,6BAAgC,GAAG,CAAA;AACvC,IAAA,WAAA,CAAY,EAAE,CAAA;AACd,IAAA,WAAA,CAAY,EAAE,CAAA;AACd,IAAA,aAAA,CAAc,EAAE,CAAA;AAChB,IAAA,QAAA,CAAS,IAAI,CAAA;AACb,IAAA,YAAA,CAAa,KAAK,CAAA;AAClB,IAAA,cAAA,CAAe,KAAK,CAAA;AACpB,IAAI,IAAA,GAAA,6BAAgC,GAAG,CAAA;AAAA,GACtC,EAAA,CAAC,gBAAkB,EAAA,kBAAA,EAAoB,SAAS,CAAC,CAAA;AACpD,EAAA,MAAM,eAAkB,GAAA,CAAC,CAAC,SAAA,IAAa,0BAA0B,CAAC,qBAAA;AAClE,EAAO,OAAA;AAAA,IACL,QAAA;AAAA,IACA,QAAA;AAAA,IACA,UAAA;AAAA,IACA,KAAA;AAAA,IACA,SAAA;AAAA,IACA,WAAA;AAAA,IACA,eAAA;AAAA,IACA,WAAA,EAAa,QAAS,CAAA,MAAA,GAAS,CAAK,IAAA,CAAC,CAAC,QAAA,IAAY,CAAC,CAAC,UAAc,IAAA,cAAA,CAAe,MAAS,GAAA,CAAA;AAAA;AAAA,IAE1F,cAAA;AAAA;AAAA,IAEA,mBAAA;AAAA,IACA,qBAAA;AAAA,IACA,WAAA;AAAA,IACA,MAAA;AAAA,IACA;AAAA,GACF;AACF"}
|
|
1
|
+
{"version":3,"file":"useChatStream.js","sources":["../../src/hooks/useChatStream.ts"],"sourcesContent":["import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react';\nimport {\n useCreateAccountChatFileDownloadLinksMutation,\n useCreateAccountChatFileUploadLinksMutation,\n} from 'common/graphql';\nimport {\n clearChannelHistoryRunning,\n markChannelHistoryRunning,\n patchChannelHistoryPreview,\n useChatMutations,\n useChatMessages,\n} from './useChatApi';\nimport { isNoActiveSessionError, useCdecliChannel } from './useCdecliChannel';\nimport { usePrerequisiteIds } from './usePrerequisiteIds';\nimport { isAgentJwtRejected, shouldInlineGatewayMediaForHostedAgent } from './systemTokenJwt';\nimport { config } from '../config';\nimport {\n MAX_QUEUED_MESSAGES,\n clearQueuedGatewayMessages,\n dropQueuedGatewayMessage,\n queueGatewayMessage,\n queuedGatewayMessages,\n restoreQueuedGatewayMessages,\n subscribeQueuedGatewayMessages,\n} from '../services/queuedGatewayMessages';\nimport { isImageAttachment } from '../features/attachments/isImageAttachment';\nimport { buildGatewayMedia, buildGatewayMediaPreferUrls } from '../features/attachments/buildGatewayMedia';\nimport { preserveAttachmentPreviews } from '../features/attachments/preserveAttachmentPreviews';\nimport { releasePreviewBytes } from '../features/attachments/releasePreviewBytes';\nimport { resolveAssistantReply } from '../features/chat/emptyChatResponse';\nimport {\n appendOrReplaceAssistant,\n collapseConsecutiveAssistants,\n mergeOptimisticGatewayMessages,\n} from '../state/chatThreadMerge';\n\n/** Agent returned an error while the cdecli-serve channel stayed connected (e.g. bad LLM API key). */\nfunction isCdecliAgentFailureOutput(text: string): boolean {\n const t = text.trim();\n if (!t) return false;\n return (\n /⚠\\s*Error:/.test(t) ||\n /LLM stream error/i.test(t) ||\n /Incorrect API key/i.test(t) ||\n /invalid_api_key/i.test(t) ||\n /authentication_error/i.test(t) ||\n isAgentJwtRejected(t)\n );\n}\n\nexport interface MessageAttachment {\n id: string;\n name: string;\n type: 'file' | 'screenshot';\n dataUrl?: string;\n mimeType?: string;\n size?: number;\n url?: string;\n}\n\nexport interface ChatMessage {\n role: 'user' | 'assistant';\n content: string;\n attachments?: MessageAttachment[];\n metadata?: {\n tokenUsage?: { inputTokens: number; outputTokens: number; totalTokens: number };\n model?: string;\n };\n}\n\n/** The queued row renders this turn now, so the optimistic bubble must not stay behind it. */\nfunction withoutTrailingUserMessage(prev: ChatMessage[], text: string): ChatMessage[] {\n const last = prev[prev.length - 1];\n return last?.role === 'user' && last.content === text ? prev.slice(0, -1) : prev;\n}\n\n/** What became of a send: delivered to the gateway, parked in the outbox, or refused outright. */\nexport type SendOutcome = 'sent' | 'queued' | 'failed';\n\nfunction formatBackendThread(\n backendMessages: Array<{\n role: string;\n content?: string;\n // The generated `ChatMessageUI` types `type` as a plain string; it is narrowed\n // to the UI union in the map below, so take it wide rather than cast at the call.\n attachments?: Array<{ id: string; name: string; type: string; mimeType?: string; size?: number; url?: string }>;\n tokenCount?: number;\n model?: string;\n }>,\n): ChatMessage[] {\n return collapseConsecutiveAssistants(\n backendMessages.map((msg) => ({\n role: msg.role as 'user' | 'assistant',\n content: msg.content ?? '',\n attachments: msg.attachments?.map((a) => ({\n id: a.id,\n name: a.name,\n type: a.type === 'screenshot' ? 'screenshot' : 'file',\n mimeType: a.mimeType,\n size: a.size,\n url: a.url,\n })),\n metadata: msg.tokenCount\n ? {\n tokenUsage: {\n inputTokens: 0,\n outputTokens: msg.tokenCount,\n totalTokens: msg.tokenCount,\n },\n model: msg.model,\n }\n : undefined,\n })),\n );\n}\n\n/** Mobile chat routes exclusively through CDeCLI (messenger-gateway). */\nexport interface UseChatStreamRouting {\n channelConnected: boolean;\n accountId: string;\n /** When `'backend'`, the gateway persists posts — skip client `saveMessages`. */\n persistenceMode?: 'backend' | 'frontend';\n /** Remint the system JWT and reconnect after cdecli-agent 401s the session. */\n recoverAgentAuth?: () => Promise<boolean>;\n}\n\nexport function useChatStream(\n sessionId: string | null,\n routing: UseChatStreamRouting = {\n channelConnected: false,\n accountId: 'default',\n persistenceMode: 'backend',\n },\n) {\n const [messages, setMessages] = useState<ChatMessage[]>([]);\n const [response, setResponse] = useState('');\n /** Brain assist — never the published agent stream. Shown as a Quick answer strip. */\n const [quickReply, setQuickReply] = useState('');\n const [isLoading, setIsLoading] = useState(false);\n const [isStreaming, setIsStreaming] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const isSendingRef = useRef(false);\n /** Follow-ups typed before cdecli has an active session. Flushed after the first token. */\n const pendingSteersRef = useRef<string[]>([]);\n /** True once this turn has produced at least one stream chunk (steer is valid). */\n const sessionLiveRef = useRef(false);\n const flushPendingSteersRef = useRef<() => Promise<void>>(async () => {});\n const sendMessageRef = useRef<\n (\n content: string,\n attachments?: MessageAttachment[],\n sessionIdOverride?: string | null,\n alreadyVisible?: boolean,\n queuedId?: string,\n ) => Promise<SendOutcome>\n >(async () => 'failed');\n\n /** Ensures GraphQL stream subscriptions use the id from createChannel+send before the next parent render. */\n const [cdecliStreamOverrideId, setCdecliStreamOverrideId] = useState<string | undefined>(undefined);\n const userMsgForSaveRef = useRef<ChatMessage | null>(null);\n const saveSessionIdRef = useRef<string | null>(null);\n const sessionIdRef = useRef<string | null>(sessionId);\n sessionIdRef.current = sessionId || cdecliStreamOverrideId || null;\n /** Blocks duplicate cdecli `onComplete` from appending assistant twice / saving twice per send. */\n const cdecliRoundHandledRef = useRef(false);\n /** One remint+resend per turn when cdecli-agent 401s the JWT. */\n const authRetryUsedRef = useRef(false);\n const recoveringAuthRef = useRef(false);\n const routingRef = useRef(routing);\n routingRef.current = routing;\n\n const tryRecoverAndResendRef = useRef<(reason: string) => Promise<boolean>>(async () => false);\n\n /** Coalesce token deltas so Fabric is not committing a native tree every chunk. */\n const pendingStreamRef = useRef('');\n const streamFlushTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);\n\n const clearPendingStream = useCallback(() => {\n if (streamFlushTimerRef.current != null) {\n clearTimeout(streamFlushTimerRef.current);\n streamFlushTimerRef.current = null;\n }\n pendingStreamRef.current = '';\n }, []);\n\n const flushPendingStream = useCallback(() => {\n streamFlushTimerRef.current = null;\n const pending = pendingStreamRef.current;\n if (!pending) return;\n pendingStreamRef.current = '';\n setResponse((r) => {\n const next = r + pending;\n const sid = sessionIdRef.current;\n if (sid) markChannelHistoryRunning(sid, next);\n return next;\n });\n }, []);\n\n useEffect(() => () => clearPendingStream(), [clearPendingStream]);\n\n const { saveMessages, patchChannelTitle } = useChatMutations();\n const titlePatchedChannelsRef = useRef(new Set<string>());\n const { accountUserId } = usePrerequisiteIds();\n const [createAccountChatFileUploadLinksMutation] = useCreateAccountChatFileUploadLinksMutation();\n const [createAccountChatFileDownloadLinksMutation] = useCreateAccountChatFileDownloadLinksMutation();\n const {\n messages: backendMessages,\n loading: backendMessagesLoading,\n messagesLoaded: backendMessagesLoaded,\n } = useChatMessages(sessionId);\n const lastHydratedSessionIdRef = useRef<string | null>(null);\n /** Trash-clear: do not re-hydrate gateway history until the next send. */\n const ignoreHydrationRef = useRef(false);\n\n const streamChannelId = sessionId || cdecliStreamOverrideId;\n\n const finalizeCdecliRound = useCallback(\n (assistantContent?: string) => {\n const previewSid = saveSessionIdRef.current || sessionIdRef.current;\n clearPendingStream();\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n sessionLiveRef.current = false;\n setResponse('');\n setQuickReply('');\n setIsLoading(false);\n setIsStreaming(false);\n isSendingRef.current = false;\n if (previewSid) clearChannelHistoryRunning(previewSid);\n if (assistantContent !== undefined) {\n setMessages((prev) =>\n appendOrReplaceAssistant(prev, { role: 'assistant' as const, content: assistantContent }),\n );\n if (previewSid) patchChannelHistoryPreview(previewSid, assistantContent);\n }\n },\n [clearPendingStream],\n );\n\n const cdecliCallbacks = useMemo(\n () => ({\n onChunk: (text: string) => {\n if (!isSendingRef.current) {\n isSendingRef.current = true;\n cdecliRoundHandledRef.current = false;\n saveSessionIdRef.current = sessionIdRef.current;\n setIsLoading(true);\n setIsStreaming(true);\n setError(null);\n const sid = sessionIdRef.current;\n if (sid) markChannelHistoryRunning(sid, text);\n }\n pendingStreamRef.current += text;\n if (!sessionLiveRef.current) {\n sessionLiveRef.current = true;\n void flushPendingSteersRef.current();\n }\n if (streamFlushTimerRef.current == null) {\n streamFlushTimerRef.current = setTimeout(flushPendingStream, 50);\n }\n },\n // The brain's provisional answer is the WHOLE reply-so-far, not a chunk:\n // it is set outright, and set to '' when the real stream supersedes it.\n // It deliberately does not mark the session live - steers wait for the\n // agent, which is the only side that can act on them.\n onQuickReply: (text: string) => {\n setQuickReply(text);\n },\n onStreamRestart: () => {\n clearPendingStream();\n pendingStreamRef.current = '';\n setResponse('');\n },\n onComplete: (text: string) => {\n clearPendingStream();\n if (cdecliRoundHandledRef.current) {\n return;\n }\n\n if (isCdecliAgentFailureOutput(text)) {\n void (async () => {\n if (await tryRecoverAndResendRef.current(text)) return;\n if (cdecliRoundHandledRef.current) return;\n cdecliRoundHandledRef.current = true;\n pendingSteersRef.current = [];\n setError(\n isAgentJwtRejected(text)\n ? text\n : 'CDeCLI agent error. Check gateway status and server-side LLM configuration.',\n );\n finalizeCdecliRound(isAgentJwtRejected(text) ? undefined : text);\n })();\n return;\n }\n\n cdecliRoundHandledRef.current = true;\n authRetryUsedRef.current = false;\n\n const reply = resolveAssistantReply(text);\n const sid = saveSessionIdRef.current;\n const um = userMsgForSaveRef.current;\n const leftover = pendingSteersRef.current;\n pendingSteersRef.current = [];\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n sessionLiveRef.current = false;\n\n setMessages((prev) => appendOrReplaceAssistant(prev, { role: 'assistant' as const, content: reply }));\n const previewSid = sid || sessionIdRef.current;\n if (previewSid) {\n clearChannelHistoryRunning(previewSid);\n patchChannelHistoryPreview(previewSid, reply);\n }\n setResponse('');\n setQuickReply('');\n setIsLoading(false);\n setIsStreaming(false);\n isSendingRef.current = false;\n\n const rt = routingRef.current;\n const persistClientSide = rt.persistenceMode !== 'backend';\n\n if (sid && um && persistClientSide) {\n saveMessages({\n sessionId: sid,\n ...(accountUserId ? { createdBy: accountUserId } : {}),\n userMessage: {\n content: um.content,\n attachments: um.attachments?.map((a) => ({\n id: a.id,\n name: a.name,\n type: a.type,\n mimeType: a.mimeType,\n size: a.size,\n url: a.url,\n })),\n },\n assistantMessage: {\n content: reply,\n tokenCount: undefined,\n model: 'cdecli-serve',\n },\n }).catch((e) => {\n console.error('[useChatStream] saveMessages (cdecli):', e);\n });\n }\n\n if (leftover.length > 0) {\n const [first, ...rest] = leftover;\n pendingSteersRef.current = rest;\n queueMicrotask(() => {\n void sendMessageRef.current(first, undefined, sid, true);\n });\n }\n },\n onError: (err: string) => {\n if (cdecliRoundHandledRef.current) return;\n void (async () => {\n if (await tryRecoverAndResendRef.current(err)) return;\n if (cdecliRoundHandledRef.current) return;\n cdecliRoundHandledRef.current = true;\n pendingSteersRef.current = [];\n setError(err || 'CDeCLI stream error.');\n finalizeCdecliRound(resolveAssistantReply(''));\n })();\n },\n }),\n [saveMessages, accountUserId, finalizeCdecliRound, flushPendingStream, clearPendingStream],\n );\n\n const {\n sendMessage: sendCdecliMessage,\n steer: steerCdecliMessage,\n cancel: cancelCdecliTurn,\n } = useCdecliChannel(routing.channelConnected, routing.accountId, streamChannelId, cdecliCallbacks);\n\n const flushPendingSteers = useCallback(async () => {\n if (!sessionLiveRef.current || !isSendingRef.current) return;\n const sid = saveSessionIdRef.current;\n if (!sid) return;\n\n while (pendingSteersRef.current.length > 0 && sessionLiveRef.current && isSendingRef.current) {\n const next = pendingSteersRef.current[0];\n const result = await steerCdecliMessage(next, sid);\n if (result.ok) {\n pendingSteersRef.current.shift();\n continue;\n }\n if (isNoActiveSessionError(result.error)) {\n return;\n }\n pendingSteersRef.current.shift();\n setError(result.error || 'Could not send follow-up. Try again.');\n return;\n }\n }, [steerCdecliMessage]);\n\n flushPendingSteersRef.current = flushPendingSteers;\n\n useEffect(() => {\n if (sessionId && cdecliStreamOverrideId && sessionId === cdecliStreamOverrideId) {\n setCdecliStreamOverrideId(undefined);\n }\n }, [sessionId, cdecliStreamOverrideId]);\n\n useEffect(() => {\n const prevSid = lastHydratedSessionIdRef.current;\n if (prevSid && sessionId && prevSid !== sessionId && isSendingRef.current) {\n // Switching threads: drop local send flags so this view can hydrate.\n // The previous channel's agent keeps running server-side; history still\n // shows it as running until that turn completes or we reopen it.\n clearPendingStream();\n pendingSteersRef.current = [];\n isSendingRef.current = false;\n sessionLiveRef.current = false;\n cdecliRoundHandledRef.current = false;\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n setIsLoading(false);\n setIsStreaming(false);\n setResponse('');\n setQuickReply('');\n }\n\n if (!sessionId) {\n setMessages([]);\n setResponse('');\n setQuickReply('');\n lastHydratedSessionIdRef.current = null;\n return;\n }\n\n const stampHistoryPreview = (msgs: ChatMessage[]) => {\n const last = msgs[msgs.length - 1];\n const lastAssistant = [...msgs].reverse().find((msg) => msg.role === 'assistant' && msg.content.trim());\n if (lastAssistant && !isSendingRef.current) {\n patchChannelHistoryPreview(sessionId, lastAssistant.content);\n }\n // Finished thread (last post is assistant) — drop the history \"Running\" badge.\n // A live turn ends with a user post until the assistant lands.\n if (!isSendingRef.current && last?.role === 'assistant') {\n clearChannelHistoryRunning(sessionId);\n }\n };\n\n if (ignoreHydrationRef.current) {\n return;\n }\n\n const keepStream = isSendingRef.current;\n const sessionChanged = lastHydratedSessionIdRef.current !== sessionId;\n if (sessionChanged) {\n lastHydratedSessionIdRef.current = sessionId;\n // Do not merge the previous channel's in-memory thread into this one.\n if (!backendMessagesLoaded) {\n if (!keepStream) {\n setMessages([]);\n setResponse('');\n setQuickReply('');\n }\n return;\n }\n const formatted = formatBackendThread(backendMessages ?? []);\n stampHistoryPreview(formatted);\n setMessages((prev) => (keepStream ? mergeOptimisticGatewayMessages(prev, formatted) : formatted));\n if (!keepStream) {\n setResponse('');\n setQuickReply('');\n }\n return;\n }\n\n if (backendMessagesLoaded) {\n const formatted = formatBackendThread(backendMessages ?? []);\n stampHistoryPreview(formatted);\n // Positional merge first so assistant replies the gateway never persisted\n // (cdecli skill turns emit no chatMessageAdded) survive this snapshot instead\n // of being dropped, then preserve in-memory attachment previews on the result.\n setMessages((prev) => preserveAttachmentPreviews(prev, mergeOptimisticGatewayMessages(prev, formatted)));\n if (!keepStream) {\n setResponse('');\n setQuickReply('');\n }\n }\n }, [sessionId, backendMessages, backendMessagesLoaded, clearPendingStream]);\n\n const sendMessage = useCallback(\n async (\n content: string,\n attachments?: MessageAttachment[],\n sessionIdOverride?: string | null,\n alreadyVisible = false,\n /** Set when this send is the release of an outbox entry; it owns that entry's fate. */\n queuedId: string | undefined = undefined,\n ): Promise<SendOutcome> => {\n if (!content.trim() && !attachments?.length) return 'failed';\n\n const effectiveSessionId = sessionIdOverride !== undefined ? sessionIdOverride : sessionId;\n const rt = routingRef.current;\n const trimmed = content.trim();\n const sendText =\n trimmed ||\n (attachments?.length\n ? `Attached: ${attachments\n .map((a) => a.name)\n .filter(Boolean)\n .join(', ')}`\n : '');\n\n const userMessage: ChatMessage = {\n role: 'user',\n content: sendText,\n attachments,\n };\n\n /**\n * The gateway is down. The turn is remembered, not erased: it stays in the\n * thread as a queued bubble and the outbox releases it in order the moment\n * the channel reports connected. Losing what the user typed here is the\n * whole reason this lane exists.\n */\n if (!rt.channelConnected) {\n if (!effectiveSessionId) {\n setError('Missing chat session id.');\n return 'failed';\n }\n // A release that raced the connection dropping stays where it is.\n if (queuedId) return 'queued';\n const result = queueGatewayMessage({\n channelId: effectiveSessionId,\n accountId: rt.accountId,\n text: sendText,\n attachments,\n });\n if (!result.ok) {\n setError(\n result.reason === 'full'\n ? `${MAX_QUEUED_MESSAGES} messages are already waiting for the gateway. They send as soon as it connects.`\n : 'Nothing to send.',\n );\n return 'failed';\n }\n if (alreadyVisible) setMessages((prev) => withoutTrailingUserMessage(prev, sendText));\n setError(null);\n return 'queued';\n }\n\n /**\n * A turn is already in flight. Keep the follow-up visible and queue it.\n * cdecli rejects steer until the agent session exists (\"no active session\"),\n * which is after the first token. Flush then. Never error/LogBox for that race.\n */\n if (isSendingRef.current) {\n if (!effectiveSessionId) {\n setError('Missing chat session id.');\n return 'failed';\n }\n if (!alreadyVisible) setMessages((prev) => [...prev, userMessage]);\n setError(null);\n pendingSteersRef.current = [...pendingSteersRef.current, sendText];\n if (queuedId) dropQueuedGatewayMessage(queuedId);\n void flushPendingSteers();\n return 'sent';\n }\n\n isSendingRef.current = true;\n sessionLiveRef.current = false;\n ignoreHydrationRef.current = false;\n if (effectiveSessionId && sendText) {\n titlePatchedChannelsRef.current.add(effectiveSessionId);\n patchChannelTitle(effectiveSessionId, sendText, true);\n markChannelHistoryRunning(effectiveSessionId);\n }\n if (!alreadyVisible) {\n // The transcript keeps this turn for the rest of the session, so it\n // keeps the preview URI and not the base64 behind it. The bytes stay\n // on `userMsgForSaveRef` below, which is nulled when the turn ends -\n // a retry still has them, a backgrounded app no longer carries them.\n const retained: ChatMessage = {\n ...userMessage,\n attachments: releasePreviewBytes(userMessage.attachments),\n };\n setMessages((prev) => [...prev, retained]);\n authRetryUsedRef.current = false;\n }\n setResponse('');\n setQuickReply('');\n setIsLoading(true);\n setIsStreaming(true);\n setError(null);\n userMsgForSaveRef.current = userMessage;\n saveSessionIdRef.current = effectiveSessionId ?? null;\n cdecliRoundHandledRef.current = false;\n\n if (!effectiveSessionId) {\n setError('Missing chat session id.');\n if (!alreadyVisible) setMessages((p) => p.slice(0, -1));\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n userMsgForSaveRef.current = null;\n saveSessionIdRef.current = null;\n return 'failed';\n }\n\n if (sessionIdOverride) {\n setCdecliStreamOverrideId(sessionIdOverride);\n await new Promise<void>((resolve) => {\n setTimeout(resolve, 0);\n });\n }\n\n const inlineForHostedAgent = shouldInlineGatewayMediaForHostedAgent(\n config.GRAPHQL_URL,\n config.CDECLI_AGENT_ENDPOINT,\n );\n // Vision turns must carry inline bytes. URL-only media is what made\n // \"what is this\" + a photo look like a text-only question.\n const inlineImages = (attachments ?? []).some(isImageAttachment) || inlineForHostedAgent;\n let media = inlineImages\n ? buildGatewayMedia(attachments, { includeData: true })\n : await buildGatewayMediaPreferUrls(\n attachments,\n async (filenames) => {\n const result = await createAccountChatFileUploadLinksMutation({\n variables: { filenames },\n });\n return result.data?.createAccountChatFileUploadLinks || [];\n },\n async (urls) => {\n const result = await createAccountChatFileDownloadLinksMutation({\n variables: { urls },\n });\n return result.data?.createAccountChatFileDownloadLinks || [];\n },\n );\n if ((attachments?.length ?? 0) > 0 && media.length === 0) {\n media = buildGatewayMedia(attachments, { includeData: true });\n }\n const ok = await sendCdecliMessage(sendText, effectiveSessionId, media);\n if (!ok && !cdecliRoundHandledRef.current && !recoveringAuthRef.current) {\n cdecliRoundHandledRef.current = true;\n // The send never reached the agent. Park it rather than drop it - a\n // release keeps its place at the head of its own queue.\n const parked = queuedId\n ? { ok: true as const }\n : queueGatewayMessage({\n channelId: effectiveSessionId,\n accountId: rt.accountId,\n text: sendText,\n attachments,\n });\n setError(\n parked.ok\n ? 'Gateway unreachable - message queued. It sends as soon as the connection is back.'\n : 'Failed to send message via CDeCLI. Check gateway connection.',\n );\n // Queued: the queued row renders the turn, so the optimistic bubble goes.\n // Not queued: only drop a bubble this call put there.\n setMessages((p) => {\n if (parked.ok) return withoutTrailingUserMessage(p, sendText);\n return alreadyVisible ? p : p.slice(0, -1);\n });\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n userMsgForSaveRef.current = null;\n saveSessionIdRef.current = null;\n clearChannelHistoryRunning(effectiveSessionId);\n return parked.ok ? 'queued' : 'failed';\n }\n if (ok && queuedId) dropQueuedGatewayMessage(queuedId);\n return ok ? 'sent' : 'failed';\n },\n [\n sessionId,\n sendCdecliMessage,\n patchChannelTitle,\n flushPendingSteers,\n createAccountChatFileUploadLinksMutation,\n createAccountChatFileDownloadLinksMutation,\n ],\n );\n\n sendMessageRef.current = sendMessage;\n\n /* ---------------------------------------------------------------------- *\n * Outbox: turns typed while the gateway was down.\n * ---------------------------------------------------------------------- */\n\n const queuedChannelId = sessionId || cdecliStreamOverrideId || null;\n const queuedSnapshot = useCallback(\n () => queuedGatewayMessages(queuedChannelId, routing.accountId),\n [queuedChannelId, routing.accountId],\n );\n const queuedMessages = useSyncExternalStore(subscribeQueuedGatewayMessages, queuedSnapshot, queuedSnapshot);\n\n useEffect(() => {\n void restoreQueuedGatewayMessages();\n }, []);\n\n /** One release at a time; a send that fails leaves its entry at the head for the next reconnect. */\n const flushingRef = useRef(false);\n const flushQueuedMessages = useCallback(async () => {\n if (flushingRef.current) return;\n flushingRef.current = true;\n try {\n // Bounded: the outbox can never hand out more than its own depth.\n for (let i = 0; i <= MAX_QUEUED_MESSAGES; i += 1) {\n const rt = routingRef.current;\n const sid = sessionIdRef.current;\n if (!rt.channelConnected || !sid) return;\n const next = queuedGatewayMessages(sid, rt.accountId)[0];\n if (!next) return;\n const outcome = await sendMessageRef.current(\n next.text,\n next.attachments,\n next.channelId,\n false,\n next.id,\n );\n if (outcome !== 'sent') return;\n }\n } finally {\n flushingRef.current = false;\n }\n }, []);\n\n /**\n * Release on the disconnected→connected edge, and when a channel with a queue\n * is opened on an already-live gateway. Deliberately not keyed on queue depth:\n * a send that fails puts its turn back, and depth would spin that into a loop.\n */\n const wasConnectedRef = useRef(routing.channelConnected);\n useEffect(() => {\n const connected = routing.channelConnected;\n const reconnected = connected && !wasConnectedRef.current;\n wasConnectedRef.current = connected;\n if (!connected || !queuedChannelId) return;\n if (!reconnected && queuedGatewayMessages(queuedChannelId, routing.accountId).length === 0) return;\n void flushQueuedMessages();\n }, [routing.channelConnected, routing.accountId, queuedChannelId, flushQueuedMessages]);\n\n const discardQueuedMessages = useCallback(() => {\n if (!queuedChannelId) return;\n clearQueuedGatewayMessages(queuedChannelId);\n setError(null);\n }, [queuedChannelId]);\n\n tryRecoverAndResendRef.current = async (reason: string) => {\n if (authRetryUsedRef.current || cdecliRoundHandledRef.current) return false;\n if (!isAgentJwtRejected(reason)) return false;\n const recover = routingRef.current.recoverAgentAuth;\n if (!recover) return false;\n authRetryUsedRef.current = true;\n recoveringAuthRef.current = true;\n try {\n setError('Refreshing CDeCLI credentials…');\n const recovered = await recover();\n if (!recovered) return false;\n const um = userMsgForSaveRef.current;\n const sid = saveSessionIdRef.current;\n cdecliRoundHandledRef.current = false;\n isSendingRef.current = false;\n setIsLoading(false);\n setIsStreaming(false);\n setError(null);\n if (um && sid) {\n queueMicrotask(() => {\n void sendMessageRef.current(um.content, um.attachments, sid, true);\n });\n }\n return true;\n } catch (err) {\n console.error('[useChatStream] recoverAgentAuth failed:', err);\n return false;\n } finally {\n recoveringAuthRef.current = false;\n }\n };\n\n const cancel = useCallback(() => {\n clearPendingStream();\n pendingSteersRef.current = [];\n sessionLiveRef.current = false;\n const sid = saveSessionIdRef.current ?? sessionId;\n void cancelCdecliTurn(sid ?? 'messenger');\n if (!cdecliRoundHandledRef.current) {\n cdecliRoundHandledRef.current = true;\n finalizeCdecliRound(resolveAssistantReply(''));\n }\n }, [cancelCdecliTurn, finalizeCdecliRound, sessionId, clearPendingStream]);\n\n const clearMessages = useCallback(() => {\n clearPendingStream();\n pendingSteersRef.current = [];\n const hadActiveTurn = isSendingRef.current || sessionLiveRef.current;\n const sid = saveSessionIdRef.current ?? sessionId;\n sessionLiveRef.current = false;\n isSendingRef.current = false;\n cdecliRoundHandledRef.current = true;\n saveSessionIdRef.current = null;\n userMsgForSaveRef.current = null;\n // Only hit /cancel when a turn was live — otherwise cdecli logs\n // \"Cannot cancel: no active session\" (Research greet + trash).\n if (hadActiveTurn) {\n void cancelCdecliTurn(sid ?? 'messenger');\n }\n ignoreHydrationRef.current = true;\n // Emptying the thread empties its outbox too: a queued turn released after\n // the user cleared the chat would answer a conversation they threw away.\n if (sid) clearQueuedGatewayMessages(sid);\n setMessages([]);\n setResponse('');\n setQuickReply('');\n setError(null);\n setIsLoading(false);\n setIsStreaming(false);\n if (sid) clearChannelHistoryRunning(sid);\n }, [cancelCdecliTurn, clearPendingStream, sessionId]);\n\n const messagesLoading = !!sessionId && backendMessagesLoading && !backendMessagesLoaded;\n\n return {\n messages,\n response,\n quickReply,\n error,\n isLoading,\n isStreaming,\n messagesLoading,\n hasMessages: messages.length > 0 || !!response || !!quickReply || queuedMessages.length > 0,\n /** Turns waiting on the gateway, oldest first. Rendered as queued bubbles. */\n queuedMessages,\n /** Send the queue now (the notice's retry), independent of the reconnect edge. */\n flushQueuedMessages,\n discardQueuedMessages,\n sendMessage,\n cancel,\n clearMessages,\n };\n}\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;AAgBA,SAAS,2BAA2B,IAAuB,EAAA;AACzD,EAAM,MAAA,CAAA,GAAI,KAAK,IAAK,EAAA;AACpB,EAAI,IAAA,CAAC,GAAU,OAAA,KAAA;AACf,EAAO,OAAA,YAAA,CAAa,KAAK,CAAC,CAAA,IAAK,oBAAoB,IAAK,CAAA,CAAC,KAAK,oBAAqB,CAAA,IAAA,CAAK,CAAC,CAAK,IAAA,kBAAA,CAAmB,KAAK,CAAC,CAAA,IAAK,wBAAwB,IAAK,CAAA,CAAC,CAAK,IAAA,kBAAA,CAAmB,CAAC,CAAA;AACrL;AAyBA,SAAS,0BAAA,CAA2B,MAAqB,IAA6B,EAAA;AACpF,EAAA,MAAM,IAAO,GAAA,IAAA,CAAK,IAAK,CAAA,MAAA,GAAS,CAAC,CAAA;AACjC,EAAO,OAAA,CAAA,IAAA,IAAA,IAAA,GAAA,MAAA,GAAA,IAAA,CAAM,IAAS,MAAA,MAAA,IAAU,IAAK,CAAA,OAAA,KAAY,OAAO,IAAK,CAAA,KAAA,CAAM,CAAG,EAAA,EAAE,CAAI,GAAA,IAAA;AAC9E;AAIA,SAAS,oBAAoB,eAeV,EAAA;AACjB,EAAO,OAAA,6BAAA,CAA8B,eAAgB,CAAA,GAAA,CAAI,CAAI,GAAA,KAAA;AApE/D,IAAA,IAAA,EAAA,EAAA,EAAA;AAoEmE,IAAA,OAAA;AAAA,MAC/D,MAAM,GAAI,CAAA,IAAA;AAAA,MACV,OAAA,EAAA,CAAS,EAAI,GAAA,GAAA,CAAA,OAAA,KAAJ,IAAe,GAAA,EAAA,GAAA,EAAA;AAAA,MACxB,WAAa,EAAA,CAAA,EAAA,GAAA,GAAA,CAAI,WAAJ,KAAA,IAAA,GAAA,MAAA,GAAA,EAAA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IAAA,WAAA,CAAY,EAAE,CAAA;AACd,IAAA,aAAA,CAAc,EAAE,CAAA;AAChB,IAAA,QAAA,CAAS,IAAI,CAAA;AACb,IAAA,YAAA,CAAa,KAAK,CAAA;AAClB,IAAA,cAAA,CAAe,KAAK,CAAA;AACpB,IAAI,IAAA,GAAA,6BAAgC,GAAG,CAAA;AAAA,GACtC,EAAA,CAAC,gBAAkB,EAAA,kBAAA,EAAoB,SAAS,CAAC,CAAA;AACpD,EAAA,MAAM,eAAkB,GAAA,CAAC,CAAC,SAAA,IAAa,0BAA0B,CAAC,qBAAA;AAClE,EAAO,OAAA;AAAA,IACL,QAAA;AAAA,IACA,QAAA;AAAA,IACA,UAAA;AAAA,IACA,KAAA;AAAA,IACA,SAAA;AAAA,IACA,WAAA;AAAA,IACA,eAAA;AAAA,IACA,WAAA,EAAa,QAAS,CAAA,MAAA,GAAS,CAAK,IAAA,CAAC,CAAC,QAAA,IAAY,CAAC,CAAC,UAAc,IAAA,cAAA,CAAe,MAAS,GAAA,CAAA;AAAA;AAAA,IAE1F,cAAA;AAAA;AAAA,IAEA,mBAAA;AAAA,IACA,qBAAA;AAAA,IACA,WAAA;AAAA,IACA,MAAA;AAAA,IACA;AAAA,GACF;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@adminide-stack/yantra-mobile",
|
|
3
|
-
"version": "12.0.64
|
|
3
|
+
"version": "12.0.64",
|
|
4
4
|
"description": "Sample core for higher packages to depend on",
|
|
5
5
|
"license": "ISC",
|
|
6
6
|
"author": "CDMBase LLC",
|
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
"uuid": "^9.0.0"
|
|
26
26
|
},
|
|
27
27
|
"devDependencies": {
|
|
28
|
-
"common": "12.0.64
|
|
28
|
+
"common": "^12.0.64"
|
|
29
29
|
},
|
|
30
30
|
"peerDependencies": {
|
|
31
31
|
"@admin-layout/gluestack-ui-mobile": "*",
|
|
@@ -41,7 +41,7 @@
|
|
|
41
41
|
"@messenger-box/platform-mobile": "*",
|
|
42
42
|
"@react-native-async-storage/async-storage": "*",
|
|
43
43
|
"@react-navigation/native": "*",
|
|
44
|
-
"common": "12.0.
|
|
44
|
+
"common": "12.0.62",
|
|
45
45
|
"expo-constants": "*",
|
|
46
46
|
"expo-secure-store": "*",
|
|
47
47
|
"lodash": "*",
|
|
@@ -57,5 +57,5 @@
|
|
|
57
57
|
"typescript": {
|
|
58
58
|
"definition": "lib/index.d.ts"
|
|
59
59
|
},
|
|
60
|
-
"gitHead": "
|
|
60
|
+
"gitHead": "95ef408f530e33065e3a353010fe6dc543aae28b"
|
|
61
61
|
}
|