Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .jshintrc
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@
"Event": true,
"ace": true,
"self": true,
"AbortController": true
"AbortController": true,
"AbortSignal": true
}
}
2 changes: 1 addition & 1 deletion app/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
}
],
"content_security_policy": {
"extension_pages": "default-src 'self'; img-src 'self' data:; style-src 'unsafe-inline';"
"extension_pages": "default-src 'self'; connect-src 'self' http: https:; img-src 'self' data:; style-src 'unsafe-inline';"
},
"description": "With the UI5 Inspector, you can easily debug and support your OpenUI5 or SAPUI5-based apps.",
"devtools_page": "/html/devtools/index.html",
Expand Down
3 changes: 3 additions & 0 deletions app/scripts/background/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
var utils = require('../modules/utils/utils.js');
var ContextMenu = require('../modules/background/ContextMenu.js');
var pageAction = require('../modules/background/pageAction.js');
var attachOpenAIHandler = require('../modules/background/openaiHandler.js');

var contextMenu = new ContextMenu({
title: 'Inspect UI5 element',
Expand Down Expand Up @@ -501,6 +502,8 @@
break;
}
});
} else if (port.name === 'openai-api') {
attachOpenAIHandler(port);
}
});

Expand Down
10 changes: 7 additions & 3 deletions app/scripts/modules/ai/AssistantController.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ function AssistantController({
this._clearConsoleErrors = clearConsoleErrors;

this._capabilityState = { status: 'unavailable', message: 'Checking model status...', progress: 0 };
this._lastReadyMessage = 'Ready';
this._listeners = {};
this._currentUrl = null;
this._conversationMemory = [];
Expand Down Expand Up @@ -91,6 +92,9 @@ AssistantController.prototype._setCapabilityState = function (status, message, p
message: message || '',
progress: typeof progress === 'number' ? progress : 0
};
if (status === 'ready' && message) {
this._lastReadyMessage = message;
}
this._emit('capability-state-changed', this._capabilityState);
};

Expand Down Expand Up @@ -161,7 +165,7 @@ AssistantController.prototype.sendUserMessage = function (userMessage) {
this._conversationMemory.push({ role: 'assistant', content: fullText });
this._isStreaming = false;
if (this._capabilityState.status === 'streaming-failed') {
this._setCapabilityState('ready', 'Gemini Nano is ready', 0);
this._setCapabilityState('ready', this._lastReadyMessage, 0);
}
this._emit('stream-complete', { content: fullText });
return { content: fullText };
Expand Down Expand Up @@ -203,7 +207,7 @@ AssistantController.prototype.setUrl = function (url) {

return this._loadConversationMemory().then(() => {
this._provider.destroy();
this._setCapabilityState('ready', 'Gemini Nano is ready', 0);
this._setCapabilityState('ready', this._lastReadyMessage, 0);
});
};

Expand Down Expand Up @@ -237,7 +241,7 @@ AssistantController.prototype.clearConversation = function () {
this._provider.destroy();
this._emit('conversation-cleared');
if (this._capabilityState.status === 'ready') {
this._setCapabilityState('ready', 'Gemini Nano is ready', 0);
this._setCapabilityState('ready', this._lastReadyMessage, 0);
}
});
};
Expand Down
188 changes: 188 additions & 0 deletions app/scripts/modules/ai/OpenAIProvider.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,188 @@
'use strict';

/**
* AI Provider backed by any OpenAI-compatible HTTP endpoint. Wraps the background service worker's
* `openai-api` port protocol — the panel's CSP blocks cross-origin `fetch`, so all network I/O
* runs in the service worker (see modules/background/openaiHandler.js).
*
* @param {Object} config
* @param {string} config.baseUrl - e.g. `http://localhost:6655/openai/v1`. No trailing `/`.
* @param {string} config.apiKey - Bearer token. Never included in error messages or logs.
* @param {string} config.model - Model identifier passed to the API.
* @param {Function} [config.portFactory] - Test seam. Defaults to a `chrome.runtime.connect` call.
* @constructor
*/
function OpenAIProvider(config) {
const cfg = config || {};
this._baseUrl = cfg.baseUrl || '';
this._apiKey = cfg.apiKey || '';
this._model = cfg.model || '';
this._portFactory = cfg.portFactory || function () {
return chrome.runtime.connect({ name: 'openai-api' });
};
this._port = null;
this._isConnected = false;
this._messageHandlers = {};
this._disconnectHandler = null;
}

function abortError() {
const err = new Error('Aborted');
err.name = 'AbortError';
return err;
}

OpenAIProvider.prototype._connect = function () {
if (this._isConnected) {
return;
}

this._port = this._portFactory();
this._isConnected = true;

this._port.onMessage.addListener((message) => {
const handler = this._messageHandlers[message.type];
if (handler) {
handler(message);
}
});

this._port.onDisconnect.addListener(() => {
this._isConnected = false;
this._port = null;

if (this._disconnectHandler) {
const h = this._disconnectHandler;
this._disconnectHandler = null;
h();
}
});
};

/**
* Return `ready` iff `baseUrl`, `apiKey`, and `model` are all set. Local check — no port traffic.
* @returns {Promise<{status: string, message: string}>}
*/
OpenAIProvider.prototype.checkAvailability = function () {
if (this._baseUrl && this._apiKey && this._model) {
return Promise.resolve({ status: 'ready', message: 'OpenAI-compatible (' + this._model + ') ready' });
}
return Promise.resolve({ status: 'unavailable', message: 'not configured' });
};

/**
* Post the messages to the background over the `openai-api` port. Route incoming
* `chunk`/`complete`/`error` frames. Resolve with the accumulated text on `complete`.
*
* @param {Array<{role: string, content: string}>} messages
* @param {{onChunk?: Function, signal?: AbortSignal}} [options]
* @returns {Promise<string>}
*/
OpenAIProvider.prototype.sendMessage = function (messages, options) {
const opts = options || {};

if (!Array.isArray(messages) || messages.length === 0) {
return Promise.reject(new Error('sendMessage: messages must be a non-empty array'));
}
if (opts.signal && opts.signal.aborted) {
return Promise.reject(abortError());
}

return new Promise((resolve, reject) => {
let settled = false;
let fullText = '';
let abortListener = null;

const cleanup = () => {
delete this._messageHandlers.chunk;
delete this._messageHandlers.complete;
delete this._messageHandlers.error;
this._disconnectHandler = null;
if (opts.signal && abortListener) {
opts.signal.removeEventListener('abort', abortListener);
}
};

const settle = (fn) => {
if (settled) {
return;
}
settled = true;
cleanup();
fn();
};

this._messageHandlers.chunk = (message) => {
if (settled) {
return;
}
fullText += message.content;
if (typeof opts.onChunk === 'function') {
opts.onChunk(message.content);
}
};

this._messageHandlers.complete = () => {
settle(() => resolve(fullText));
};

this._messageHandlers.error = (message) => {
settle(() => reject(new Error(message.message)));
};

this._disconnectHandler = () => {
settle(() => reject(new Error('Connection to background script lost. Please try again.')));
};

if (opts.signal) {
abortListener = () => {
if (this._isConnected) {
this._port.postMessage({ type: 'cancel' });
}
settle(() => reject(abortError()));
};
opts.signal.addEventListener('abort', abortListener);
}

this._connect();
this._port.postMessage({
type: 'send',
config: {
baseUrl: this._baseUrl,
apiKey: this._apiKey,
model: this._model
},
messages: messages
});
});
};

/**
* OpenAI-compatible endpoints expose no client-visible token quota, so there is no usage to
* report. Returning `null` tells the UI to leave the token pill untouched (see AIChat).
* @returns {Promise<null>}
*/
OpenAIProvider.prototype.getUsageInfo = function () {
return Promise.resolve(null);
};

/**
* Cancel any in-flight request and disconnect the port.
*/
OpenAIProvider.prototype.destroy = function () {
if (this._disconnectHandler) {
const h = this._disconnectHandler;
this._disconnectHandler = null;
h();
}
if (this._isConnected && this._port) {
this._port.postMessage({ type: 'cancel' });
this._port.disconnect();
}
this._port = null;
this._isConnected = false;
this._messageHandlers = {};
this._disconnectHandler = null;
};

module.exports = OpenAIProvider;
10 changes: 10 additions & 0 deletions app/scripts/modules/ai/providers/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const GeminiNanoProvider = require('../GeminiNanoProvider.js');
const OpenAIProvider = require('../OpenAIProvider.js');

/**
* Static registry of AI providers available to the assistant. Keys are provider names persisted in
Expand All @@ -16,6 +17,15 @@ const PROVIDERS = {
displayName: 'Gemini Nano (on-device)',
ProviderClass: GeminiNanoProvider,
configSchema: []
},
'openai': {
displayName: 'OpenAI-compatible',
ProviderClass: OpenAIProvider,
configSchema: [
{ key: 'baseUrl', label: 'Base URL', type: 'text', required: true },
{ key: 'apiKey', label: 'API Key', type: 'password', required: true },
{ key: 'model', label: 'Model', type: 'text', required: true }
]
}
};

Expand Down
Loading