File size: 12,785 Bytes
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
'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 };