You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

438 lines
12 KiB

#!/usr/bin/env node
/**
* Opens a file at a specific line in the Antigravity Desktop App's Auxiliary Panel (right split).
*
* Can be invoked:
* 1. Via Windows URL protocol: `antigravity-app://file/C:/path/to/file.tsx:42:5`
* 2. Via CLI: `node open-in-antigravity-app.cjs "C:/path/to/file.tsx:42:5"`
* 3. Programmatically: `const { openInAntigravityApp } = require("./open-in-antigravity-app.cjs")`
*/
const fs = require("fs");
const os = require("os");
const path = require("path");
const { spawn } = require("child_process");
function parseAppLocator(raw) {
let cleaned = String(raw || "").trim();
// Strip surrounding quotes if passed from Windows shell
cleaned = cleaned.replace(/^["']+|["']+$/g, "");
// Strip custom URL protocol prefix (e.g. antigravity-app://file/, antigravity://file/)
if (!/^[a-zA-Z]:[/\\]/.test(cleaned)) {
cleaned = cleaned.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\/(?:file\/?)?/i, "");
}
try {
cleaned = decodeURIComponent(cleaned);
} catch {
// Keep as-is if percent-decoding fails
}
// Strip leading slash before Windows drive letter (e.g. /C:/Users/... -> C:/Users/...)
cleaned = cleaned.replace(/^\/+([a-zA-Z]:[/\\])/, "$1");
// Strip trailing slash added by browser protocol handlers
cleaned = cleaned.replace(/\/+$/, "");
let filePath = cleaned;
let line = null;
let column = null;
const lineColMatch = cleaned.match(/^(.*):(\d+|unknown):(\d+|unknown)$/);
if (lineColMatch) {
filePath = lineColMatch[1];
line = lineColMatch[2] === "unknown" ? null : Number(lineColMatch[2]);
column = lineColMatch[3] === "unknown" ? null : Number(lineColMatch[3]);
} else {
const lineOnlyMatch = cleaned.match(/^(.*):(\d+)$/);
if (lineOnlyMatch) {
filePath = lineOnlyMatch[1];
line = Number(lineOnlyMatch[2]);
}
}
const normalizedPath = filePath.replace(/\\/g, "/");
const driveMatch = normalizedPath.match(/^([a-zA-Z]):(\/.*)$/);
const rawFileUri = driveMatch
? `file:///${driveMatch[1].toLowerCase()}:${driveMatch[2]}`
: normalizedPath.startsWith("/")
? `file://${normalizedPath}`
: `file:///${normalizedPath}`;
const encodedPath = driveMatch
? `${driveMatch[1].toLowerCase()}%3A${driveMatch[2]
.split("/")
.map((seg) => encodeURIComponent(seg))
.join("/")}`
: normalizedPath
.split("/")
.map((seg) => encodeURIComponent(seg))
.join("/");
const encodedFileUri = `file:///${encodedPath.replace(/^\/+/, "")}`;
const encodedFileUriWithLine =
line !== null ? `${encodedFileUri}#L${line}-${line}` : encodedFileUri;
return {
filePath: normalizedPath,
line,
column,
rawFileUri,
encodedFileUri,
encodedFileUriWithLine,
};
}
function getAntigravityExecutablePath() {
const platform = os.platform();
if (platform === "win32") {
const localAppData =
process.env.LOCALAPPDATA || path.join(os.homedir(), "AppData", "Local");
return path.join(localAppData, "Programs", "antigravity", "Antigravity.exe");
}
if (platform === "darwin") {
return "/Applications/Antigravity.app/Contents/MacOS/Antigravity";
}
return "antigravity";
}
function getDevToolsActivePortPath() {
const platform = os.platform();
if (platform === "win32") {
const appData =
process.env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
return path.join(appData, "Antigravity", "DevToolsActivePort");
}
if (platform === "darwin") {
return path.join(
os.homedir(),
"Library",
"Application Support",
"Antigravity",
"DevToolsActivePort"
);
}
return path.join(os.homedir(), ".config", "Antigravity", "DevToolsActivePort");
}
function focusOrLaunchAntigravityApp() {
const exePath = getAntigravityExecutablePath();
try {
if (os.platform() !== "win32" || fs.existsSync(exePath)) {
const child = spawn(exePath, [], {
detached: true,
stdio: "ignore",
windowsHide: false,
});
child.unref();
}
} catch {
// Ignore spawn errors if already running or custom path
}
}
async function waitForDevToolsTarget(timeoutMs = 6000) {
const portFile = getDevToolsActivePortPath();
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
try {
if (fs.existsSync(portFile)) {
const lines = fs
.readFileSync(portFile, "utf8")
.trim()
.split(/\r?\n/);
const port = Number(lines[0]);
if (port > 0) {
const res = await fetch(`http://127.0.0.1:${port}/json`);
if (res.ok) {
const targets = await res.json();
const page = targets.find(
(t) => t.type === "page" && t.webSocketDebuggerUrl
);
if (page) {
return page;
}
}
}
}
} catch {
// Wait and retry if Antigravity is still starting up
}
await new Promise((r) => setTimeout(r, 200));
}
throw new Error(
`Could not connect to Antigravity DevToolsActivePort at ${portFile}`
);
}
async function openInAntigravityApp(rawLocator) {
const parsed = parseAppLocator(rawLocator);
// Trigger Electron's second-instance handler so Antigravity restores & focuses its window
focusOrLaunchAntigravityApp();
const pageTarget = await waitForDevToolsTarget();
// Function serialized and executed inside the Antigravity renderer context
const rendererOpenFn = async (payload) => {
const {
filePath,
line,
rawFileUri,
encodedFileUri,
encodedFileUriWithLine,
} = payload;
const root = document.getElementById("root");
if (!root) {
return { success: false, reason: "No #root element" };
}
const containerKey = Object.keys(root).find((k) =>
k.startsWith("__reactContainer$")
);
if (!containerKey) {
return { success: false, reason: "No React fiber container on #root" };
}
const startNode = root[containerKey].current || root[containerKey];
const queue = [startNode];
const seen = new Set();
const contexts = [];
let store = null;
while (queue.length > 0) {
const fiber = queue.shift();
if (!fiber || seen.has(fiber)) continue;
seen.add(fiber);
const val = fiber.memoizedProps?.value || fiber.memoizedProps;
if (val) {
if (val.store && typeof val.store.dispatch === "function") {
store = val.store;
} else if (
typeof val.dispatch === "function" &&
typeof val.getState === "function"
) {
store = val;
}
if (val.stepHandler && typeof val.stepHandler.openFile === "function") {
contexts.push({
stepHandler: val.stepHandler,
workspaceUris: val.workspaceInfo?.workspaceUris || [],
});
}
}
if (fiber.child) queue.push(fiber.child);
if (fiber.sibling) queue.push(fiber.sibling);
}
const resolveTreeId = () => {
const pathname = window.location.pathname || "";
if (pathname.startsWith("/c/")) {
const cascadeId = pathname.slice(3).split("/")[0];
if (cascadeId) return { kind: "cascadeId", cascadeId };
}
const sectionId = new URLSearchParams(window.location.search).get(
"section"
);
if (sectionId) {
return { kind: "newConversation", sectionId };
}
if (store) {
const focusedPaneId = store.getState()?.multiConvoLayout?.focusedPaneId;
const rootNode = store.getState()?.multiConvoLayout?.rootNode;
if (rootNode?.cascadeId) {
return { kind: "cascadeId", cascadeId: rootNode.cascadeId };
}
if (focusedPaneId && rootNode?.children) {
const match = rootNode.children.find((c) => c.id === focusedPaneId);
if (match?.cascadeId) {
return { kind: "cascadeId", cascadeId: match.cascadeId };
}
}
}
return { kind: "home" };
};
const treeId = resolveTreeId();
const tabId = `file__${encodedFileUri}`;
// If the file is already open in the Auxiliary Panel, clear its cached scrollPos
// so opening it at a new line number scrolls freshly to the requested line.
if (store && line !== null) {
try {
store.dispatch({
type: "auxPaneV2/clearContent",
payload: { treeId, tabId },
});
} catch {
// Ignore if slice differs
}
}
// Prefer a stepHandler whose workspace matches the target file path
const lowerTarget = filePath.toLowerCase();
const matchingContext =
contexts
.slice()
.reverse()
.find((ctx) =>
ctx.workspaceUris.some((uri) => {
try {
const decoded = decodeURIComponent(uri)
.replace(/^file:\/\/\/+/i, "")
.replace(/\\/g, "/")
.toLowerCase();
return lowerTarget.startsWith(decoded);
} catch {
return false;
}
})
) || contexts[contexts.length - 1];
if (matchingContext?.stepHandler) {
await matchingContext.stepHandler.openFile(
rawFileUri,
line !== null ? line : undefined,
line !== null ? line : undefined
);
return {
success: true,
via: "stepHandler.openFile",
uri: encodedFileUriWithLine,
};
}
// Fallback when on New Conversation / Home screen where stepHandler is not mounted
if (store) {
const cascadeId =
treeId.kind === "cascadeId" ? treeId.cascadeId : undefined;
store.dispatch({
type: "auxPaneV2/setContent",
payload: {
treeId,
content: {
type: "fileView",
fileView: {
fileUri: encodedFileUriWithLine,
...(cascadeId ? { cascadeId } : {}),
},
},
tabId,
keepOpen: false,
},
});
store.dispatch({
type: "auxPane/setAuxPaneOpen",
payload: { treeId, isOpen: true },
});
return {
success: true,
via: "auxPaneV2/setContent",
uri: encodedFileUriWithLine,
};
}
return {
success: false,
reason: "Neither stepHandler nor Redux store found",
};
};
return new Promise((resolve, reject) => {
const ws = new WebSocket(pageTarget.webSocketDebuggerUrl);
const timeout = setTimeout(() => {
try {
ws.close();
} catch {}
reject(new Error("Timed out communicating with Antigravity renderer"));
}, 5000);
ws.onopen = () => {
ws.send(JSON.stringify({ id: 1, method: "Page.bringToFront" }));
ws.send(
JSON.stringify({
id: 2,
method: "Runtime.evaluate",
params: {
expression: `(${rendererOpenFn.toString()})(${JSON.stringify(
parsed
)})`,
awaitPromise: true,
returnByValue: true,
},
})
);
};
ws.onmessage = (event) => {
try {
const msg = JSON.parse(
typeof event.data === "string"
? event.data
: event.data.toString("utf8")
);
if (msg.id === 2) {
clearTimeout(timeout);
try {
ws.close();
} catch {}
const value = msg.result?.result?.value;
if (value?.success) {
resolve(value);
} else {
reject(
new Error(
value?.reason ||
msg.result?.exceptionDetails?.text ||
"Failed to open file in Antigravity Auxiliary Panel"
)
);
}
}
} catch (err) {
clearTimeout(timeout);
try {
ws.close();
} catch {}
reject(err);
}
};
ws.onerror = (err) => {
clearTimeout(timeout);
try {
ws.close();
} catch {}
reject(err);
};
});
}
if (require.main === module) {
const arg = process.argv.slice(2).join(" ");
if (!arg) {
console.error(
"Usage: node open-in-antigravity-app.cjs <antigravity-app://file/path:line:col | path:line:col>"
);
process.exit(1);
}
openInAntigravityApp(arg)
.then(() => process.exit(0))
.catch((err) => {
console.error("[open-in-antigravity-app]", err);
process.exit(1);
});
}
module.exports = {
parseAppLocator,
openInAntigravityApp,
};