-
Notifications
You must be signed in to change notification settings - Fork 59
Expand file tree
/
Copy pathmain.js
More file actions
467 lines (409 loc) · 14.6 KB
/
Copy pathmain.js
File metadata and controls
467 lines (409 loc) · 14.6 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
(function () {
'use strict';
var utils = require('../modules/utils/utils.js');
var ContextMenu = require('../modules/background/ContextMenu.js');
var pageAction = require('../modules/background/pageAction.js');
var contextMenu = new ContextMenu({
title: 'Inspect UI5 control',
id: 'context-menu',
contexts: ['all']
});
/**
* This method will be fired when an instance is clicked. The idea is to be overwritten from the instance.
* @param {Object} info - Information sent when a context menu item is clicked. Check chrome.contextMenus.onClicked.
* @param {Object} tab - The details of the tab where the click took place.
*/
contextMenu.onClicked = function (info, tab) {
utils.sendToAll({
action: 'do-context-menu-control-select',
target: contextMenu._rightClickTarget,
// specify the frame in which the user clicked
frameId: info.frameId
});
};
// Name space for message handler functions.
var messageHandler = {
/**
* Create an icons with hover information inside the address bar.
* @param {Object} message
* @param {Object} messageSender
*/
'on-ui5-detected': function (message, messageSender) {
var framework = message.framework;
if (message.isVersionSupported === true) {
pageAction.create({
version: framework.version,
framework: framework.name,
tabId: messageSender.tab.id
});
pageAction.enable();
}
},
/**
* Handler for UI5 none detection on the current inspected page.
* @param {Object} message
*/
'on-ui5-not-detected': function (message) {
pageAction.disable();
},
/**
* Inject script into the inspected page.
* @param {Object} message
*/
'do-script-injection': function (message) {
const frameId = message.frameId;
chrome.windows.getCurrent().then(w => {
chrome.tabs.query({ active: true, windowId: w.id }).then(tabs => {
const target = {
tabId: tabs[0].id
};
// inject the script only into the frame
// specified in the request from the devTools UI5 panel script;
// If no frameId specified, the script will be injected into the main frame
if (frameId !== undefined) {
target.frameIds = [message.frameId];
}
chrome.scripting.executeScript({
target,
files: [message.file]
});
});
});
},
/**
* Set the element that was clicked with the right button of the mouse.
* @param {Object} message
*/
'on-right-click': function (message) {
contextMenu.setRightClickTarget(message.target);
},
/**
* Create the button for the context menu, when the user switches to the "UI5" panel.
* @param {Object} message
*/
'on-ui5-devtool-show': function (message) {
contextMenu.create();
},
/**
* Delete the button for the context menu, when the user switches away to the "UI5" panel.
* @param {Object} message
*/
'on-ui5-devtool-hide': function (message) {
contextMenu.removeAll();
},
'do-ping-frames': function (message, messageSender) {
var frameIds = message.frameIds;
var liveFrameIds = [];
var pingFrame = function (i) {
if (i >= frameIds.length) {
// no more frameId to ping
// => done with pinging each frame
// => send a message [to the devTools UI5 panel]
// with the updated list of 'live' frame ids
chrome.runtime.sendMessage(messageSender.id, {
action: 'on-ping-frames',
frameIds: liveFrameIds
});
return;
}
var frameId = frameIds[i];
// ping the next frame
// from the <code>frameIds</code> list
utils.sendToAll({
action: 'do-ping',
frameId: frameId
}, function (isAlive) {
if (isAlive) {
liveFrameIds.push(frameId);
}
pingFrame(i + 1);
});
};
pingFrame(0);
}
};
chrome.runtime.onMessage.addListener(function (request, messageSender, sendResponse) {
// Resolve incoming messages
utils.resolveMessage({
message: request,
messageSender: messageSender,
sendResponse: sendResponse,
actions: messageHandler
});
utils.sendToAll(request);
});
chrome.runtime.onInstalled.addListener(() => {
// Page actions are disabled by default and enabled on select tabs
chrome.action.disable();
});
// ================================================================================
// Prompt API Integration (Gemini Nano)
// ================================================================================
let promptAPISession = null;
let promptAPIController = null;
/**
* Check if Prompt API is supported
*/
function isPromptAPISupported() {
return 'LanguageModel' in self;
}
/**
* Initialize Prompt API session
*/
async function initPromptAPISession(options, signal) {
const availability = await self.LanguageModel.availability();
if (availability === 'unavailable') {
throw new Error('AI Model is not available on this device.');
}
const sessionOptions = {
signal
};
if (Array.isArray(options.initialPrompts) && options.initialPrompts.length > 0) {
sessionOptions.initialPrompts = options.initialPrompts;
}
// Add download progress monitoring if callback provided
if (options.onProgress) {
sessionOptions.monitor = function(m) {
m.addEventListener('downloadprogress', (e) => {
options.onProgress(e.loaded || 0);
});
};
}
return await self.LanguageModel.create(sessionOptions);
}
/**
* Handle check availability request
*/
async function handleCheckAvailability(port) {
if (!isPromptAPISupported()) {
port.postMessage({
type: 'availability',
status: 'unavailable',
message: 'Prompt API not supported - LanguageModel not found in self'
});
return;
}
try {
const availability = await self.LanguageModel.availability();
let status;
let message;
if (availability === 'available') {
status = 'ready';
message = 'Gemini Nano is ready to use';
} else if (availability === 'downloadable') {
status = 'needs-download';
message = 'Gemini Nano needs to be downloaded (~22GB)';
} else if (availability === 'downloading') {
status = 'downloading';
message = 'Gemini Nano is currently downloading';
} else if (availability === 'unavailable') {
status = 'unavailable';
message = 'Gemini Nano is not available on this device';
} else {
status = 'unavailable';
message = `Gemini Nano status unknown. Availability returned: "${availability}"`;
}
port.postMessage({
type: 'availability',
status: status,
message: message
});
} catch (error) {
console.error('[Background] Error checking availability:', error);
port.postMessage({
type: 'availability',
status: 'error',
message: `Error: ${error.message}`
});
}
}
/**
* Handle download model request
*/
async function handleDownloadModel(port) {
if (!isPromptAPISupported()) {
port.postMessage({
type: 'error',
message: 'Prompt API not supported'
});
return;
}
// Abort any existing operation
if (promptAPIController) {
promptAPIController.abort();
}
promptAPIController = new AbortController();
try {
promptAPISession = await initPromptAPISession({
onProgress: (progress) => {
port.postMessage({
type: 'download-progress',
progress: progress
});
}
}, promptAPIController.signal);
port.postMessage({
type: 'download-complete'
});
} catch (error) {
console.error('[Background] Error downloading model:', error);
port.postMessage({
type: 'error',
message: error.message
});
} finally {
promptAPIController = null;
}
}
/**
* Handle create session request
*/
async function handleCreateSession(data, port) {
if (!isPromptAPISupported()) {
port.postMessage({
type: 'error',
message: 'Prompt API not supported'
});
return;
}
try {
// Create the new session first; only swap out the old one on success.
// Otherwise a failure here would leave promptAPISession null and every
// subsequent prompt would return "No active session".
const newSession = await initPromptAPISession({
initialPrompts: data && data.initialPrompts
}, new AbortController().signal);
if (promptAPISession) {
promptAPISession.destroy();
}
promptAPISession = newSession;
port.postMessage({
type: 'session-created'
});
} catch (error) {
console.error('[Background] Error creating session:', error);
port.postMessage({
type: 'error',
message: error.message
});
}
}
/**
* Handle streaming prompt request
*/
async function handlePromptStreaming(data, port) {
if (!data || typeof data.userMessage !== 'string') {
port.postMessage({
type: 'error',
message: 'Invalid prompt: expected userMessage string'
});
return;
}
if (!promptAPISession) {
port.postMessage({
type: 'error',
message: 'No active session'
});
return;
}
// Abort any existing operation
if (promptAPIController) {
promptAPIController.abort();
}
promptAPIController = new AbortController();
try {
const stream = await promptAPISession.promptStreaming(
data.userMessage,
{ signal: promptAPIController.signal }
);
for await (const chunk of stream) {
if (promptAPIController.signal.aborted) {
break;
}
port.postMessage({
type: 'chunk',
content: chunk
});
}
if (!promptAPIController.signal.aborted) {
port.postMessage({
type: 'complete'
});
}
} catch (error) {
console.error('[Background] Error during streaming:', error);
port.postMessage({
type: 'error',
message: error.message
});
} finally {
promptAPIController = null;
}
}
/**
* Handle get usage info request
*/
function handleGetUsageInfo(port) {
if (!promptAPISession) {
port.postMessage({
type: 'usage-info',
data: null
});
return;
}
const inputUsage = promptAPISession.inputUsage || 0;
const inputQuota = promptAPISession.inputQuota || 4096;
const percentUsed = Math.round((inputUsage / inputQuota) * 100);
port.postMessage({
type: 'usage-info',
data: {
inputUsage: inputUsage,
inputQuota: inputQuota,
percentUsed: percentUsed
}
});
}
/**
* Handle destroy session request
*/
function handleDestroySession(port) {
if (promptAPISession) {
promptAPISession.destroy();
promptAPISession = null;
}
if (promptAPIController) {
promptAPIController.abort();
promptAPIController = null;
}
port.postMessage({
type: 'session-destroyed'
});
}
// Listen for long-lived connections for Prompt API
chrome.runtime.onConnect.addListener((port) => {
if (port.name === 'prompt-api') {
port.onMessage.addListener((message) => {
switch (message.type) {
case 'check-availability':
handleCheckAvailability(port);
break;
case 'download-model':
handleDownloadModel(port);
break;
case 'create-session':
handleCreateSession(message.data, port);
break;
case 'prompt-streaming':
handlePromptStreaming(message.data, port);
break;
case 'get-usage-info':
handleGetUsageInfo(port);
break;
case 'destroy-session':
handleDestroySession(port);
break;
}
});
}
});
}());