@@ -10,6 +10,8 @@ import kotlinx.coroutines.flow.MutableStateFlow
1010import kotlinx.coroutines.flow.asStateFlow
1111import java.util.concurrent.atomic.AtomicInteger
1212import java.util.concurrent.atomic.AtomicReference
13+ import com.intellij.openapi.application.ApplicationManager
14+
1315
1416@Service
1517class CompletionProvider {
@@ -23,34 +25,46 @@ class CompletionProvider {
2325
2426 private val currentContext = AtomicReference <CompletionContext ?>(null )
2527
26- fun provideCompletion (editor : Editor , offset : Int , manually : Boolean = false) {
27- val currentSequence = completionSequence.incrementAndGet()
28- val agentService = service<AgentService >()
29- val inlineCompletionService = service<InlineCompletionService >()
28+ fun provideCompletion (editor : Editor , offset : Int , manually : Boolean = false) {
29+ logger.info(" start provideCompletion" )
30+ val currentSequence = completionSequence.incrementAndGet()
31+ val agentService = service<AgentService >()
32+ val inlineCompletionService = service<InlineCompletionService >()
3033
31- val oldContext = currentContext.getAndSet(null )
32- oldContext?.job?.cancel()
33- inlineCompletionService.dismiss()
34+ val oldContext = currentContext.getAndSet(null )
35+ oldContext?.job?.cancel()
36+ inlineCompletionService.dismiss()
3437
35- val job = agentService.scope.launch {
38+ val job = agentService.scope.launch {
39+ try {
3640 logger.info(" Trigger completion at $offset " )
37- agentService.provideCompletion(editor, offset, manually).let {
38- if (isActive) { // Check if the job is still active before updating
39- if (it != null && completionSequence.get() == currentSequence) {
40- logger.info(" Show completion at $offset : $it " )
41- inlineCompletionService.show(editor, offset, it)
42- }
43- currentContext.set(null )
44- ongoingCompletionFlow.value = null
41+ val result = agentService.provideCompletion(editor, offset, manually)
42+ if (isActive && result != null && completionSequence.get() == currentSequence) {
43+ logger.info(" Show completion at $offset : $result " )
44+ ApplicationManager .getApplication().invokeLater {
45+ inlineCompletionService.show(editor, offset, result)
4546 }
4647 }
47- }
48+ } catch (e: CancellationException ) {
49+ // 方案1:以较低的日志级别记录
50+ logger.info(" Completion was cancelled: ${e.message} " )
51+ // 或者方案2:完全忽略
52+ // // 不做任何处理
4853
49- val newContext = CompletionContext (editor, offset, job)
50- currentContext.set(newContext)
51- ongoingCompletionFlow.value = newContext
54+ null
55+ } catch (e: Exception ) {
56+ logger.error(" Error in completion job" , e)
57+ } finally {
58+ currentContext.set(null )
59+ ongoingCompletionFlow.value = null
60+ }
5261 }
5362
63+ val newContext = CompletionContext (editor, offset, job)
64+ currentContext.set(newContext)
65+ ongoingCompletionFlow.value = newContext
66+ }
67+
5468 fun clear () {
5569 val inlineCompletionService = service<InlineCompletionService >()
5670 inlineCompletionService.dismiss()
0 commit comments