EnergyVenom's picture
Patchwise Agent Studio: Oracle AI Agent Studio cycles
af1bee9 verified
Raw History Blame Contribute Delete
12.8 kB
'use strict';
// Patchwise desktop shell (Electron). Loads the SAME built web app the backend serves; no second UI codebase.
// local mode : spawns the project's venv Python -> FastAPI on a free 127.0.0.1 port, waits for /api/ready, kills it on quit
// remote mode: loads a shared backend URL entered in Settings
// Security: contextIsolation on, nodeIntegration off, sandboxed renderer, minimal preload bridge, CSP, external links in
// the default browser, navigation pinned to the backend origin. Mock app only, never Oracle Fusion.
const { app, BrowserWindow, Menu, Notification, Tray, dialog, ipcMain, nativeImage, session, shell } = require('electron');
const { spawn, execFileSync } = require('node:child_process');
const fs = require('node:fs');
const http = require('node:http');
const https = require('node:https');
const net = require('node:net');
const path = require('node:path');
const { pathToFileURL } = require('node:url');
if (process.env.FPT_DESKTOP_USERDATA) app.setPath('userData', process.env.FPT_DESKTOP_USERDATA);
const CONFIG_FILE = () => path.join(app.getPath('userData'), 'config.json');
const DEV_ROOT = path.resolve(__dirname, '..', '..');
const SETTINGS_CSP = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self'; connect-src 'none'; form-action 'none'";
const FALLBACK_CSP = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; frame-src 'self'; object-src 'none'";
let win = null;
let settingsWin = null;
let tray = null;
let backend = null;
let backendPort = null;
let quitting = false;
let currentOrigin = null;
// ------------------------------------------------------------------ config
const VENV_PY = (root) => [path.join(root, 'architecture', '.venv', 'Scripts', 'python.exe'), path.join(root, 'architecture', '.venv', 'bin', 'python')];
/** The FPT checkout layout we are willing to spawn Python from: coworker package + the project's own venv. */
function isProjectRoot(p) {
return !!p && path.isAbsolute(p) && fs.existsSync(path.join(p, 'coworker', '__main__.py')) && fs.existsSync(path.join(p, 'coworker', 'api', 'app.py'))
&& VENV_PY(p).some((x) => fs.existsSync(x));
}
const isLoopback = (h) => ['localhost', '127.0.0.1', '::1', '[::1]'].includes(h) || /^127\./.test(h);
function loadConfig() {
let cfg = {};
try { cfg = JSON.parse(fs.readFileSync(CONFIG_FILE(), 'utf8')); } catch { /* first run */ }
const out = {
mode: cfg.mode === 'remote' ? 'remote' : 'local',
serverUrl: typeof cfg.serverUrl === 'string' ? cfg.serverUrl : '',
projectRoot: typeof cfg.projectRoot === 'string' && cfg.projectRoot ? cfg.projectRoot : (isProjectRoot(DEV_ROOT) ? DEV_ROOT : ''),
autoStart: !!cfg.autoStart,
};
if (process.env.FPT_DESKTOP_MODE) out.mode = process.env.FPT_DESKTOP_MODE === 'remote' ? 'remote' : 'local';
if (process.env.FPT_PROJECT_ROOT) out.projectRoot = process.env.FPT_PROJECT_ROOT;
if (process.env.FPT_SERVER_URL) out.serverUrl = process.env.FPT_SERVER_URL;
return out;
}
function validateConfig(c) {
const errs = [];
if (!['local', 'remote'].includes(c.mode)) errs.push('mode must be local or remote');
if (c.mode === 'remote') {
try {
const u = new URL(c.serverUrl);
if (u.protocol !== 'https:' && !(u.protocol === 'http:' && isLoopback(u.hostname))) errs.push('server URL must be https (http only for a loopback address)');
} catch { errs.push('server URL is not a valid URL'); }
}
if (c.mode === 'local' && !isProjectRoot(c.projectRoot)) errs.push('project folder must be the FPT checkout (coworker/ and architecture/.venv)');
return errs;
}
function saveConfig(c) {
fs.mkdirSync(path.dirname(CONFIG_FILE()), { recursive: true });
fs.writeFileSync(CONFIG_FILE(), JSON.stringify(c, null, 2));
try { app.setLoginItemSettings({ openAtLogin: !!c.autoStart }); } catch { /* not supported in all environments */ }
}
// ------------------------------------------------------------------ backend (local mode)
function freePort() {
return new Promise((resolve, reject) => {
const s = net.createServer();
s.unref();
s.on('error', reject);
s.listen(0, '127.0.0.1', () => { const { port } = s.address(); s.close(() => resolve(port)); });
});
}
function getJson(url, timeoutMs = 2000) {
const mod = url.startsWith('https:') ? https : http;
return new Promise((resolve) => {
const req = mod.get(url, { timeout: timeoutMs }, (res) => {
let body = '';
res.on('data', (d) => { body += d; });
res.on('end', () => { try { resolve({ status: res.statusCode, body: JSON.parse(body) }); } catch { resolve({ status: res.statusCode, body: null }); } });
});
req.on('error', () => resolve({ status: 0, body: null }));
req.on('timeout', () => { req.destroy(); resolve({ status: 0, body: null }); });
});
}
async function waitReady(base, timeoutMs = 120000) {
const end = Date.now() + timeoutMs;
while (Date.now() < end) {
const r = await getJson(`${base}/api/ready`);
if (r.status === 200 && r.body && r.body.ready) return r.body;
if (backend && backend.exitCode !== null) throw new Error(`backend exited with code ${backend.exitCode}; see ${path.join(app.getPath('userData'), 'backend.log')}`);
await new Promise((res) => setTimeout(res, 500));
}
throw new Error(`backend not ready after ${timeoutMs / 1000}s`);
}
function pythonFor(root) {
const py = VENV_PY(root).find((p) => fs.existsSync(p));
if (!isProjectRoot(root) || !py) throw new Error(`not an FPT checkout with a venv: ${root}`);
return py;
}
async function startBackend(cfg) {
backendPort = await freePort();
const log = fs.openSync(path.join(app.getPath('userData'), 'backend.log'), 'a');
backend = spawn(pythonFor(cfg.projectRoot), ['-m', 'coworker', 'api', '--host', '127.0.0.1', '--port', String(backendPort)], {
// local mode has no separate worker process: the backend hosts the Temporal worker in-process (or falls back to LangGraph)
cwd: cfg.projectRoot, env: { ...process.env, PYTHONUNBUFFERED: '1', FPT_EMBEDDED_WORKER: process.env.FPT_EMBEDDED_WORKER || '1' }, stdio: ['ignore', log, log], windowsHide: true,
});
const base = `http://127.0.0.1:${backendPort}`;
await waitReady(base);
return base;
}
function stopBackend() {
if (!backend || backend.exitCode !== null) return;
try {
if (process.platform === 'win32') execFileSync('taskkill', ['/PID', String(backend.pid), '/T', '/F'], { stdio: 'ignore' });
else process.kill(-backend.pid, 'SIGTERM');
} catch { try { backend.kill(); } catch { /* already gone */ } }
backend = null;
}
// ------------------------------------------------------------------ windows
function secureWebContents(wc) {
wc.setWindowOpenHandler(({ url }) => {
if (/^https?:\/\//i.test(url)) void shell.openExternal(url);
return { action: 'deny' };
});
wc.on('will-navigate', (e, url) => {
let origin = null;
try { origin = new URL(url).origin; } catch { /* invalid */ }
if (!currentOrigin || origin !== currentOrigin) { // no file:// exception: navigation stays on the backend origin
e.preventDefault();
if (/^https?:\/\//i.test(url)) void shell.openExternal(url);
}
});
}
const WEB_PREFS = { preload: path.join(__dirname, 'preload.js'), contextIsolation: true, nodeIntegration: false, sandbox: true, webSecurity: true, spellcheck: false };
function createMainWindow() {
win = new BrowserWindow({ width: 1360, height: 900, minWidth: 380, title: 'Patchwise (mock app, not Oracle Fusion)', show: false,
icon: path.join(__dirname, '..', 'build', 'icon.png'), webPreferences: WEB_PREFS });
secureWebContents(win.webContents);
win.once('ready-to-show', () => win.show());
win.on('close', (e) => { if (!quitting && tray) { e.preventDefault(); win.hide(); } });
return win;
}
function openSettings(message) {
if (settingsWin) { settingsWin.focus(); return; }
settingsWin = new BrowserWindow({ width: 560, height: 560, title: 'Patchwise settings', parent: win || undefined, webPreferences: WEB_PREFS });
secureWebContents(settingsWin.webContents);
settingsWin.loadFile(path.join(__dirname, 'settings.html'), { query: message ? { message } : {} });
settingsWin.on('closed', () => { settingsWin = null; });
}
async function connect() {
const cfg = loadConfig();
const errs = validateConfig(cfg);
if (errs.length) { openSettings(errs.join('; ')); return; }
if (!win) createMainWindow();
await win.loadFile(path.join(__dirname, 'loading.html'));
try {
stopBackend();
let base;
if (cfg.mode === 'local') base = await startBackend(cfg);
else {
base = new URL(cfg.serverUrl).origin;
const r = await getJson(`${base}/api/ready`, 5000);
if (r.status !== 200) throw new Error(`server ${base} is not ready (HTTP ${r.status || 'unreachable'})`);
}
currentOrigin = new URL(base).origin;
await win.loadURL(`${base}/`);
buildTray();
} catch (e) {
dialog.showErrorBox('Patchwise', String(e && e.message ? e.message : e));
openSettings(String(e && e.message ? e.message : e));
}
}
function buildTray() {
if (!tray) {
tray = new Tray(nativeImage.createFromPath(path.join(__dirname, 'tray.png')));
tray.setToolTip('Patchwise (mock app, not Oracle Fusion)');
tray.on('click', () => { if (win) { win.show(); win.focus(); } });
}
const cfg = loadConfig();
tray.setContextMenu(Menu.buildFromTemplate([
{ label: 'Open', click: () => { if (win) { win.show(); win.focus(); } } },
{ label: `Mode: ${cfg.mode}${cfg.mode === 'local' && backendPort ? ` (port ${backendPort})` : ''}`, enabled: false },
{ label: 'Settings', click: () => openSettings() },
{ label: 'Reconnect / restart backend', click: () => void connect() },
{ type: 'separator' },
{ label: 'Quit', click: () => { quitting = true; app.quit(); } },
]));
}
// ------------------------------------------------------------------ IPC (validated)
const fromApp = (e) => { try { return new URL(e.senderFrame.url).origin === currentOrigin; } catch { return false; } };
const SETTINGS_URL = pathToFileURL(path.join(__dirname, 'settings.html')).href;
const fromSettings = (e) => {
try {
const u = new URL(e.senderFrame.url);
u.search = '';
u.hash = '';
return u.href === SETTINGS_URL; // exactly our settings page (the ?message= query is ignored)
} catch { return false; }
};
ipcMain.on('fpt:notify', (e, msg) => {
if (!fromApp(e) || !msg || typeof msg.title !== 'string' || typeof msg.body !== 'string') return;
if (Notification.isSupported()) new Notification({ title: msg.title.slice(0, 80), body: msg.body.slice(0, 240) }).show();
});
ipcMain.on('fpt:open-settings', (e) => { if (fromApp(e)) openSettings(); });
ipcMain.handle('fpt:get-config', (e) => (fromSettings(e) ? loadConfig() : null));
ipcMain.handle('fpt:save-config', (e, c) => {
if (!fromSettings(e) || !c || typeof c !== 'object') return { ok: false, errors: ['not allowed'] };
const cfg = { mode: c.mode === 'remote' ? 'remote' : 'local', serverUrl: String(c.serverUrl || '').trim(), projectRoot: String(c.projectRoot || '').trim(), autoStart: !!c.autoStart };
const errors = validateConfig(cfg);
if (errors.length) return { ok: false, errors };
saveConfig(cfg);
if (settingsWin) settingsWin.close();
void connect();
return { ok: true, errors: [] };
});
// ------------------------------------------------------------------ app lifecycle
if (!app.requestSingleInstanceLock()) {
app.quit();
} else {
app.on('second-instance', () => { if (win) { if (win.isMinimized()) win.restore(); win.show(); win.focus(); } });
app.whenReady().then(() => {
app.setAppUserModelId('local.fpt.coworker');
Menu.setApplicationMenu(null);
session.defaultSession.setPermissionRequestHandler((_wc, _perm, cb) => cb(false));
session.defaultSession.webRequest.onHeadersReceived((details, cb) => {
const h = details.responseHeaders || {};
const has = Object.keys(h).some((k) => k.toLowerCase() === 'content-security-policy');
if (!has && details.resourceType === 'mainFrame' && details.url.startsWith('http')) h['Content-Security-Policy'] = [FALLBACK_CSP];
cb({ responseHeaders: h });
});
void connect();
});
app.on('before-quit', () => { quitting = true; stopBackend(); });
app.on('window-all-closed', () => { if (process.platform !== 'darwin') app.quit(); });
process.on('exit', stopBackend);
}
module.exports = { SETTINGS_CSP };