refactor(electrobun): simplify bun backend — extract db-utils, merge handlers

- db-utils.ts: shared openDb() (WAL, busy_timeout, foreign_keys, mkdirSync)
- 5 DB modules use openDb() instead of duplicated PRAGMA boilerplate
- bttask-db shares btmsg-db's Database handle (was duplicate connection)
- misc-handlers.ts: 14 inline handlers extracted from index.ts
- index.ts: 349→195 lines (only window controls remain inline)
- updater.ts: removed dead getLastKnownVersion()
- Net reduction: ~700 lines of duplicated boilerplate
This commit is contained in:
Hibryda 2026-03-23 21:09:57 +01:00
parent 2b1194c809
commit f2e8b07d7f
10 changed files with 291 additions and 239 deletions

View file

@ -5,23 +5,17 @@
* Fix #2: Path traversal guard on files.list/read/write via path-guard.ts.
*/
import fs from "fs";
import { BrowserWindow, BrowserView, Updater, Utils } from "electrobun/bun";
import { BrowserWindow, BrowserView, Updater } from "electrobun/bun";
import { PtyClient } from "./pty-client.ts";
import { settingsDb } from "./settings-db.ts";
import { sessionDb } from "./session-db.ts";
import { btmsgDb } from "./btmsg-db.ts";
import { bttaskDb } from "./bttask-db.ts";
import { createBttaskDb } from "./bttask-db.ts";
import { SidecarManager } from "./sidecar-manager.ts";
import type { PtyRPCSchema } from "../shared/pty-rpc-schema.ts";
import { Database } from "bun:sqlite";
import { randomUUID } from "crypto";
import { SearchDb } from "./search-db.ts";
import { checkForUpdates, getLastCheckTimestamp } from "./updater.ts";
import { RelayClient } from "./relay-client.ts";
import { initTelemetry, telemetry } from "./telemetry.ts";
import { homedir } from "os";
import { join } from "path";
// Handler modules
import { createPtyHandlers } from "./handlers/pty-handlers.ts";
@ -34,6 +28,7 @@ import { createPluginHandlers } from "./handlers/plugin-handlers.ts";
import { createRemoteHandlers } from "./handlers/remote-handlers.ts";
import { createGitHandlers } from "./handlers/git-handlers.ts";
import { createProviderHandlers } from "./handlers/provider-handlers.ts";
import { createMiscHandlers } from "./handlers/misc-handlers.ts";
/** Current app version — sourced from electrobun.config.ts at build time. */
const APP_VERSION = "0.0.1";
@ -47,6 +42,7 @@ const ptyClient = new PtyClient();
const sidecarManager = new SidecarManager();
const searchDb = new SearchDb();
const relayClient = new RelayClient();
const bttaskDb = createBttaskDb(btmsgDb.getHandle());
initTelemetry();
@ -70,27 +66,10 @@ async function connectToDaemon(retries = 5, delayMs = 500): Promise<boolean> {
return false;
}
// ── Clone helpers ──────────────────────────────────────────────────────────
const BRANCH_RE = /^[a-zA-Z0-9/_.-]+$/;
async function gitWorktreeAdd(mainRepoPath: string, worktreePath: string, branchName: string): Promise<{ ok: boolean; error?: string }> {
const proc = Bun.spawn(
["git", "worktree", "add", worktreePath, "-b", branchName],
{ cwd: mainRepoPath, stderr: "pipe", stdout: "pipe" }
);
const exitCode = await proc.exited;
if (exitCode !== 0) {
const errText = await new Response(proc.stderr).text();
return { ok: false, error: errText.trim() || `git exited with code ${exitCode}` };
}
return { ok: true };
}
// ── Build handler maps ───────────────────────────────────────────────────
// Placeholder rpc for agent handler — will be set after rpc creation
let rpcRef: { send: Record<string, (...args: unknown[]) => void> } = { send: {} };
const rpcRef: { send: Record<string, (...args: unknown[]) => void> } = { send: {} };
const ptyHandlers = createPtyHandlers(ptyClient);
const filesHandlers = createFilesHandlers();
@ -103,108 +82,33 @@ const pluginHandlers = createPluginHandlers();
const remoteHandlers = createRemoteHandlers(relayClient, settingsDb);
const gitHandlers = createGitHandlers();
const providerHandlers = createProviderHandlers();
const miscHandlers = createMiscHandlers({
settingsDb, ptyClient, relayClient, sidecarManager, telemetry, appVersion: APP_VERSION,
});
// Window ref — handlers use closure; set after mainWindow creation
let mainWindow: BrowserWindow;
// ── RPC definition ─────────────────────────────────────────────────────────
const rpc = BrowserView.defineRPC<PtyRPCSchema>({
maxRequestTime: 120_000, // 2 min — native dialogs block until user closes
maxRequestTime: 120_000,
handlers: {
requests: {
// PTY
...ptyHandlers,
// Files (with path traversal guard)
...filesHandlers,
// Settings + Groups + Themes
...settingsHandlers,
// Agents + Session persistence
...agentHandlers,
// btmsg + bttask
...btmsgHandlers,
...bttaskHandlers,
// Search
...searchHandlers,
// Plugins
...pluginHandlers,
// Remote
...remoteHandlers,
// Git
...gitHandlers,
// Providers
...providerHandlers,
...miscHandlers,
// Native folder picker dialog via zenity (proper GTK folder chooser)
"files.pickDirectory": async ({ startingFolder }) => {
try {
const { execSync } = await import("child_process");
const start = startingFolder?.replace(/^~/, process.env.HOME || "/home") || process.env.HOME || "/home";
const result = execSync(
`zenity --file-selection --directory --title="Select Project Folder" --filename="${start}/"`,
{ encoding: "utf-8", timeout: 120_000 }
).trim();
return { path: result || null };
} catch (e: any) {
// zenity exits with code 1 on cancel, code 5 if not found
// Do NOT fall back to Electrobun dialog — just return null
return { path: null };
}
},
// Home directory
"files.homeDir": async () => {
return { path: process.env.HOME || "/home" };
},
// Project templates (hardcoded list)
"project.templates": async () => ({
templates: [
{ id: "blank", name: "Blank Project", description: "Empty directory with no scaffolding", icon: "📁" },
{ id: "web-app", name: "Web App", description: "HTML/CSS/JS web application starter", icon: "🌐" },
{ id: "api-server", name: "API Server", description: "Node.js/Bun HTTP API server", icon: "⚡" },
{ id: "cli-tool", name: "CLI Tool", description: "Command-line tool with argument parser", icon: "🔧" },
],
}),
// ── Project clone handler ──────────────────────────────────────────
"project.clone": async ({ projectId, branchName }) => {
try {
if (!BRANCH_RE.test(branchName)) {
return { ok: false, error: "Invalid branch name. Use only letters, numbers, /, _, -, ." };
}
const source = settingsDb.getProject(projectId);
if (!source) return { ok: false, error: `Project not found: ${projectId}` };
const mainRepoPath = source.mainRepoPath ?? source.cwd;
const allProjects = settingsDb.listProjects();
const existingClones = allProjects.filter(
(p) => p.cloneOf === projectId || (source.cloneOf && p.cloneOf === source.cloneOf)
);
if (existingClones.length >= 3) return { ok: false, error: "Maximum 3 clones per project reached" };
const cloneIndex = existingClones.length + 1;
const wtSuffix = randomUUID().slice(0, 8);
const worktreePath = `${mainRepoPath}-wt-${wtSuffix}`;
const gitResult = await gitWorktreeAdd(mainRepoPath, worktreePath, branchName);
if (!gitResult.ok) return { ok: false, error: gitResult.error };
const cloneId = `${projectId}-clone-${cloneIndex}-${randomUUID().slice(0, 8)}`;
const cloneConfig = {
id: cloneId, name: `${source.name} [${branchName}]`,
cwd: worktreePath, accent: source.accent, provider: source.provider,
profile: source.profile, model: source.model,
groupId: source.groupId ?? "dev", mainRepoPath,
cloneOf: projectId, worktreePath, worktreeBranch: branchName, cloneIndex,
};
settingsDb.setProject(cloneId, cloneConfig);
return { ok: true, project: { id: cloneId, config: JSON.stringify(cloneConfig) } };
} catch (err) {
const error = err instanceof Error ? err.message : String(err);
console.error("[project.clone]", err);
return { ok: false, error };
}
},
// ── Window controls ────────────────────────────────────────────────
// Window controls — need mainWindow closure, stay inline
"window.minimize": () => { try { mainWindow.minimize(); return { ok: true }; } catch (err) { console.error("[window.minimize]", err); return { ok: false }; } },
"window.maximize": () => {
try {
@ -216,64 +120,6 @@ const rpc = BrowserView.defineRPC<PtyRPCSchema>({
"window.close": () => { try { mainWindow.close(); return { ok: true }; } catch (err) { console.error("[window.close]", err); return { ok: false }; } },
"window.getFrame": () => { try { return mainWindow.getFrame(); } catch { return { x: 0, y: 0, width: 1400, height: 900 }; } },
"window.setPosition": ({ x, y }: { x: number; y: number }) => { try { mainWindow.setPosition(x, y); return { ok: true }; } catch { return { ok: false }; } },
// ── Keybindings ────────────────────────────────────────────────────
"keybindings.getAll": () => { try { return { keybindings: settingsDb.getKeybindings() }; } catch (err) { console.error("[keybindings.getAll]", err); return { keybindings: {} }; } },
"keybindings.set": ({ id, chord }) => { try { settingsDb.setKeybinding(id, chord); return { ok: true }; } catch (err) { console.error("[keybindings.set]", err); return { ok: false }; } },
"keybindings.reset": ({ id }) => { try { settingsDb.deleteKeybinding(id); return { ok: true }; } catch (err) { console.error("[keybindings.reset]", err); return { ok: false }; } },
// ── Updater ────────────────────────────────────────────────────────
"updater.check": async () => {
try { const result = await checkForUpdates(APP_VERSION); return { ...result, error: undefined }; }
catch (err) { const error = err instanceof Error ? err.message : String(err); console.error("[updater.check]", err); return { available: false, version: "", downloadUrl: "", releaseNotes: "", checkedAt: Date.now(), error }; }
},
"updater.getVersion": () => ({ version: APP_VERSION, lastCheck: getLastCheckTimestamp() }),
// ── Memora (read-only) ────────────────────────────────────────────
"memora.search": ({ query, limit }) => {
try {
const dbPath = join(homedir(), ".local", "share", "memora", "memories.db");
if (!fs.existsSync(dbPath)) return { memories: [] };
const db = new Database(dbPath, { readonly: true });
try {
const rows = db.query("SELECT id, content, tags, metadata, created_at as createdAt, updated_at as updatedAt FROM memories WHERE content LIKE ? ORDER BY updated_at DESC LIMIT ?").all(`%${query}%`, limit ?? 20);
return { memories: rows as Array<{ id: number; content: string; tags: string; metadata: string; createdAt: string; updatedAt: string }> };
} finally { db.close(); }
} catch (err) { console.error("[memora.search]", err); return { memories: [] }; }
},
"memora.list": ({ limit, tag }) => {
try {
const dbPath = join(homedir(), ".local", "share", "memora", "memories.db");
if (!fs.existsSync(dbPath)) return { memories: [] };
const db = new Database(dbPath, { readonly: true });
try {
let sql = "SELECT id, content, tags, metadata, created_at as createdAt, updated_at as updatedAt FROM memories";
const params: unknown[] = [];
if (tag) { sql += " WHERE tags LIKE ?"; params.push(`%${tag}%`); }
sql += " ORDER BY updated_at DESC LIMIT ?";
params.push(limit ?? 20);
const rows = db.query(sql).all(...params);
return { memories: rows as Array<{ id: number; content: string; tags: string; metadata: string; createdAt: string; updatedAt: string }> };
} finally { db.close(); }
} catch (err) { console.error("[memora.list]", err); return { memories: [] }; }
},
// ── Feature 8: Diagnostics ─────────────────────────────────────────
"diagnostics.stats": () => {
return {
ptyConnected: ptyClient.isConnected,
relayConnections: relayClient.listMachines().filter(m => m.status === "connected").length,
activeSidecars: sidecarManager.listSessions().filter(s => s.status === "running").length,
rpcCallCount: 0, // Placeholder — Electrobun doesn't expose RPC call count
droppedEvents: 0,
};
},
// ── Telemetry ─────────────────────────────────────────────────────
"telemetry.log": ({ level, message, attributes }) => {
try { telemetry.log(level, `[frontend] ${message}`, attributes ?? {}); return { ok: true }; }
catch (err) { console.error("[telemetry.log]", err); return { ok: false }; }
},
},
messages: {},
},
@ -333,7 +179,7 @@ const savedY = Number(settingsDb.getSetting("win_y") ?? 100);
const savedWidth = Number(settingsDb.getSetting("win_width") ?? 1400);
const savedHeight = Number(settingsDb.getSetting("win_height") ?? 900);
const mainWindow = new BrowserWindow({
mainWindow = new BrowserWindow({
title: "Agent Orchestrator",
titleBarStyle: "default",
url,