-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathapp-v3-ai.js
More file actions
589 lines (529 loc) ยท 20.9 KB
/
Copy pathapp-v3-ai.js
File metadata and controls
589 lines (529 loc) ยท 20.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
import { isDirectMessengerAiEnabled } from "./direct-messenger-ai-config.js";
export const AI_COMPANION_ID = "ai-companion";
export const AI_THREAD_ID = "thread-ai-companion";
const AI_CREATED_AT = new Date("2026-05-01").toISOString();
export const AI_COMPANION_PROFILE = Object.freeze({
id: AI_COMPANION_ID,
email: "ai@signal.share",
displayName: "AI Companion",
isAi: true,
createdAt: AI_CREATED_AT
});
function readFileAsDataURL(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
export function isAiThreadId(threadId) {
return threadId === AI_THREAD_ID;
}
export function getAiMessagesStorageKey(state) {
if (!state?.currentUser?.id) return "";
return `ai-messages-${state.currentUser.id}`;
}
function sanitizeAiMessageForStorage(message) {
if (!message || typeof message !== "object") return null;
const next = { ...message };
if (next.isThinking) return null;
if (typeof next.attachmentUrl === "string" && /^blob:/i.test(next.attachmentUrl.trim())) {
next.attachmentUrl = "";
}
if (next.attachmentUrl === null) next.attachmentUrl = "";
if (!next.createdAt) next.createdAt = new Date().toISOString();
return next;
}
export function sanitizeAiMessagesForStorage(messages) {
if (!Array.isArray(messages)) return [];
return messages
.map(sanitizeAiMessageForStorage)
.filter((entry) => entry && typeof entry === "object");
}
export function loadAiMessagesLocally(state) {
const storageKey = getAiMessagesStorageKey(state);
if (!storageKey) return [];
const raw = localStorage.getItem(storageKey);
if (!raw) return [];
try {
const parsed = JSON.parse(raw);
const sanitized = sanitizeAiMessagesForStorage(parsed);
const normalizedRaw = JSON.stringify(sanitized);
if (normalizedRaw !== raw) {
localStorage.setItem(storageKey, normalizedRaw);
}
return sanitized;
} catch (error) {
console.warn("AI local message cache was invalid and has been reset.", error);
localStorage.removeItem(storageKey);
return [];
}
}
export function clearAiMessagesLocally(state) {
const storageKey = getAiMessagesStorageKey(state);
if (!storageKey) return;
localStorage.removeItem(storageKey);
}
export function saveAiMessagesLocally(state, messages) {
const storageKey = getAiMessagesStorageKey(state);
if (!storageKey) return;
const sanitized = sanitizeAiMessagesForStorage(messages);
try {
localStorage.setItem(storageKey, JSON.stringify(sanitized));
} catch (error) {
console.warn("AI local message cache exceeded limits; retrying without attachment payloads.", error);
try {
const fallback = sanitized.map((message) => ({ ...message, attachmentUrl: "" }));
localStorage.setItem(storageKey, JSON.stringify(fallback));
} catch (finalError) {
console.warn("AI local message cache could not be saved.", finalError);
}
}
}
export function buildAiThread(userId, { createdAt = AI_CREATED_AT, updatedAt = "", lastMessageBody = "" } = {}) {
const normalizedCreatedAt = typeof createdAt === "string" && createdAt.trim()
? createdAt
: AI_CREATED_AT;
const normalizedUpdatedAt = typeof updatedAt === "string" && updatedAt.trim()
? updatedAt
: new Date().toISOString();
const thread = {
id: AI_THREAD_ID,
userOneId: userId || "",
userTwoId: AI_COMPANION_ID,
createdAt: normalizedCreatedAt,
updatedAt: normalizedUpdatedAt,
isAi: true
};
if (typeof lastMessageBody === "string" && lastMessageBody.trim()) {
thread.lastMessageBody = lastMessageBody;
}
return thread;
}
export function appendAiThreadFromLocalHistory({ state, threads }) {
if (!isDirectMessengerAiEnabled()) {
const safeThreads = Array.isArray(threads) ? threads : [];
const filtered = safeThreads.filter((thread) => thread?.id !== AI_THREAD_ID && !thread?.isAi);
return { threads: filtered, aiHistory: [] };
}
const aiHistory = loadAiMessagesLocally(state);
if (!Array.isArray(threads)) return { threads: [], aiHistory };
if (aiHistory.length === 0) return { threads: [...threads], aiHistory };
if (threads.some((thread) => thread?.id === AI_THREAD_ID)) return { threads: [...threads], aiHistory };
const lastMessage = aiHistory[aiHistory.length - 1];
const aiThread = buildAiThread(state?.currentUser?.id || "", {
updatedAt: lastMessage?.createdAt || new Date().toISOString(),
lastMessageBody: lastMessage?.body || ""
});
return { threads: [...threads, aiThread], aiHistory };
}
export function handleAiOpenOrCreateThread({
partnerId,
state,
sortThreads,
clearMessageAttachmentSelection,
showMessengerFeedback
}) {
if (!isDirectMessengerAiEnabled()) return false;
if (partnerId !== AI_COMPANION_ID) return false;
const nowIso = new Date().toISOString();
const aiThread = buildAiThread(state?.currentUser?.id || "", {
createdAt: nowIso,
updatedAt: nowIso
});
if (!state.directThreads.some((thread) => thread?.id === aiThread.id)) {
state.directThreads = sortThreads([aiThread, ...state.directThreads]);
}
state.activeThreadId = aiThread.id;
state.activeMessages = loadAiMessagesLocally(state);
clearMessageAttachmentSelection?.({ preserveFeedback: true });
showMessengerFeedback?.("");
return true;
}
export async function handleAiThreadMessageSubmit({
state,
elements,
body,
attachmentFile,
getMessageAttachmentKind,
getActiveThread,
mergeActiveMessage,
renderMessenger,
showMessengerFeedback,
playIncomingMessageSound
}) {
if (!isDirectMessengerAiEnabled()) return false;
const activeThread = getActiveThread();
if (!activeThread?.isAi) return false;
try {
const userMessage = {
id: crypto.randomUUID(),
threadId: state.activeThreadId,
senderId: state.currentUser.id,
body,
createdAt: new Date().toISOString(),
attachmentUrl: null,
attachmentKind: attachmentFile ? getMessageAttachmentKind(attachmentFile.type) : null,
attachmentName: attachmentFile ? attachmentFile.name : null,
attachmentType: attachmentFile ? attachmentFile.type : null,
attachmentSize: attachmentFile ? attachmentFile.size : 0
};
const directSteamTarget = window.SignalShareAiCore?.parseDirectSteamCommand?.(body) || "";
const directDuckDuckGoQuery = window.SignalShareAiCore?.parseDuckDuckGoCommand?.(body) || "";
if (directSteamTarget || directDuckDuckGoQuery) {
mergeActiveMessage(userMessage);
saveAiMessagesLocally(state, state.activeMessages);
state.messageAttachmentFile = null;
state.messageAttachmentPreviewUrl = "";
renderMessenger();
let aiReply = "";
if (directSteamTarget) {
const steamPlan = window.SignalShareAiCore?.buildSteamLaunchPlan?.(directSteamTarget) || null;
if (steamPlan?.type === "run" && steamPlan.uri) {
window.location.href = steamPlan.uri;
aiReply = `๐ฎ [Steam Protocol]: Launching ${steamPlan.key.toUpperCase()} via Steam now.`;
} else {
const searchUrl = steamPlan?.searchUrl || `https://store.steampowered.com/search/?term=${encodeURIComponent(directSteamTarget)}`;
window.open(searchUrl, "_blank", "noopener,noreferrer");
aiReply = `๐ฎ [Steam Protocol]: I couldn't find a direct app ID for "${directSteamTarget}", so I opened Steam search.`;
}
} else {
const query = directDuckDuckGoQuery.trim();
if (query) {
const url = `https://duckduckgo.com/?q=${encodeURIComponent(query)}`;
window.open(url, "_blank", "noopener,noreferrer");
aiReply = `๐ [Search Protocol]: Searching DuckDuckGo for "${query}".`;
} else {
aiReply = "๐ [Search Protocol]: Tell me what you want to search on DuckDuckGo.";
}
}
const directAiMessage = {
id: crypto.randomUUID(),
threadId: state.activeThreadId,
senderId: AI_COMPANION_ID,
body: aiReply,
createdAt: new Date().toISOString()
};
mergeActiveMessage(directAiMessage);
saveAiMessagesLocally(state, state.activeMessages);
renderMessenger();
playIncomingMessageSound();
showMessengerFeedback("");
return true;
}
let aiAttachment = null;
if (attachmentFile) {
try {
aiAttachment = {
data: await readFileAsDataURL(attachmentFile),
type: getMessageAttachmentKind(attachmentFile.type),
name: attachmentFile.name
};
if (aiAttachment?.data) {
userMessage.attachmentUrl = aiAttachment.data;
}
} catch (error) {
console.error("Failed to read AI attachment", error);
}
}
const history = window.SignalShareAiCore
? window.SignalShareAiCore.normalizeHistory(state.activeMessages, {
aiSenderId: AI_COMPANION_ID,
currentMessageId: userMessage.id
})
: state.activeMessages
.filter((message) => !message.isThinking && message.id !== userMessage.id)
.map((message) => ({
role: message.senderId === AI_COMPANION_ID ? "assistant" : "user",
content: `${message.body || ""}`.trim().slice(0, 900)
}))
.filter((row) => row.content.length > 0)
.slice(-18);
mergeActiveMessage(userMessage);
saveAiMessagesLocally(state, state.activeMessages);
state.messageAttachmentFile = null;
state.messageAttachmentPreviewUrl = "";
renderMessenger();
const thinkingId = `thinking-${crypto.randomUUID()}`;
const thinkingMessage = {
id: thinkingId,
threadId: state.activeThreadId,
senderId: AI_COMPANION_ID,
body: "Thinking...",
isThinking: true,
createdAt: new Date().toISOString()
};
state.activeMessages.push(thinkingMessage);
renderMessenger();
if (window.heroMediaPlayerController) {
try {
const refreshTasks = [];
if (typeof window.heroMediaPlayerController.refreshDesktopSnapshot === "function") {
refreshTasks.push(Promise.resolve(
window.heroMediaPlayerController.refreshDesktopSnapshot({ force: true, renderAfter: false })
));
}
if (typeof window.heroMediaPlayerController.refreshNativeSnapshot === "function") {
refreshTasks.push(Promise.resolve(
window.heroMediaPlayerController.refreshNativeSnapshot({ renderAfter: false })
));
}
if (refreshTasks.length > 0) {
await Promise.race([
Promise.allSettled(refreshTasks),
new Promise((resolve) => window.setTimeout(resolve, 500))
]);
}
} catch (error) {
console.warn("Failed to refresh media context for AI", error);
}
}
const pageContext = document.title || "Signal Share";
const pageRoot = document.querySelector(".page-shell") || document.body;
const pageText = `${pageRoot?.textContent || ""}`.replace(/\s+/g, " ").trim().slice(0, 600);
const sharedAiContext = window.SignalShareAiCore
? window.SignalShareAiCore.buildCompanionContext({
surface: "main",
pageTitle: document.title || "",
pageUrl: window.location.href,
currentCategory: state.messengerOpen ? "messenger" : "feed",
visibleText: pageText,
attachment: aiAttachment
})
: "";
const fullContext = `${pageContext} (Visible text: ${pageText})${sharedAiContext ? `\n\n${sharedAiContext}` : ""}`;
let aiResponse;
try {
aiResponse = await callLocalAI({
text: body,
history,
pageContext: fullContext,
attachment: aiAttachment,
conversationId: state.activeThreadId
});
} finally {
state.activeMessages = state.activeMessages.filter((message) => message.id !== thinkingId);
}
const aiMessage = {
id: crypto.randomUUID(),
threadId: state.activeThreadId,
senderId: AI_COMPANION_ID,
body: aiResponse,
createdAt: new Date().toISOString()
};
mergeActiveMessage(aiMessage);
saveAiMessagesLocally(state, state.activeMessages);
if (aiResponse && aiResponse.includes("[ARCADE:")) {
const arcadeMatch = aiResponse.match(/\[ARCADE:\s*([^\]]+)\]/);
if (arcadeMatch && typeof window.executeArcadeAction === "function") {
const action = arcadeMatch[1].trim().toLowerCase();
window.executeArcadeAction(action);
}
}
renderMessenger();
playIncomingMessageSound();
showMessengerFeedback("");
} catch (error) {
console.error("AI response failed", error);
showMessengerFeedback("AI Companion is currently offline.", true);
} finally {
window.__SIGNAL_MESSENGER_SUBMITTING__ = false;
state.messengerBusy = Math.max(0, state.messengerBusy - 1);
if (elements?.messageInput) elements.messageInput.disabled = false;
if (elements?.sendMessageButton) elements.sendMessageButton.disabled = false;
renderMessenger();
}
return true;
}
async function callLocalAI({
text,
history = [],
pageContext = "",
attachment = null,
conversationId = ""
}) {
let abortController = new AbortController();
let stopRequested = false;
window.stopMessengerAi = () => {
stopRequested = true;
if (abortController) {
abortController.abort();
abortController = null;
}
};
let reply = null;
let lastError = null;
const modelSelect = document.getElementById("chat-model-select");
const selectedModel = modelSelect ? modelSelect.value : "auto";
const requestModel = typeof window.resolveChatRequestModel === "function"
? window.resolveChatRequestModel(selectedModel)
: (`${selectedModel || "auto"}`.trim() || "auto");
const coreInstructions = window.SignalShareAiCore?.getStoredCustomInstructions;
const customInstructions = typeof coreInstructions === "function"
? coreInstructions()
: `${localStorage.getItem("ss_ai_custom_instructions") || ""}`.trim().slice(0, 2000);
const provider = window.SignalShareLocalLlm?.getProviderPreference?.() || "auto";
const endpointBaseUrl = window.SignalShareLocalLlm?.getDirectEndpointBaseUrl?.(provider)
|| (provider === "openai-compatible" ? window.SignalShareLocalLlm?.getCustomEndpointBaseUrl?.() : "")
|| "";
const aiPayload = {
message: text,
model: requestModel,
provider,
endpointBaseUrl,
customInstructions,
attachment,
history: Array.isArray(history) ? history : [],
conversationId: `${conversationId || ""}`.trim(),
lmStudioMcpTools: typeof window.getSelectedLmStudioMcpTools === "function"
? window.getSelectedLmStudioMcpTools()
: [],
pageContext: pageContext || "Signal Share"
};
const tryBridgeAi = async (timeoutMs = 180000) => {
if (typeof window.bridgeFetch !== "function") {
lastError = "Bridge fetch unavailable";
return false;
}
const bridgePayload = JSON.stringify(aiPayload);
const candidateChatPaths = ["/api/local-llm/chat", "/api/llm/chat"];
for (const chatPath of candidateChatPaths) {
try {
const response = await window.bridgeFetch(chatPath, {
method: "POST",
signal: abortController.signal,
timeoutMs,
body: bridgePayload
});
if (response.ok) {
const data = await response.json().catch(() => null);
const nextReply = typeof data?.reply === "string" ? data.reply : "";
if (nextReply) {
reply = nextReply;
break;
}
lastError = "Bridge returned an invalid AI payload";
continue;
}
// Only continue to next path if we haven't tried the final path yet
if (response.status === 404 && chatPath !== candidateChatPaths[candidateChatPaths.length - 1]) {
continue;
}
lastError = `Bridge returned ${response.status}`;
// If auth fails on any path, stop trying other paths
if (response.status === 401 || response.status === 403) {
break;
}
} catch (error) {
if (stopRequested) {
return false;
}
const bridgeDisabled = error?.name === "BridgeDisabledError";
let nextError = bridgeDisabled
? "Bridge disabled"
: (error?.message || "Connection refused or blocked by browser");
if (!bridgeDisabled && /failed to fetch/i.test(`${nextError}`)) {
const configuredBridge = `${window.SignalShareLocalLlm?.getBridgeBaseUrl?.()
|| localStorage.getItem("signal-share-bridge-url")
|| ""}`.trim();
if (configuredBridge) {
const hint = configuredBridge.toLowerCase().startsWith("https://")
? " Use http:// for local bridge URLs."
: "";
nextError = `Failed to fetch bridge at ${configuredBridge}. Ensure phone and PC are on the same Wi-Fi and port 3000 is allowed.${hint}`;
} else {
nextError = "Failed to fetch bridge. Set Bridge URL (PC IP) in settings (example: http://192.168.x.x:3000).";
}
}
lastError = nextError;
if (!bridgeDisabled) {
console.warn(`[AI Messenger] Bridge request failed (${chatPath}):`, error);
}
}
if (reply !== null) break;
}
return reply !== null;
};
const bridgePreferred = typeof window.shouldPreferPcBridgeForAi === "function"
? await window.shouldPreferPcBridgeForAi({ signal: abortController.signal, timeoutMs: 2500 })
: window.isPcBridgeKnownOnline?.() === true;
if (bridgePreferred) await tryBridgeAi(180000);
if (reply === null && !stopRequested && typeof window.SignalShareLocalLlm?.chatDirect === "function") {
try {
const direct = await window.SignalShareLocalLlm.chatDirect({
...aiPayload,
endpointBaseUrl: undefined,
lmStudioMcpTools: []
}, {
signal: abortController?.signal,
timeoutMs: 180000
});
const directReply = `${direct?.reply || ""}`.trim();
if (directReply) {
reply = directReply;
window.updateEngineStatus?.(true, { source: "direct", reachable: true });
}
} catch (error) {
if (stopRequested || error?.name === "AbortError") {
return "๐ [Signal Protocol] AI request stopped.";
}
lastError = error?.message || "Direct endpoint request failed";
console.warn("[AI Messenger] Direct endpoint request failed:", error);
}
}
if (reply === null && !stopRequested && !bridgePreferred) {
await tryBridgeAi(10000);
}
if (stopRequested) {
return "๐ [Signal Protocol] AI request stopped.";
}
if (reply !== null) {
return reply || "...";
}
if (lastError && lastError !== "Bridge disabled") {
console.warn(`[AI Messenger] Local AI failed (${lastError}). Switching to Offline Protocol.`);
}
return getGlobalProtocolOfflineResponse(text);
}
function getGlobalProtocolOfflineResponse(text) {
const input = (text || "").toLowerCase();
const responses = [
{
keywords: ["pinball", "gravity"],
answer: "๐น๏ธ [Arcade Protocol]: In Neon Pinball, keep your eyes on the top bumpers. Hitting them in sequence triggers the 'Gravity Shift' multiplier, which can triple your score in seconds!"
},
{
keywords: ["basketball", "hoops", "shot"],
answer: "๐ [Arcade Protocol]: For Neon Hoops, consistency is key. Try to release the ball at the peak of your swipe for a 'Perfect' shot bonus. The net gets smaller as your streak increases!"
},
{
keywords: ["snake", "wrap", "trap"],
answer: "๐ [Arcade Protocol]: In Neon Snake, the board is edge-wrapped. If you're about to crash, move through the wall to appear on the other side. Use this to surprise high-value fruit!"
},
{
keywords: ["hello", "hi", "hey"],
answer: "๐ [Arcade Protocol]: Intelligence core is currently offline, but I am standing by for tactical support. Ask me about the games or how to improve your high score!"
},
{
keywords: ["help", "what can you do"],
answer: "๐ฎ [Arcade Protocol]: I am your tactical game assistant. Even in offline mode, I can provide tips for Pinball, Hoops, and Snake. Just ask about a specific game!"
},
{
keywords: ["thank", "thanks"],
answer: "๐น๏ธ [Arcade Protocol]: You're welcome, player. Now get back in there and break that record!"
}
];
for (const response of responses) {
if (response.keywords.some((keyword) => input.includes(keyword))) {
return response.answer;
}
}
const fallbacks = [
"๐ถ [Arcade Protocol]: No local AI endpoint is reachable. Start LM Studio or Ollama, then check the Endpoints tab.",
"๐ก [Arcade Protocol]: The selected model endpoint is unavailable or blocked by browser CORS. The PC Bridge is optional for normal chat.",
"๐น๏ธ [Arcade Protocol]: Sync failed, so I'm relying on cached arcade data. Check the provider URL and load a model.",
"๐ฎ [Arcade Protocol]: My logic processors are running local-only. (Bridge unreachable). I can still help with game tips though!"
];
return fallbacks[Math.floor(Math.random() * fallbacks.length)];
}