Skip to content

Instantly share code, notes, and snippets.

@maurycy
Last active March 21, 2026 20:17
Show Gist options
  • Select an option

  • Save maurycy/50a80586636a90216efc86065bbfd6de to your computer and use it in GitHub Desktop.

Select an option

Save maurycy/50a80586636a90216efc86065bbfd6de to your computer and use it in GitHub Desktop.
extension.js
const vscode = require("vscode");
const fs = require("fs");
const path = require("path");
let profileData = null; // Map<filepath, Map<lineNo, {self, cumulative}>>
let samplesTotal = 0;
let decorationTypes = [];
// ---------------------------------------------------------------------------
// JSONL parser
// ---------------------------------------------------------------------------
function parseJsonl(filePath) {
const content = fs.readFileSync(filePath, "utf-8");
const lines = content.split("\n").filter((l) => l.trim());
const strings = {};
const frames = [];
const agg = {};
let total = 0;
for (const line of lines) {
const record = JSON.parse(line);
switch (record.type) {
case "str_def":
for (const d of record.defs) strings[d.str_id] = d.value;
break;
case "frame_def":
frames.push(...record.defs);
break;
case "agg":
total = record.samples_total || total;
for (const e of record.entries) {
if (agg[e.frame_id]) {
agg[e.frame_id].self += e.self;
agg[e.frame_id].cumulative += e.cumulative;
} else {
agg[e.frame_id] = { self: e.self, cumulative: e.cumulative };
}
}
break;
case "end":
total = record.samples_total || total;
break;
}
}
// Aggregate per (filepath, line)
const result = new Map();
for (const frame of frames) {
const filepath = strings[frame.path_str_id];
const line = frame.line;
if (!filepath || line <= 0 || !agg[frame.frame_id]) continue;
if (!result.has(filepath)) result.set(filepath, new Map());
const fileMap = result.get(filepath);
const existing = fileMap.get(line) || { self: 0, cumulative: 0 };
existing.self += agg[frame.frame_id].self;
existing.cumulative += agg[frame.frame_id].cumulative;
fileMap.set(line, existing);
}
return { data: result, samplesTotal: total };
}
// ---------------------------------------------------------------------------
// Decorations
// ---------------------------------------------------------------------------
function clearDecorations() {
for (const dt of decorationTypes) dt.dispose();
decorationTypes = [];
}
function findLineMap(filePath) {
if (!profileData) return null;
if (profileData.has(filePath)) return profileData.get(filePath);
for (const [storedPath, map] of profileData.entries()) {
if (
filePath.endsWith(storedPath) ||
storedPath.endsWith(path.basename(filePath))
) {
return map;
}
}
return null;
}
const NUM_BUCKETS = 5;
const MIN_PCT = 0.001;
function borderColor(intensity) {
const r = 255;
const g = Math.round(180 * (1 - intensity));
const b = Math.round(60 * (1 - intensity));
return `rgb(${r}, ${g}, ${b})`;
}
function hoverMarkdown(data, selfPct, cumulPct) {
const lines = [
`**Self:** ${selfPct.toFixed(1)}% (${data.self} samples)`,
`**Cumulative:** ${cumulPct.toFixed(1)}% (${data.cumulative} samples)`,
`**Total samples:** ${samplesTotal}`,
];
return new vscode.MarkdownString(lines.join(" \n"));
}
function applyDecorations(editor) {
if (!profileData || !editor) return;
clearDecorations();
const lineMap = findLineMap(editor.document.uri.fsPath);
if (!lineMap) return;
let maxSelf = 0;
for (const data of lineMap.values()) {
if (data.self > maxSelf) maxSelf = data.self;
}
const buckets = Array.from({ length: NUM_BUCKETS }, () => []);
const cumulOnly = [];
for (const [lineNo, data] of lineMap.entries()) {
if (lineNo < 1 || lineNo > editor.document.lineCount) continue;
const selfPct =
samplesTotal > 0 ? (data.self / samplesTotal) * 100 : 0;
const cumulPct =
samplesTotal > 0 ? (data.cumulative / samplesTotal) * 100 : 0;
if (selfPct < MIN_PCT && cumulPct < MIN_PCT) continue;
const range = new vscode.Range(lineNo - 1, 0, lineNo - 1, 0);
const hover = hoverMarkdown(data, selfPct, cumulPct);
if (data.self > 0 && selfPct >= MIN_PCT) {
const intensity = maxSelf > 0 ? data.self / maxSelf : 0;
const idx = Math.min(
Math.floor(intensity * NUM_BUCKETS),
NUM_BUCKETS - 1
);
const hot = intensity > 0.8 && selfPct >= 5 ? " << hot" : "";
buckets[idx].push({
range,
hoverMessage: hover,
renderOptions: {
after: {
contentText: ` ${selfPct.toFixed(1)}% self, ${cumulPct.toFixed(1)}% cumul${hot}`,
color: "rgba(150, 150, 150, 0.7)",
fontStyle: "italic",
},
},
});
} else if (cumulPct >= MIN_PCT) {
cumulOnly.push({
range,
hoverMessage: hover,
renderOptions: {
after: {
contentText: ` (${cumulPct.toFixed(1)}% cumul)`,
color: "rgba(150, 150, 150, 0.5)",
fontStyle: "italic",
},
},
});
}
}
for (let i = 0; i < NUM_BUCKETS; i++) {
if (buckets[i].length === 0) continue;
const intensity = (i + 1) / NUM_BUCKETS;
const alpha = (0.05 + (i / (NUM_BUCKETS - 1)) * 0.25).toFixed(2);
const dt = vscode.window.createTextEditorDecorationType({
backgroundColor: `rgba(255, 60, 60, ${alpha})`,
borderWidth: "0 0 0 3px",
borderStyle: "solid",
borderColor: borderColor(intensity),
isWholeLine: true,
overviewRulerColor: borderColor(intensity),
overviewRulerLane: vscode.OverviewRulerLane.Left,
});
decorationTypes.push(dt);
editor.setDecorations(dt, buckets[i]);
}
if (cumulOnly.length > 0) {
const dt = vscode.window.createTextEditorDecorationType({
backgroundColor: "rgba(255, 165, 0, 0.05)",
borderWidth: "0 0 0 3px",
borderStyle: "solid",
borderColor: "rgba(255, 165, 0, 0.3)",
isWholeLine: true,
});
decorationTypes.push(dt);
editor.setDecorations(dt, cumulOnly);
}
}
// ---------------------------------------------------------------------------
// Activation
// ---------------------------------------------------------------------------
function activate(context) {
context.subscriptions.push(
vscode.commands.registerCommand("profiling.loadProfile", async () => {
const uris = await vscode.window.showOpenDialog({
filters: { "JSONL Profile": ["jsonl"] },
canSelectMany: false,
});
if (!uris || uris.length === 0) return;
try {
const result = parseJsonl(uris[0].fsPath);
profileData = result.data;
samplesTotal = result.samplesTotal;
vscode.window.showInformationMessage(
`Loaded profile: ${samplesTotal} samples, ${profileData.size} files`
);
if (vscode.window.activeTextEditor) {
applyDecorations(vscode.window.activeTextEditor);
}
} catch (err) {
vscode.window.showErrorMessage(
`Failed to load profile: ${err.message}`
);
}
})
);
context.subscriptions.push(
vscode.commands.registerCommand("profiling.clearProfile", () => {
profileData = null;
samplesTotal = 0;
clearDecorations();
vscode.window.showInformationMessage("Profile annotations cleared");
})
);
context.subscriptions.push(
vscode.window.onDidChangeActiveTextEditor((editor) => {
if (editor) applyDecorations(editor);
})
);
}
function deactivate() {
clearDecorations();
}
module.exports = { activate, deactivate };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment