Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 6 additions & 0 deletions packages/react-grab/src/core/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2590,3 +2590,9 @@ export type {

export { generateSnippet } from "../utils/generate-snippet.js";
export { copyContent } from "../utils/copy-content.js";
export {
setGlobalIDEInfo,
getGlobalIDEInfo,
buildOpenFileUrl,
} from "../utils/build-open-file-url.js";
export type { EditorId, IDEInfo } from "../utils/build-open-file-url.js";
6 changes: 6 additions & 0 deletions packages/react-grab/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ export {
} from "./utils/capture-screenshot.js";
export type { ElementBounds } from "./utils/capture-screenshot.js";
export { isScreenshotSupported } from "./utils/is-screenshot-supported.js";
export {
setGlobalIDEInfo,
getGlobalIDEInfo,
buildOpenFileUrl,
} from "./utils/build-open-file-url.js";
export type { EditorId, IDEInfo } from "./utils/build-open-file-url.js";
export type {
Options,
ReactGrabAPI,
Expand Down
71 changes: 71 additions & 0 deletions packages/react-grab/src/utils/build-open-file-url.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,83 @@
export type EditorId =
| "cursor"
| "vscode"
| "antigravity"
| "zed"
| "webstorm"
| null;

export interface IDEInfo {
editorId: EditorId;
editorName: string | null;
urlScheme: string | null;
}

const BASE_URL =
process.env.NODE_ENV === "production"
? "https://react-grab.com"
: "http://localhost:3000";

// Encode file path for custom URI schemes while preserving path delimiters
const encodePathForCustomScheme = (filePath: string): string => {
// Ensure path starts with /
const normalizedPath = filePath.startsWith("/") ? filePath : `/${filePath}`;
// Split by "/" to preserve path structure, then encode each segment
return normalizedPath
.split("/")
.map((segment) => encodeURIComponent(segment))
.join("/");
};

// Build editor-specific URL scheme
const buildEditorUrl = (
editorId: EditorId,
filePath: string,
lineNumber?: number,
): string | null => {
if (!editorId) return null;

if (editorId === "webstorm") {
const lineParam = lineNumber ? `&line=${lineNumber}` : "";
return `webstorm://open?file=${encodeURIComponent(filePath)}${lineParam}`;
}

const encodedPath = encodePathForCustomScheme(filePath);
const lineParam = lineNumber ? `:${lineNumber}` : "";
return `${editorId}://file${encodedPath}${lineParam}`;
};

// Global IDE info storage - set by relay client or manually
let globalIDEInfo: IDEInfo | null = null;

export const setGlobalIDEInfo = (ideInfo: IDEInfo | null): void => {
globalIDEInfo = ideInfo;
};

export const getGlobalIDEInfo = (): IDEInfo | null => {
return globalIDEInfo;
};

export const buildOpenFileUrl = (
filePath: string,
lineNumber?: number,
ideInfo?: IDEInfo | null,
): string => {
// Use provided IDE info, or fall back to global IDE info
const effectiveIDEInfo = ideInfo ?? globalIDEInfo;

// If IDE is detected, try to generate direct URL scheme
if (effectiveIDEInfo?.editorId) {
const directUrl = buildEditorUrl(
effectiveIDEInfo.editorId,
filePath,
lineNumber,
);
if (directUrl) {
return directUrl;
}
}

// Fall back to open-file page for manual IDE selection
const lineParam = lineNumber ? `&line=${lineNumber}` : "";
return `${BASE_URL}/open-file?url=${encodeURIComponent(filePath)}${lineParam}`;
};
53 changes: 49 additions & 4 deletions packages/relay/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type {
AgentContext,
BrowserToRelayMessage,
RelayToBrowserMessage,
IDEInfo,
} from "./protocol.js";
import {
DEFAULT_RELAY_PORT,
Expand All @@ -20,7 +21,9 @@ export interface RelayClient {
onMessage: (callback: (message: RelayToBrowserMessage) => void) => () => void;
onHandlersChange: (callback: (handlers: string[]) => void) => () => void;
onConnectionChange: (callback: (connected: boolean) => void) => () => void;
onIDEInfoChange: (callback: (ideInfo: IDEInfo | null) => void) => () => void;
getAvailableHandlers: () => string[];
getIDEInfo: () => IDEInfo | null;
}

interface RelayClientOptions {
Expand All @@ -42,6 +45,7 @@ export const createRelayClient = (
let webSocketConnection: WebSocket | null = null;
let isConnectedState = false;
let availableHandlers: string[] = [];
let currentIDEInfo: IDEInfo | null = null;
let reconnectTimeoutId: ReturnType<typeof setTimeout> | null = null;
let pendingConnectionPromise: Promise<void> | null = null;
let pendingConnectionReject: ((error: Error) => void) | null = null;
Expand All @@ -50,6 +54,7 @@ export const createRelayClient = (
const messageCallbacks = new Set<(message: RelayToBrowserMessage) => void>();
const handlersChangeCallbacks = new Set<(handlers: string[]) => void>();
const connectionChangeCallbacks = new Set<(connected: boolean) => void>();
const ideInfoChangeCallbacks = new Set<(ideInfo: IDEInfo | null) => void>();

const scheduleReconnect = () => {
if (!autoReconnect || reconnectTimeoutId || isIntentionalDisconnect) return;
Expand All @@ -64,10 +69,27 @@ export const createRelayClient = (
try {
const message = JSON.parse(event.data as string) as RelayToBrowserMessage;

if (message.type === "handlers" && message.handlers) {
availableHandlers = message.handlers;
for (const callback of handlersChangeCallbacks) {
callback(availableHandlers);
if (message.type === "handlers") {
if (message.handlers) {
availableHandlers = message.handlers;
for (const callback of handlersChangeCallbacks) {
callback(availableHandlers);
}
}

// Handle IDE info update
const newIDEInfo = message.ideInfo ?? null;
const ideChanged =
(newIDEInfo === null) !== (currentIDEInfo === null) ||
(newIDEInfo !== null &&
(newIDEInfo.editorId !== currentIDEInfo?.editorId ||
newIDEInfo.editorName !== currentIDEInfo?.editorName ||
newIDEInfo.urlScheme !== currentIDEInfo?.urlScheme));
if (ideChanged) {
currentIDEInfo = newIDEInfo;
for (const callback of ideInfoChangeCallbacks) {
callback(currentIDEInfo);
}
}
}

Expand Down Expand Up @@ -115,9 +137,13 @@ export const createRelayClient = (
pendingConnectionPromise = null;
isConnectedState = false;
availableHandlers = [];
currentIDEInfo = null;
for (const callback of handlersChangeCallbacks) {
callback(availableHandlers);
}
for (const callback of ideInfoChangeCallbacks) {
callback(currentIDEInfo);
}
for (const callback of connectionChangeCallbacks) {
callback(false);
}
Expand Down Expand Up @@ -146,10 +172,13 @@ export const createRelayClient = (
pendingConnectionReject = null;
}
pendingConnectionPromise = null;
// Note: webSocketConnection.close() triggers onclose handler
// which handles state reset and callback notifications
webSocketConnection?.close();
webSocketConnection = null;
isConnectedState = false;
availableHandlers = [];
currentIDEInfo = null;
};

const isConnected = () => isConnectedState;
Expand Down Expand Up @@ -221,8 +250,22 @@ export const createRelayClient = (
return () => connectionChangeCallbacks.delete(callback);
};

const onIDEInfoChange = (
callback: (ideInfo: IDEInfo | null) => void,
): (() => void) => {
ideInfoChangeCallbacks.add(callback);
queueMicrotask(() => {
if (ideInfoChangeCallbacks.has(callback)) {
callback(currentIDEInfo);
}
});
return () => ideInfoChangeCallbacks.delete(callback);
};

const getAvailableHandlers = () => availableHandlers;

const getIDEInfo = () => currentIDEInfo;

return {
connect,
disconnect,
Expand All @@ -234,7 +277,9 @@ export const createRelayClient = (
onMessage,
onHandlersChange,
onConnectionChange,
onIDEInfoChange,
getAvailableHandlers,
getIDEInfo,
};
};

Expand Down
21 changes: 15 additions & 6 deletions packages/relay/src/connection.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
import pc from "picocolors";
import fkill from "fkill";
import type { AgentHandler } from "./protocol.js";
import type { AgentHandler, IDEInfo } from "./protocol.js";
import { DEFAULT_RELAY_PORT, HEALTH_CHECK_TIMEOUT_MS, POST_KILL_DELAY_MS, RELAY_TOKEN_PARAM } from "./protocol.js";
import { createRelayServer, type RelayServer } from "./server.js";
import { sleep } from "@react-grab/utils/server";
import { detectParentIDE } from "./detect-ide.js";

const VERSION = process.env.VERSION ?? "0.0.0";

Expand Down Expand Up @@ -38,18 +39,21 @@ export const connectRelay = async (
const relayPort = options.port ?? DEFAULT_RELAY_PORT;
const { handler, token } = options;

// Detect parent IDE
const ideInfo = detectParentIDE();

let relayServer: RelayServer | null = null;
let isRelayHost = false;

const isRelayServerRunning = await checkIfRelayServerIsRunning(relayPort, token);

if (isRelayServerRunning) {
relayServer = await connectToExistingRelay(relayPort, handler, token);
relayServer = await connectToExistingRelay(relayPort, handler, token, ideInfo);
} else {
await fkill(`:${relayPort}`, { force: true, silent: true }).catch(() => {});
await sleep(POST_KILL_DELAY_MS);

relayServer = createRelayServer({ port: relayPort, token });
relayServer = createRelayServer({ port: relayPort, token, ideInfo });
relayServer.registerHandler(handler);

try {
Expand All @@ -68,11 +72,11 @@ export const connectRelay = async (

if (!isNowRunning) throw error;

relayServer = await connectToExistingRelay(relayPort, handler, token);
relayServer = await connectToExistingRelay(relayPort, handler, token, ideInfo);
}
}

printStartupMessage(handler.agentId, relayPort);
printStartupMessage(handler.agentId, relayPort, ideInfo);

const handleShutdown = async () => {
if (isRelayHost) {
Expand Down Expand Up @@ -103,6 +107,7 @@ const connectToExistingRelay = async (
port: number,
handler: AgentHandler,
token?: string,
ideInfo?: IDEInfo,
): Promise<RelayServer> => {
const { WebSocket } = await import("ws");

Expand Down Expand Up @@ -144,6 +149,7 @@ const connectToExistingRelay = async (
JSON.stringify({
type: "register-handler",
agentId: handler.agentId,
ideInfo,
}),
);

Expand Down Expand Up @@ -282,9 +288,12 @@ const connectToExistingRelay = async (
});
};

const printStartupMessage = (agentId: string, port: number) => {
const printStartupMessage = (agentId: string, port: number, ideInfo?: IDEInfo) => {
console.log(
`${pc.magenta("✿")} ${pc.bold("React Grab")} ${pc.gray(VERSION)} ${pc.dim(`(${agentId})`)}`,
);
console.log(`- Local: ${pc.cyan(`ws://localhost:${port}`)}`);
if (ideInfo?.editorName) {
console.log(`- IDE: ${pc.green(ideInfo.editorName)}`);
}
};
Loading