Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
refactor(ripple): move SDK client to renderer, add model picker, simp…
…lify IPC

Move session management and messaging from main process IPC to direct
SDK client usage in the renderer. The main process now only handles
server lifecycle (start with port:0 for random port, status, URL).

- Add ripple-client.ts with singleton SDK client, model listing, and
  message conversion utilities
- Add ModelPicker component for selecting from connected providers
- Rewrite browse mode sidebar (inner.tsx) to use SDK client directly
  with per-tab session tracking via React refs
- Rewrite work mode page (page.tsx) with SDK client, session list,
  and model picker in header
- Remove settings-panel.tsx (fs-access toggle was non-functional)
- Simplify FlowRippleAPI to 4 methods: initialize, getStatus,
  getServerUrl, toggleSidebar
  • Loading branch information
iamEvanYT committed Mar 4, 2026
commit bf8d38e764766861f1f04cf5c365e7ab487df244
44 changes: 4 additions & 40 deletions src/main/ipc/ripple.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,8 @@
import { ipcMain } from "electron";
import { rippleService } from "@/modules/ripple/service";
import { sendMessageToListeners } from "@/ipc/listeners-manager";
import type { RippleMode, RippleEvent } from "~/flow/interfaces/ripple/interface";

// Subscribe to Ripple events and forward them to renderer listeners.
rippleService.onEvent((event: RippleEvent) => {
sendMessageToListeners("ripple:event", event);
});

// Initialize the Ripple OpenCode server.
// Initialize the Ripple OpenCode server. Returns { url } or null.
ipcMain.handle("ripple:initialize", async () => {
return rippleService.initialize();
});
Expand All @@ -18,39 +12,9 @@ ipcMain.handle("ripple:get-status", () => {
return rippleService.getStatus();
});

// Create a new session.
ipcMain.handle("ripple:create-session", async (_event, mode: RippleMode, tabId?: number) => {
return rippleService.createSession(mode, tabId);
});

// Get or create a session for a specific tab.
ipcMain.handle("ripple:get-or-create-tab-session", async (_event, tabId: number) => {
return rippleService.getOrCreateTabSession(tabId);
});

// Send a prompt message.
ipcMain.handle("ripple:send-prompt", async (_event, sessionId: string, text: string) => {
return rippleService.sendPrompt(sessionId, text);
});

// Abort the current generation.
ipcMain.handle("ripple:abort", async (_event, sessionId: string) => {
return rippleService.abort(sessionId);
});

// List sessions.
ipcMain.handle("ripple:get-sessions", async (_event, mode?: RippleMode) => {
return rippleService.getSessions(mode);
});

// Get messages for a session.
ipcMain.handle("ripple:get-messages", async (_event, sessionId: string) => {
return rippleService.getMessages(sessionId);
});

// Toggle filesystem access.
ipcMain.handle("ripple:toggle-fs-access", async (_event, sessionId: string, enabled: boolean) => {
return rippleService.toggleFsAccess(sessionId, enabled);
// Get the server URL.
ipcMain.handle("ripple:get-server-url", () => {
return rippleService.getServerUrl();
});

// Toggle Ripple sidebar (send to browser UI).
Expand Down
257 changes: 26 additions & 231 deletions src/main/modules/ripple/service.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,18 @@
import { createOpencode, createOpencodeClient } from "@opencode-ai/sdk";
import { createOpencode } from "@opencode-ai/sdk";
import { startMcpBrowserServer, stopMcpBrowserServer } from "./mcp-browser-server";
import type {
RippleMode,
RippleStatus,
RippleSessionInfo,
RippleMessageInfo,
RippleEvent,
RippleMessagePart
} from "~/flow/interfaces/ripple/interface";
import type { RippleStatus } from "~/flow/interfaces/ripple/interface";

/**
* RippleService manages the OpenCode server lifecycle and provides
* session management for the Ripple AI agent.
* RippleService manages the OpenCode server lifecycle.
*
* It is lazily initialized on first activation and handles:
* - Starting/stopping the OpenCode server
* - Starting the MCP browser tools server
* - Creating and managing Browse/Work sessions
* - Forwarding events to the renderer
* Session management, messages, and model selection are handled
* directly by the SDK client in the renderer process.
*/
class RippleService {
private opencode: Awaited<ReturnType<typeof createOpencode>> | null = null;
private client: ReturnType<typeof createOpencodeClient> | null = null;
private status: RippleStatus = "stopped";
private statusError: string | undefined;
private eventListeners = new Set<(event: RippleEvent) => void>();

/** Map of tabId → sessionId for browse mode. */
private tabSessions = new Map<number, string>();

/** Map of sessionId → session metadata. */
private sessions = new Map<string, RippleSessionInfo>();

/** Set of sessions with filesystem access enabled. */
private fsAccessSessions = new Set<string>();
private serverUrl: string | null = null;

getStatus(): RippleStatus {
return this.status;
Expand All @@ -43,43 +22,27 @@ class RippleService {
return this.statusError;
}

private setStatus(status: RippleStatus, error?: string) {
this.status = status;
this.statusError = error;
this.emitEvent({ type: "status-changed", status, error });
}

/** Subscribe to Ripple events. Returns unsubscribe function. */
onEvent(listener: (event: RippleEvent) => void): () => void {
this.eventListeners.add(listener);
return () => {
this.eventListeners.delete(listener);
};
getServerUrl(): string | null {
return this.serverUrl;
}

private emitEvent(event: RippleEvent) {
for (const listener of this.eventListeners) {
try {
listener(event);
} catch (e) {
console.error("[Ripple] Event listener error:", e);
}
/** Initialize the OpenCode server and MCP browser tools. Returns the server URL. */
async initialize(): Promise<{ url: string } | null> {
if (this.status === "running" && this.serverUrl) {
return { url: this.serverUrl };
}
}
if (this.status === "starting") return null;

/** Initialize the OpenCode server and MCP browser tools. */
async initialize(): Promise<boolean> {
if (this.status === "running") return true;
if (this.status === "starting") return false;

this.setStatus("starting");
this.status = "starting";
this.statusError = undefined;

try {
// Start MCP browser tools server first
const mcpPort = await startMcpBrowserServer();

// Start OpenCode server with MCP config
// Start OpenCode server with port 0 (random) to avoid conflicts
this.opencode = await createOpencode({
port: 0,
config: {
mcp: {
"flow-browser": {
Expand All @@ -90,163 +53,17 @@ class RippleService {
}
});

this.client = this.opencode.client;
this.setStatus("running");
console.log("[Ripple] OpenCode server started successfully");
return true;
this.serverUrl = this.opencode.server.url;
this.status = "running";
console.log(`[Ripple] OpenCode server started at ${this.serverUrl}`);
return { url: this.serverUrl };
} catch (e) {
const errorMsg = e instanceof Error ? e.message : String(e);
console.error("[Ripple] Failed to initialize:", errorMsg);
this.setStatus("error", errorMsg);
return false;
}
}

/** Create a new session. */
async createSession(mode: RippleMode, tabId?: number): Promise<RippleSessionInfo> {
if (!this.client) throw new Error("Ripple not initialized");

const title = mode === "browse" ? `Browse Session${tabId ? ` (Tab ${tabId})` : ""}` : "Work Session";

const { data: session } = await this.client.session.create({
body: { title }
});

if (!session) throw new Error("Failed to create session");

const info: RippleSessionInfo = {
id: session.id,
title: session.title || title,
mode,
tabId,
createdAt: new Date().toISOString()
};

this.sessions.set(session.id, info);

if (mode === "browse" && tabId !== undefined) {
this.tabSessions.set(tabId, session.id);
}

this.emitEvent({ type: "session-updated", session: info });
return info;
}

/** Get or create a session for a specific tab. */
async getOrCreateTabSession(tabId: number): Promise<RippleSessionInfo> {
const existingSessionId = this.tabSessions.get(tabId);
if (existingSessionId) {
const existing = this.sessions.get(existingSessionId);
if (existing) return existing;
}

return this.createSession("browse", tabId);
}

/** Send a prompt and stream the response. */
async sendPrompt(sessionId: string, text: string): Promise<void> {
if (!this.client) throw new Error("Ripple not initialized");

try {
const result = await this.client.session.prompt({
path: { id: sessionId },
body: {
parts: [{ type: "text", text }]
}
});

// The SDK returns the complete response. Emit it as parts.
if (result.data) {
const msg = result.data;
const messageId = msg.info.id;

this.emitEvent({
type: "message-start",
sessionId,
messageId,
role: "assistant"
});

if (msg.parts) {
for (const part of msg.parts) {
this.emitEvent({
type: "message-part",
sessionId,
messageId,
part: convertPart(part)
});
}
}

this.emitEvent({
type: "message-complete",
sessionId,
messageId
});
}
} catch (e) {
console.error("[Ripple] Prompt error:", e);
throw e;
}
}

/** Abort the current generation. */
async abort(sessionId: string): Promise<boolean> {
if (!this.client) return false;

try {
const { data } = await this.client.session.abort({
path: { id: sessionId }
});
return !!data;
} catch {
return false;
}
}

/** List sessions, optionally filtered by mode. */
getSessions(mode?: RippleMode): RippleSessionInfo[] {
const all = Array.from(this.sessions.values());
if (mode) return all.filter((s) => s.mode === mode);
return all;
}

/** Get messages for a session. */
async getMessages(sessionId: string): Promise<RippleMessageInfo[]> {
if (!this.client) return [];

try {
const { data } = await this.client.session.messages({
path: { id: sessionId }
});

if (!data) return [];

return data.map((msg) => ({
id: msg.info.id,
sessionId,
role: msg.info.role as "user" | "assistant",
parts: (msg.parts || []).map(convertPart),
createdAt: msg.info.time?.created ? new Date(msg.info.time.created).toISOString() : new Date().toISOString()
}));
} catch {
return [];
}
}

/** Toggle filesystem access for a browse session. */
toggleFsAccess(sessionId: string, enabled: boolean): boolean {
if (enabled) {
this.fsAccessSessions.add(sessionId);
} else {
this.fsAccessSessions.delete(sessionId);
this.status = "error";
this.statusError = errorMsg;
return null;
}
return true;
}

/** Check if a session has filesystem access. */
hasFsAccess(sessionId: string): boolean {
return this.fsAccessSessions.has(sessionId);
}

/** Shutdown everything. */
Expand All @@ -259,32 +76,10 @@ class RippleService {
}
this.opencode = null;
}
this.client = null;
this.serverUrl = null;
await stopMcpBrowserServer();
this.setStatus("stopped");
}
}

/** Convert an SDK part to our RippleMessagePart type. */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function convertPart(part: any): RippleMessagePart {
if (part.type === "text") {
return { type: "text", text: part.text || "" };
}
if (part.type === "tool") {
return {
type: "tool-invocation",
toolName: part.tool || "unknown",
args: part.state?.input || {},
result: part.state?.output ? String(part.state.output) : undefined,
state: part.state?.status || "pending"
};
}
if (part.type === "step-start") {
return { type: "step-start", title: part.title };
this.status = "stopped";
}
// Fallback: treat as text
return { type: "text", text: JSON.stringify(part) };
}

/** Singleton instance. */
Expand Down
Loading