Skip to content

Commit 700bd39

Browse files
authored
actually emit the version when opening baml file (#2612)
<!-- CURSOR_SUMMARY --> > [!NOTE] > Emit generator version on BAML file open and track the last active BAML file in VS Code to scope version updates; improve reload/logging and simplify debug/telemetry handling. > > - **Engine (LSP)**: > - **didOpen**: Reload project and send `baml_src_generator_version`; add tracing around generator version retrieval. > - **didSave**: Add info log when no generator version map is available. > - **Session.reload**: Enhance logging (per-project and total file counts) during initial reload. > - **VS Code Extension**: > - **Active file tracking**: Introduce `LAST_ACTIVE_BAML_FILE` and update it on cursor selection; use it to validate `baml_src_generator_version` root before acting. > - **Debug/telemetry**: Replace `isDebugOrTestSession` with `isDebugMode`; always initialize telemetry; adjust disposal condition; add debug-mode CLI logs. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit 95dc502. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY -->
1 parent 07a0bb6 commit 700bd39

File tree

7 files changed

+70
-35
lines changed

7 files changed

+70
-35
lines changed

engine/language_server/src/server/api/notifications/did_open.rs

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,15 @@ impl SyncNotificationHandler for DidOpenTextDocumentHandler {
7575
)
7676
.internal_error()?;
7777

78-
// tracing::info!("before get_or_create_project");
78+
// session.open_text_document(
79+
// q DocumentKey::from_path(&file_path, &file_path).internal_error()?,
80+
// TextDocument::new(params.text_document.text, params.text_document.version),
81+
// );
82+
83+
session.reload(Some(notifier.clone())).internal_error()?;
84+
85+
// We do this after the project reload since we may be loading this baml project with files (and creating a new runtime) in the .reload(), and we only want to send the generator version if we've had a runtime created. Ideally we don't depend on the runtime being created (since our version of the LSP may not be able to read all baml files), and it only reads the generator config blocks.
86+
tracing::info!("before send_generator_version");
7987
{
8088
let locked = project.lock();
8189
let default_flags = vec!["beta".to_string()];
@@ -87,16 +95,10 @@ impl SyncNotificationHandler for DidOpenTextDocumentHandler {
8795
let client_version = session.baml_settings.get_client_version();
8896

8997
let generator_version = locked.get_common_generator_version();
98+
tracing::info!("common generator version {:?}", generator_version);
9099
send_generator_version(&notifier, &locked, generator_version.as_ref().ok());
91100
}
92101

93-
// session.open_text_document(
94-
// DocumentKey::from_path(&file_path, &file_path).internal_error()?,
95-
// TextDocument::new(params.text_document.text, params.text_document.version),
96-
// );
97-
98-
session.reload(Some(notifier.clone())).internal_error()?;
99-
100102
publish_session_lsp_diagnostics(&notifier, session, &url)?;
101103

102104
Ok(())

engine/language_server/src/server/api/notifications/did_save_text_document.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,8 @@ pub(crate) fn send_generator_version(
164164
"Failed to send baml_src_generator_version notification to IDE: {e}"
165165
);
166166
});
167+
} else {
168+
tracing::info!("No version map available");
167169
}
168170
}
169171

engine/language_server/src/session.rs

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -245,12 +245,19 @@ impl Session {
245245

246246
let project_updates: Vec<HashMap<_, _>> = baml_src_projects
247247
.iter_mut()
248-
.map(|(_project_root, project)| {
248+
.map(|(project_root, project)| {
249249
let files_map = project
250250
.lock()
251251
.baml_project
252252
.load_files()
253253
.map_err(|e| anyhow::anyhow!("Failed to load project files: {}", e))?;
254+
255+
tracing::info!(
256+
"Loaded {} files for project root: {:?}",
257+
files_map.len(),
258+
project_root
259+
);
260+
254261
{
255262
let default_flags = vec!["beta".to_string()];
256263
project.lock().update_runtime(
@@ -268,7 +275,13 @@ impl Session {
268275
Ok(files_map)
269276
})
270277
.collect::<anyhow::Result<Vec<_>>>()?;
271-
tracing::info!("Initial reload of {} files", project_updates.len());
278+
279+
let total_files: usize = project_updates.iter().map(|m| m.len()).sum();
280+
tracing::info!(
281+
"Initial reload complete: {} projects, {} total files",
282+
project_updates.len(),
283+
total_files
284+
);
272285

273286
// Guard no longer used. We can drop now instead of waiting for the end
274287
// of scope.

typescript/apps/vscode-ext/src/extension.ts

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import type { Express } from 'express'
1717
import { Socket } from 'net'
1818
import StatusBarPanel from './panels/StatusBarPanel'
1919
import { Server } from 'http'
20+
import { LAST_ACTIVE_BAML_FILE } from './helpers/get-open-file'
2021

2122
const outputChannel = vscode.window.createOutputChannel('baml')
2223
const diagnosticsCollection =
@@ -292,7 +293,18 @@ export function activate(context: vscode.ExtensionContext) {
292293
})
293294

294295
// Add cursor movement listener
296+
vscode.window.onDidChangeActiveTextEditor
295297
vscode.window.onDidChangeTextEditorSelection((event) => {
298+
299+
// properly track the actual last known baml file.
300+
if (event.textEditor.document.fileName.endsWith(".baml")) {
301+
LAST_ACTIVE_BAML_FILE.uri = event.textEditor.document.uri;
302+
}
303+
304+
305+
306+
// The code below this line may not be fully accurate. The vscode.window.activeTextEditor may go
307+
// undefined in some cases.
296308
const position = event.selections[0]?.active
297309

298310
const editor = vscode.window.activeTextEditor
@@ -303,6 +315,8 @@ export function activate(context: vscode.ExtensionContext) {
303315
return
304316
}
305317

318+
319+
306320
// TODO: buggy when used with multiple functions, needs a fix.
307321
WebviewPanelHost.currentPanel?.sendCommandToWebview({
308322
source: 'ide_message',

typescript/apps/vscode-ext/src/helpers/get-open-file.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,3 +13,7 @@ export const getCurrentOpenedFile = () => {
1313
return visibleEditors[0]?.document.uri?.toString() ?? '';
1414
}
1515
};
16+
17+
export const LAST_ACTIVE_BAML_FILE: { uri: undefined | vscode.Uri } = {
18+
uri: undefined
19+
};

typescript/apps/vscode-ext/src/plugins/language-server-client/index.ts

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -20,14 +20,13 @@ import {
2020
import { URI } from 'vscode-uri';
2121
import { z } from 'zod';
2222
import packageJson from '../../../package.json';
23-
import { getCurrentOpenedFile } from '../../helpers/get-open-file';
23+
import { getCurrentOpenedFile, LAST_ACTIVE_BAML_FILE } from '../../helpers/get-open-file';
2424
import StatusBarPanel from '../../panels/StatusBarPanel';
2525
import { WebviewPanelHost } from '../../panels/WebviewPanelHost';
2626
import TelemetryReporter from '../../telemetryReporter';
2727
import {
2828
checkForMinimalColorTheme,
2929
createLanguageServer,
30-
isDebugOrTestSession,
3130
} from '../../util';
3231
import type { BamlVSCodePlugin } from '../types';
3332
import {
@@ -544,15 +543,16 @@ export const registerClientEventHandlers = (client: LanguageClient, context: Ext
544543
}
545544

546545
// Check if this version update is for the currently active baml_src directory
547-
const activeEditor =
548-
window.activeTextEditor || (window.visibleTextEditors.length > 0 ? window.visibleTextEditors[0] : null);
546+
const activeEditor = LAST_ACTIVE_BAML_FILE.uri;
549547
if (activeEditor) {
550548
try {
551-
const currentFilePath = URI.parse(activeEditor.document.uri.toString()).fsPath;
549+
550+
const currentFilePath = activeEditor.fsPath;
551+
552552
const rootPathUri = URI.file(payload.root_path).fsPath;
553553
if (!isPathWithinParent(currentFilePath, rootPathUri)) {
554554
bamlOutputChannel.appendLine(
555-
`baml_src_generator_version ignored: root path does not match active editor ${currentFilePath} ${rootPathUri}`,
555+
`baml_src_generator_version ignored: root path does not match active editor ${currentFilePath} root: ${rootPathUri}`,
556556
);
557557
return;
558558
}
@@ -795,7 +795,7 @@ const plugin: BamlVSCodePlugin = {
795795
name: 'baml-language-server',
796796
enabled: () => true,
797797
activate: async (context, _outputChannel) => {
798-
const isDebugOrTest = isDebugOrTestSession();
798+
const isDebugOrTest = isDebugMode();
799799
bamlOutputChannel = _outputChannel;
800800
context.subscriptions.push(bamlOutputChannel);
801801
bamlOutputChannel.appendLine('Activating BAML Language Server plugin...');
@@ -809,6 +809,8 @@ const plugin: BamlVSCodePlugin = {
809809

810810
let serverAbsolutePath: string | null = null;
811811
if (isDebugOrTest) {
812+
console.log('Using debug cli in debug mode');
813+
bamlOutputChannel.append('Using debug cli in debug mode');
812814
serverAbsolutePath = process.env.VSCODE_DEBUG_BAML_CLI_PATH || null;
813815
} else {
814816
try {
@@ -1029,22 +1031,22 @@ const plugin: BamlVSCodePlugin = {
10291031

10301032
activateClient(context, serverOptions, clientOptions);
10311033

1032-
if (!isDebugOrTest) {
1033-
try {
1034-
const extensionId = `Boundary.${packageJson.name}`;
1035-
const extensionVersion: string = packageJson.version;
1036-
console.log(
1037-
`Initializing telemetry for ${extensionId} v${extensionVersion}`,
1038-
);
1039-
telemetry = new TelemetryReporter(extensionId, extensionVersion);
1040-
context.subscriptions.push(telemetry);
1041-
await telemetry.initialize();
1042-
console.log('Telemetry initialized.');
1043-
} catch (err) {
1044-
console.error('Failed to initialize telemetry:', err);
1045-
}
1034+
1035+
try {
1036+
const extensionId = `Boundary.${packageJson.name}`;
1037+
const extensionVersion: string = packageJson.version;
1038+
console.log(
1039+
`Initializing telemetry for ${extensionId} v${extensionVersion}`,
1040+
);
1041+
telemetry = new TelemetryReporter(extensionId, extensionVersion);
1042+
context.subscriptions.push(telemetry);
1043+
await telemetry.initialize();
1044+
console.log('Telemetry initialized.');
1045+
} catch (err) {
1046+
console.error('Failed to initialize telemetry:', err);
10461047
}
10471048

1049+
10481050
checkForMinimalColorTheme();
10491051
console.log('BAML Language Server plugin activation finished.');
10501052
},
@@ -1061,7 +1063,7 @@ const plugin: BamlVSCodePlugin = {
10611063
console.log('Client not running or already stopped.');
10621064
}
10631065

1064-
if (!isDebugOrTestSession() && telemetry) {
1066+
if (!isDebugMode() && telemetry) {
10651067
console.log('Disposing telemetry.');
10661068
await telemetry.dispose().catch((err) => {
10671069
console.error('Error disposing telemetry:', err);

typescript/apps/vscode-ext/src/util.ts

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,7 @@ import type {
1717
} from 'vscode-languageclient';
1818
import { LanguageClient, type ServerOptions } from 'vscode-languageclient/node';
1919

20-
export function isDebugOrTestSession(): boolean {
21-
return env.sessionId === 'someValue.sessionId';
22-
}
20+
2321

2422
export function checkForOtherPrismaExtension(): void {
2523
const files = readdirSync(path.join(homedir(), '.vscode/extensions')).filter(

0 commit comments

Comments
 (0)