@@ -353,22 +353,7 @@ export class TelemetryTracer extends TelemetryBase {
353353 * See docs/telemetry.md
354354 */
355355 public run < T , U extends MetricName > ( name : U , fn : ( span : Metric < MetricShapes [ U ] > ) => T , options ?: SpanOptions ) : T {
356- const initTraceId = ( callback : ( ) => T ) : T => {
357- /**
358- * Generate a new traceId if one doesn't exist.
359- * This ensures the traceId is created before the span,
360- * allowing it to propagate to all child telemetry metrics.
361- */
362- if ( ! this . attributes ?. traceId ) {
363- return this . runRoot ( ( ) => {
364- this . record ( { traceId : randomUUID ( ) } )
365- return callback ( )
366- } )
367- }
368- return callback ( )
369- }
370-
371- return initTraceId ( ( ) => {
356+ return this . withTraceId ( ( ) => {
372357 const span = this . createSpan ( name , options ) . start ( )
373358 const frame = this . switchContext ( span )
374359
@@ -396,7 +381,34 @@ export class TelemetryTracer extends TelemetryBase {
396381 span . stop ( e )
397382 throw e
398383 }
399- } )
384+ } , this . attributes ?. traceId ?? randomUUID ( ) )
385+ }
386+
387+ /**
388+ * **Use {@link run} for most scenarios. Only use this method when you have a specific, pre-existing trace ID that you need to instrument.**
389+ *
390+ * Associates a known trace ID with subsequent telemetry events in the provided callback,
391+ * enabling correlation of events from multiple disjoint sources (e.g., webview, VSCode, partner team code).
392+ *
393+ * The difference between this and using telemetry.record({traceId: 'foo'}) directly is that this will create an active
394+ * span if one doesn't already exist. If you already know you're operating in a span (like vscode_executeCommand) then use
395+ * telemetry.record directly.
396+ *
397+ * Records traceId iff this metric is not already associated with a trace
398+ */
399+ withTraceId < T > ( callback : ( ) => T , traceId : string ) : T {
400+ /**
401+ * Generate a new traceId if one doesn't exist.
402+ * This ensures the traceId is created before the span,
403+ * allowing it to propagate to all child telemetry metrics.
404+ */
405+ if ( ! this . attributes ?. traceId ) {
406+ return this . runRoot ( ( ) => {
407+ this . record ( { traceId } )
408+ return callback ( )
409+ } )
410+ }
411+ return callback ( )
400412 }
401413
402414 /**
0 commit comments