Skip to content

fix(DiagnosticProvider): слать workspace/diagnostic/refresh после наполнения контекста#4057

Merged
nixel2007 merged 4 commits into
developfrom
claude/diagnostics-refresh-on-populate
Jun 12, 2026
Merged

fix(DiagnosticProvider): слать workspace/diagnostic/refresh после наполнения контекста#4057
nixel2007 merged 4 commits into
developfrom
claude/diagnostics-refresh-on-populate

Conversation

@nixel2007

@nixel2007 nixel2007 commented Jun 12, 2026

Copy link
Copy Markdown
Member

Проблема

При interFileDependencies=true межфайловые диагностики уже открытых документов (неиспользуемые методы, обращения к общим модулям и т.п.) устаревали после построения индексов. refreshDiagnostics отправлялся только при смене конфигурации, поэтому после ServerContextPopulatedEvent pull-клиент не узнавал, что надо перезапросить диагностики.

Дополнительно при анализе на старте AnalyzeProjectOnStart безусловно публиковал диагностики push-ем даже для клиента с pull-моделью — для открытых документов это создавало второй конкурирующий источник тех же диагностик.

Решение

  • DiagnosticProvider подписан на ServerContextPopulatedEvent; при поддержке клиентом workspace.diagnostics.refreshSupport дёргается workspace/diagnostic/refresh. Логика отправки refresh вынесена в общий requestRefreshIfSupported().
  • Признак pull-клиента вынесен в ClientCapabilitiesHolder.supportsPullDiagnostics() и переиспользован в BSLTextDocumentService и AnalyzeProjectOnStart, чтобы не дублировать проверку capability. Для pull-клиента push-публикация при анализе на старте больше не выполняется (документы по-прежнему перестраиваются, а диагностики клиент запросит сам через refresh).

Тесты

  • DiagnosticProviderTest:
    • testServerContextPopulatedRequestsRefreshWhenClientSupportsRefresh
    • testServerContextPopulatedDoesNotRequestRefreshWhenClientDoesNotSupportRefresh
  • AnalyzeProjectOnStartTest:
    • doesNotPublishDiagnosticsToPullClient

Прогон: DiagnosticProviderTest 10/10, AnalyzeProjectOnStartTest 4/4, BSLTextDocumentServiceTest 65/65 — без падений.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes

    • Improved diagnostic refresh timing to ensure errors and warnings update promptly after server initialization and configuration changes.
  • Refactor

    • Simplified detection of client diagnostic support to improve reliability and maintainability.
  • Tests

    • Added tests covering diagnostic refresh behavior and client capability detection to prevent regressions.

@coderabbitai

coderabbitai Bot commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 0e028e73-050d-4828-b0ce-e148ddbd68e5

📥 Commits

Reviewing files that changed from the base of the PR and between f0a679d and d910e12.

📒 Files selected for processing (3)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentService.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProvider.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProviderTest.java
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProvider.java
  • src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentService.java
  • src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProviderTest.java

📝 Walkthrough

Walkthrough

Centralizes pull-diagnostics capability detection in DiagnosticProvider, adds event-driven diagnostic refresh on server-context population and configuration changes, updates BSLTextDocumentService to query the provider, and adds tests covering capability detection and refresh behavior.

Changes

Diagnostic Pull Model Integration

Layer / File(s) Summary
Diagnostic pull model capability detection
src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProvider.java
supportsPullDiagnostics() method checks client textDocument.diagnostic capability support and returns false when capabilities are unset. Imports for TextDocumentClientCapabilities and ServerContextPopulatedEvent are added.
Event-driven diagnostic refresh
src/main/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProvider.java
handleConfigurationChangedEvent delegates to requestRefreshIfSupported(). New handleServerContextPopulatedEvent() listener requests diagnostic refresh when server context is populated if the client supports refresh capability.
Service initialization refactoring
src/main/java/com/github/_1c_syntax/bsl/languageserver/BSLTextDocumentService.java
handleInitializeEvent now uses diagnosticProvider.supportsPullDiagnostics() for pull-diagnostics detection. Unused capability imports (ClientCapabilities, TextDocumentClientCapabilities) and the redundant clientCapabilitiesHolder field are removed.
Test coverage for capability detection and refresh
src/test/java/com/github/_1c_syntax/bsl/languageserver/providers/DiagnosticProviderTest.java
Added test imports, @AfterEach teardown cleanup for client and capability state, and test cases validating supportsPullDiagnostics() correctness based on client capabilities and handleServerContextPopulatedEvent() refresh behavior. New initializeRefreshSupport() helper configures mocked capabilities and initializes provider state for testing.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested labels

hacktoberfest-accepted

Suggested reviewers

  • theshadowco

Poem

🐰 I checked the client's diagnostic song,
Pulled the capabilities all day long,
Events now wake the server's eye,
Refreshes hop when answers reply,
A little rabbit cheers: "Works right along!"

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 31.82% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is in Russian and describes the main change: sending workspace/diagnostic/refresh after context population. This directly relates to the core objective of the PR, which is to refresh diagnostics when ServerContextPopulatedEvent occurs.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/diagnostics-refresh-on-populate

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@github-actions

github-actions Bot commented Jun 12, 2026

Copy link
Copy Markdown
Contributor

Test Results

 3 246 files   3 246 suites   1h 24m 14s ⏱️
 3 097 tests  3 082 ✅ 15 💤 0 ❌
18 582 runs  18 492 ✅ 90 💤 0 ❌

Results for commit a2d178f.

♻️ This comment has been updated with latest results.

@sonarqubecloud

Copy link
Copy Markdown


// Клиент с pull-моделью сам запросит диагностики (в том числе через
// workspace/diagnostic/refresh), поэтому push-публикацию по открытым документам
// для него выполнять не нужно — иначе возникает второй конкурирующий источник

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

это сделано намерено, поддержки workspace/diagnosic/refresh еще нет

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Понял, откатил: AnalyzeProjectOnStart и его тесты возвращены к виду develop — push-публикация при старте снова безусловная. В PR остаётся только отправка workspace/diagnostic/refresh после наполнения контекста (она и так выполняется только при заявленной клиентом workspace.diagnostics.refreshSupport, так что для текущих клиентов это no-op). AnalyzeProjectOnStartTest и DiagnosticProviderTest зелёные.

nixel2007 and others added 4 commits June 12, 2026 18:50
…олнения контекста

После ServerContextPopulatedEvent межфайловые диагностики открытых документов
устаревают, поэтому при поддержке клиентом refreshSupport отправляем запрос на
повторный расчёт через workspace/diagnostic/refresh.

Co-Authored-By: Claude Fable 5 <[email protected]>
…с pull-моделью

Для клиента с pull-моделью push-публикация диагностик по открытым документам при
анализе на старте создавала второй конкурирующий источник тех же диагностик.
Признак pull-клиента вынесен в ClientCapabilitiesHolder.supportsPullDiagnostics()
и переиспользован в BSLTextDocumentService, чтобы не дублировать логику.

Co-Authored-By: Claude Fable 5 <[email protected]>
…tCapabilitiesHolder

Доменно-специфичный хелпер supportsPullDiagnostics() вынесен из общего
ClientCapabilitiesHolder в DiagnosticProvider. BSLTextDocumentService и
AnalyzeProjectOnStart переиспользуют его оттуда, без дублирования вычисления.

Co-Authored-By: Claude Fable 5 <[email protected]>
… анализе на старте

Безусловный push при старте сделан намеренно: поддержки workspace/diagnostic/refresh
на стороне клиентов ещё нет. AnalyzeProjectOnStart и его тесты возвращены к виду develop;
refresh после наполнения контекста (первый коммит PR) остаётся.

Co-Authored-By: Claude Fable 5 <[email protected]>
@nixel2007
nixel2007 force-pushed the claude/diagnostics-refresh-on-populate branch from f0a679d to d910e12 Compare June 12, 2026 16:50
@nixel2007
nixel2007 enabled auto-merge June 12, 2026 17:29
@nixel2007
nixel2007 disabled auto-merge June 12, 2026 18:00
@nixel2007
nixel2007 merged commit f33f4b7 into develop Jun 12, 2026
32 checks passed
@nixel2007
nixel2007 deleted the claude/diagnostics-refresh-on-populate branch June 12, 2026 18:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant