Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 | 1x 2x 2x 2x 1x 7x 7x 7x 7x 7x 7x 7x 7x 5x 4x 3x 3x 3x 3x 3x 5x 7x 7x 7x 2x 2x 7x 7x 1x 7x 7x 1x 7x 7x 7x 7x 7x 7x 7x 7x 2x 2x 2x 2x 2x 2x 2x 7x 7x 7x 7x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 2x 2x 2x 2x 3x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 3x 3x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x | import { ipcMain, type BrowserWindow } from "electron";
import type { SessionStore, SessionPatch } from "./session-store";
import type { SessionWatcher } from "./session-watcher";
import type { HookServer } from "./hook-server";
import type { AgentEvent, AgentState, SessionState } from "../shared/types";
import { logger } from "./logger";
import { installHook, readSettings, uninstallHook } from "./hook-installer";
import {
MAX_IDLE_BEFORE_GHOST_MINUTES,
MIN_IDLE_BEFORE_GHOST_MINUTES,
readUserSettings,
writeUserSettingsAtomic,
type UserSettings
} from "./user-settings";
/**
* Serializable projection of a `SessionState` for IPC transit. The live
* `SessionState.agents` is a `Map`, which `structuredClone` (used by Electron
* IPC under the hood) can serialize - but the renderer consumes plain arrays,
* so we flatten here to keep the contract explicit on both sides of the wire.
*/
type SerializedSession = Omit<SessionState, "agents"> & { agents: AgentState[] };
function serialize(session: SessionState): SerializedSession {
return { ...session, agents: Array.from(session.agents.values()) };
}
/**
* Wires the ingest sources (JSONL watcher + hook HTTP server) into the store,
* forwards store patches to the renderer, and registers the request/response
* IPC handlers the renderer calls.
*
* Contract with `SessionStore`:
* - `store.apply(event)` always emits a `patch`, even when no materialised
* change resulted (e.g. a duplicate or ignored event type).
* We filter empty-change patches here so `session:patch` is only sent when
* the renderer has something to apply - otherwise we burn a structuredClone
* + IPC round trip per ingested line for nothing.
*/
export function wireIpc(opts: {
window: BrowserWindow;
store: SessionStore;
watcher: SessionWatcher;
hookServer: HookServer;
/**
* Path to the persistent user-settings JSON file. Injected so tests can
* point to a tmp path and the main process can point to
* `{app userData}/user-settings.json`.
*/
userSettingsPath: string;
}): { dispose: () => void } {
const { window, store, watcher, hookServer, userSettingsPath } = opts;
logger.info("IPC bridge wiring");
const onWatcherEvent = (e: AgentEvent): void => store.apply(e);
const onHookEvent = (e: AgentEvent): void => store.apply(e);
watcher.on("event", onWatcherEvent);
hookServer.on("event", onHookEvent);
const onPatch = (patch: SessionPatch): void => {
if (patch.changes.length === 0) return;
if (window.isDestroyed()) return;
logger.debug("IPC bridge forwarding patch", {
sessionId: patch.sessionId,
changes: patch.changes.length
});
window.webContents.send("session:patch", patch);
};
store.on("patch", onPatch);
ipcMain.handle("sessions:list", () => store.listSessions().map(serialize));
ipcMain.handle("session:get", (_e, id: string) => {
const s = store.getSession(id);
return s ? serialize(s) : null;
});
ipcMain.handle("session:pin", (_e, id: string) => {
store.pin(id);
});
ipcMain.handle("session:unpin", (_e, id: string) => {
store.unpin(id);
});
// Hook installer IPC. Kept thin here - all the merge / write logic lives
// in `hook-installer.ts` so it stays unit-testable without Electron.
// Each handler catches and surfaces errors as `{ ok: false, error }` so the
// renderer can show a message instead of crashing on an unhandled IPC
// rejection.
ipcMain.handle("hooks:read", async () => {
try {
return { ok: true as const, ...(await readSettings()) };
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
logger.error("hooks:read failed", { message });
return { ok: false as const, error: message };
}
});
ipcMain.handle("hooks:install", async () => {
try {
const result = await installHook();
return { ok: true as const, ...result };
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
logger.error("hooks:install failed", { message });
return { ok: false as const, error: message };
}
});
ipcMain.handle("hooks:uninstall", async () => {
try {
const result = await uninstallHook();
return { ok: true as const, ...result };
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
logger.error("hooks:uninstall failed", { message });
return { ok: false as const, error: message };
}
});
// User-settings IPC. Currently just the ghost-retirement idle timer, but
// kept as a generic "settings:read / settings:write" pair so future knobs
// can extend the same surface without adding new channels.
ipcMain.handle("settings:read", async () => {
try {
const settings = await readUserSettings(userSettingsPath);
return {
ok: true as const,
idleBeforeGhostMinutes: settings.idleBeforeGhostMinutes
};
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
logger.error("settings:read failed", { message });
return { ok: false as const, error: message };
}
});
ipcMain.handle(
"settings:write",
async (_e, payload: { idleBeforeGhostMinutes?: unknown } | undefined) => {
try {
const raw = payload?.idleBeforeGhostMinutes;
// Validate in the main process regardless of renderer checks. An
// invalid value means "do not touch persisted state", which prevents
// a renderer bug from nuking the file.
if (
typeof raw !== "number" ||
!Number.isInteger(raw) ||
raw < MIN_IDLE_BEFORE_GHOST_MINUTES ||
raw > MAX_IDLE_BEFORE_GHOST_MINUTES
) {
return {
ok: false as const,
error: `idleBeforeGhostMinutes must be an integer between ${MIN_IDLE_BEFORE_GHOST_MINUTES} and ${MAX_IDLE_BEFORE_GHOST_MINUTES}.`
};
}
const previous = await readUserSettings(userSettingsPath);
const next: UserSettings = { idleBeforeGhostMinutes: raw };
const changed = previous.idleBeforeGhostMinutes !== next.idleBeforeGhostMinutes;
// Always call setIdleBeforeGhostMs so the live store matches the
// persisted state even on first-run after a crash.
store.setIdleBeforeGhostMs(raw * 60_000);
if (changed) {
await writeUserSettingsAtomic(userSettingsPath, next);
logger.info("settings:write persisted", {
userSettingsPath,
idleBeforeGhostMinutes: raw
});
}
return {
ok: true as const,
changed,
next: { idleBeforeGhostMinutes: next.idleBeforeGhostMinutes }
};
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
logger.error("settings:write failed", { message });
return { ok: false as const, error: message };
}
}
);
// Two-stage retirement runs inside `store.expireGhosts`:
// 1) idle -> ghost after 3 min of silence on an agent,
// 2) ghost -> removed after 1 h.
// Ticking every 30s keeps worst-case idle-to-ghost latency at ~30s, which
// matches the previous cadence and is well under the 1 h despawn window.
const ghostInterval = setInterval(() => store.expireGhosts(Date.now()), 30_000);
// Do not keep the Node event loop alive just for this timer. The window
// lifecycle owns shutdown.
ghostInterval.unref?.();
return {
dispose: () => {
logger.info("IPC bridge disposing");
clearInterval(ghostInterval);
watcher.off("event", onWatcherEvent);
hookServer.off("event", onHookEvent);
store.off("patch", onPatch);
ipcMain.removeHandler("sessions:list");
ipcMain.removeHandler("session:get");
ipcMain.removeHandler("session:pin");
ipcMain.removeHandler("session:unpin");
ipcMain.removeHandler("hooks:read");
ipcMain.removeHandler("hooks:install");
ipcMain.removeHandler("hooks:uninstall");
ipcMain.removeHandler("settings:read");
ipcMain.removeHandler("settings:write");
}
};
}
|