Skip to content

Comments

Hotfix 16.01.2026 часть 2#1427

Merged
Rxup merged 4 commits intomasterfrom
hotfix-160126-2
Jan 16, 2026
Merged

Hotfix 16.01.2026 часть 2#1427
Rxup merged 4 commits intomasterfrom
hotfix-160126-2

Conversation

@Rxup
Copy link
Owner

@Rxup Rxup commented Jan 16, 2026

прошлый не успел доделать :)

Summary by CodeRabbit

  • Новые функции

    • В окно анализа здоровья добавлена панель «Причины боли» с вкладками «Нервная система» и «Причины боли по телу».
    • Показываются суммарный уровень боли, детализированный список причин с цветовой индикацией прогресса и кнопками помощи; отображение вкладок адаптируется к наличию данных.
    • Добавлен индикатор «заболевший» в секцию предупреждений.
  • Документация

    • Обновлены локализации (en-US, ru-RU) для новых текстов, статусов боли и меток вкладок.

✏️ Tip: You can customize this high-level summary in your review settings.

@github-actions github-actions bot added S: Untriaged size/L Changes: UI Can be reviewed or fixed by people who are knowledgeable with UI design Changes: Localization Can be reviewed or fixed by people who are knowledgeable with translation labels Jan 16, 2026
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jan 16, 2026

Walkthrough

Добавлен клиентский компонент PainCausesDisplay и интегрирован в HealthAnalyzer; конвейер расчёта боли расширен на сервере — ConsciousnessSystem переехал на обёртки Entity и агрегирует данные из PainSystem; обновлены сообщения сканера и локализации, а вызовы и тесты адаптированы под новые сигнатуры.

Изменения

Когорта / Файл(ы) Описание изменений
Новая UI-компонента
Content.Client/Backmen/Medical/UI/PainCausesDisplay.xaml, Content.Client/Backmen/Medical/UI/PainCausesDisplay.xaml.cs
Добавлен компонент PainCausesDisplay с табами для нервной системы и причин боли тела, прогресс-барами, цветовой индикацией уровней боли, кнопками справки и публичным методом UpdatePainCauses(...).
Интеграция в Health Analyzer (клиент)
Content.Client/HealthAnalyzer/UI/HealthAnalyzerWindow.xaml, Content.Client/HealthAnalyzer/UI/HealthAnalyzerWindow.xaml.cs
Заменён прежний блок отображения причин боли на <backmen:PainCausesDisplay />, обновлена логика вызова UpdatePainCauses, увеличена высота окна, добавлена обработка DiseasedComponent.
Серверная логика сознания — рефакторинг API
Content.Server/Backmen/Surgery/Consciousness/Systems/ServerConsciousnessSystem.cs, Content.Shared/Backmen/Surgery/Consciousness/Systems/ConsciousnessSystem.Helpers.cs, Content.Shared/Backmen/Surgery/Consciousness/Systems/ConsciousnessSystem.cs
Множество публичных/защищённых API переведены на обёртки Entity<ConsciousnessComponent?> / Entity<ConsciousnessComponent?, MobStateComponent?>; добавлены GetTotalPain(...) и обновлён GetPainCauses(...), агрегация данных из PainSystem.
Вызовы и адаптации на базе новых сигнатур
Content.Server/Medical/DefibrillatorSystem.cs, Content.Shared/Backmen/EntityEffects/Effects/AdjustConsciousness.cs, Content.Shared/Backmen/EntityEffects/Effects/AdjustPainFeels.cs, Content.Shared/Backmen/EntityEffects/Effects/SuppressPain.cs, Content.Shared/Chat/SharedSuicideSystem.cs
Обновлены вызовы методов сознания (передача nullable/обёрнутых Entity либо tuple-аргументов), использование entity.Owner при поиске нервной системы, адаптация параметров при Add/Remove/ChangeConsciousnessModifier/Multiplier.
HealthAnalyzerSystem и сообщение сканера
Content.Server/Medical/HealthAnalyzerSystem.cs, Content.Shared/MedicalScanner/HealthAnalyzerScannedUserMessage.cs
HealthAnalyzerSystem теперь запрашивает totalPain у ConsciousnessSystem и передаёт его в HealthAnalyzerScannedUserMessage; сообщение расширено полем TotalPain.
Локализация
Resources/Locale/en-US/.../health-analyzer-component.ftl, Resources/Locale/ru-RU/.../health-analyzer-component.ftl
Добавлены ключи для табов и текстов нервной системы/причин боли, статусов боли, кнопки помощи и ключ для состояния "болен".
Тесты и вспомогательные адаптации
Content.IntegrationTests/Tests/Backmen/Body/BodySetupTest.cs, Content.Shared/Body/Systems/SharedBloodstreamSystem.cs, Content.Shared/Mobs/Systems/MobThresholdSystem.cs
Подправлены вызовы для соответствия новым сигнатурам (tuple/Entity), добавлен ранний выход в MobThresholdSystem при наличии ConsciousnessComponent.

Sequence Diagram(s)

sequenceDiagram
    participant HealthAnalyzerSystem as HealthAnalyzerSystem
    participant ConsciousnessSystem as ConsciousnessSystem
    participant PainSystem as PainSystem
    participant ServerNet as Server/Net
    participant ClientUI as HealthAnalyzerWindow / PainCausesDisplay

    HealthAnalyzerSystem->>ConsciousnessSystem: GetPainCauses(target)
    ConsciousnessSystem->>PainSystem: Query nerve-system modifiers (if present)
    PainSystem-->>ConsciousnessSystem: Nerve-system pain causes
    ConsciousnessSystem-->>HealthAnalyzerSystem: aggregate painCauses, totalPain
    HealthAnalyzerSystem->>ServerNet: Send HealthAnalyzerScannedUserMessage(painCauses, totalPain)
    ServerNet-->>ClientUI: Deliver message
    ClientUI->>ClientUI: PainCausesDisplay.UpdatePainCauses(painCauses, totalPain, target)
    ClientUI-->>ClientUI: Render tabs, bars, help buttons
Loading

Оценка трудозатрат на код-ревью

🎯 4 (Complex) | ⏱️ ~50 минут

Стихотворение

🐰 Я кролик, с хвостиком пушистым,
В окне теперь виден нерв и боль,
Табки, бары — всё стало чистым,
Помощь найдёшь в подсказок роль.
Взмахнул лапкой — апдейт готов!

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Title check ⚠️ Warning Заголовок на русском языке не отражает основное содержание изменений. Changeset включает значительные изменения в UI, системах сознания, боли и медицинском интерфейсе, но заголовок использует неинформативное описание 'Hotfix 16.01.2026 часть 2' и неправильное объяснение 'прошлый не успел доделать'. Измените заголовок на более описательный, например: 'Refactor: Update consciousness system API and integrate PainCausesDisplay UI' или аналогичный на русском, который точнее описывает основные изменения в системе сознания и UI боли.
Docstring Coverage ⚠️ Warning Docstring coverage is 41.54% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch hotfix-160126-2


📜 Recent review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 2d5e01c and a6d8241.

📒 Files selected for processing (1)
  • Content.Shared/Chat/SharedSuicideSystem.cs
⏰ Context from checks skipped due to timeout of 300000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: Test Packaging
🔇 Additional comments (1)
Content.Shared/Chat/SharedSuicideSystem.cs (1)

101-118: Хорошо: безопасное удаление модификаторов/мультипликаторов.
Копирование ключей перед удалением предотвращает InvalidOperationException, а переход на nullable-target сохраняет совместимость с обновлённым API.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.


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.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

🤖 Fix all issues with AI agents
In `@Content.Shared/Backmen/Surgery/Consciousness/Systems/ConsciousnessSystem.cs`:
- Around line 131-132: The calls pass the wrong typed parameters: update the
MobStateSys.ChangeMobState and MobThresholds.VerifyThresholds invocations to use
the entity UID and the MobStateComponent from the wrapper. Call ChangeMobState
with target.Owner as the EntityUid (instead of target) and preserve newMobState;
call VerifyThresholds with target.Owner as the first argument and pass
target.Comp2 as the mobState parameter (instead of target).

In `@Content.Shared/Chat/SharedSuicideSystem.cs`:
- Around line 103-111: Итерация по target.Comp.Modifiers и
target.Comp.Multipliers происходит одновременно с их модификацией в методах
RemoveConsciousnessModifier/RemoveConsciousnessMultiplier, что вызывает
InvalidOperationException; перед циклами в SharedSuicideSystem.cs сделайте
защитные копии коллекций (например вызовом .ToList() или CreateArray/CopyTo) и
итерируйте по этим копиям, при этом продолжая вызывать
_consciousness.RemoveConsciousnessModifier(target.AsNullable(),
modifier.Key.Item1, modifier.Key.Item2) и
_consciousness.RemoveConsciousnessMultiplier(target.AsNullable(),
multiplier.Key.Item1, multiplier.Key.Item2).

In `@Resources/Locale/ru-RU/medical/components/health-analyzer-component.ftl`:
- Around line 26-39: The Russian translation for the key
health-analyzer-window-pain-cause-death-threshold needs a comma in the
participial phrase; update the value from "Состояние близкое к смерти" to
"Состояние, близкое к смерти" in the health-analyzer-component.ftl entry for
health-analyzer-window-pain-cause-death-threshold.
🧹 Nitpick comments (6)
Content.Shared/Backmen/Surgery/Consciousness/Systems/ConsciousnessSystem.Helpers.cs (1)

280-288: Проверьте согласованность Resolve с остальными методами.

Здесь используется Resolve без подавления логов, тогда как выше — ConsciousnessQuery.Resolve(..., false). Если Resolve пишет в лог при отсутствии компонента, это может зашумить обычные TryGet. Стоит привести к единому подходу.

♻️ Возможная правка для унификации резолва
-        if (!Resolve(target, ref target.Comp) ||
+        if (!ConsciousnessQuery.Resolve(target, ref target.Comp, false) ||
             !target.Comp.Multipliers.TryGetValue((multiplierOwner, identifier), out var rawMultiplier))
             return false;
Content.Server/Medical/HealthAnalyzerSystem.cs (1)

4-5: Обнаружены дублирующиеся импорты.

В файле присутствуют повторяющиеся директивы using:

  • Content.Shared.Body.Components (строки 4, 9, 31)
  • Content.Shared.Chemistry.EntitySystems (строки 5, 10)
  • Content.Shared.Traits.Assorted (строки 23, 32)
🔧 Предлагаемое исправление
 using Content.Server.Medical.Components;
 using Content.Server.Temperature.Components;
 using Content.Shared.Backmen.Targeting;
 using Content.Shared.Body.Components;
 using Content.Shared.Chemistry.EntitySystems;
 using Content.Shared.Body.Part;
 using Content.Shared.Body.Systems;
 using Content.Shared.Damage;
-using Content.Shared.Body.Components;
-using Content.Shared.Chemistry.EntitySystems;
 using Content.Shared.Damage.Components;
 using Content.Shared.DoAfter;
 using Content.Shared.IdentityManagement;
 using Content.Shared.Interaction;
 using Content.Shared.Interaction.Events;
 using Content.Shared.Item.ItemToggle;
 using Content.Shared.Item.ItemToggle.Components;
 using Content.Shared.MedicalScanner;
 using Content.Shared.Mobs.Components;
 using Content.Shared.Popups;
 using Content.Shared.PowerCell;
 using Content.Shared.Temperature.Components;
 using Content.Shared.Traits.Assorted;
 using Robust.Server.GameObjects;
 using Robust.Shared.Audio.Systems;
 using Robust.Shared.Containers;
 using Robust.Shared.Timing;
 using System.Linq;
 using Content.Shared.Backmen.Surgery.Wounds;
 using Content.Shared.Backmen.Surgery.Wounds.Systems;
-using Content.Shared.Body.Components;
-using Content.Shared.Traits.Assorted;
 using Content.Server.Body.Systems;
 using Content.Server.Backmen.Surgery.Consciousness.Systems;

Also applies to: 9-10, 31-32

Content.Shared/Chat/SharedSuicideSystem.cs (1)

1-8: Дублирующийся импорт System.Linq.

using System.Linq; объявлен дважды — на строках 1 и 8.

♻️ Предлагаемое исправление
 using System.Linq;
 using Content.Shared.Damage;
 using Content.Shared.Damage.Components;
 using Content.Shared.Damage.Prototypes;
 using Content.Shared.Damage.Systems;
 using Content.Shared.Mobs.Components;
 using Robust.Shared.Prototypes;
-using System.Linq;
 using Content.Shared.Backmen.Surgery.Consciousness;
Content.Client/Backmen/Medical/UI/PainCausesDisplay.xaml.cs (2)

88-110: Дублирование кода очистки дочерних элементов.

Блоки кода на строках 94-98 и 105-109 идентичны. Рекомендуется вынести в отдельный метод или объединить логику.

♻️ Предлагаемое исправление
+        // Очистка прямых дочерних элементов (кроме PainTabs)
+        var directChildren = RootContainer.Children.Where(c => c != PainTabs).ToList();
+        foreach (var child in directChildren)
+        {
+            RootContainer.RemoveChild(child);
+        }
+
         // Show tabs only if we have both types of data, otherwise show directly in RootContainer
         if (hasNerveSystemPain && hasBodyPainCauses)
         {
             PainTabs.Visible = true;
             PainTabs.SetTabTitle(0, Loc.GetString("health-analyzer-window-tab-nerve-system-pain"));
             PainTabs.SetTabTitle(1, Loc.GetString("health-analyzer-window-tab-body-pain-causes"));
-            // Clear RootContainer from direct children (when using tabs, content goes into tabs, not RootContainer)
-            var directChildren = RootContainer.Children.Where(c => c != PainTabs).ToList();
-            foreach (var child in directChildren)
-            {
-                RootContainer.RemoveChild(child);
-            }
         }
         else
         {
             PainTabs.Visible = false;
-            // Clear RootContainer from direct children (when not using tabs, we'll add content directly)
-            // But keep PainTabs in the tree (it's part of XAML structure)
-            var directChildren = RootContainer.Children.Where(c => c != PainTabs).ToList();
-            foreach (var child in directChildren)
-            {
-                RootContainer.RemoveChild(child);
-            }
         }

383-394: Все случаи возвращают одинаковое значение.

Метод GetTreatmentGuideId возвращает "MedicalDoctor" для всех известных идентификаторов. Можно упростить логику или оставить комментарий о планах на расширение.

♻️ Упрощённый вариант (если расширение не планируется)
     private ProtoId<GuideEntryPrototype>? GetTreatmentGuideId(string identifier)
     {
-        return identifier switch
-        {
-            "WoundPain" => "MedicalDoctor",
-            "Suffocation" => "MedicalDoctor",
-            "Bloodloss" => "MedicalDoctor",
-            "DeathThreshold" => "MedicalDoctor",
-            "Suicide" => "MedicalDoctor",
-            _ => null,
-        };
+        // TODO: Добавить специфичные гайды для разных причин боли
+        var knownCauses = new[] { "WoundPain", "Suffocation", "Bloodloss", "DeathThreshold", "Suicide" };
+        return knownCauses.Contains(identifier) ? "MedicalDoctor" : null;
     }
Content.Server/Medical/DefibrillatorSystem.cs (1)

240-291: Уберите дублирующее снятие модификаторов (если не нужно дважды).
Suffocation и DeathThreshold снимаются и до, и после ForcePassOut, что выглядит избыточно и усложняет чтение.

♻️ Предлагаемое упрощение
-                    _consciousness.ForcePassOut(entConsciousness, TimeSpan.FromSeconds(10));
-                    _consciousness.RemoveConsciousnessModifier(entConsciousness, target, "DeathThreshold");
-                    _consciousness.RemoveConsciousnessModifier(entConsciousness, nerveSys.Value, "Suffocation");
+                    _consciousness.ForcePassOut(entConsciousness, TimeSpan.FromSeconds(10));
📜 Review details

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Knowledge base: Disabled due to Reviews -> Disable Knowledge Base setting

📥 Commits

Reviewing files that changed from the base of the PR and between 1daf554 and be9bb5e.

📒 Files selected for processing (19)
  • Content.Client/Backmen/Medical/UI/PainCausesDisplay.xaml
  • Content.Client/Backmen/Medical/UI/PainCausesDisplay.xaml.cs
  • Content.Client/HealthAnalyzer/UI/HealthAnalyzerWindow.xaml
  • Content.Client/HealthAnalyzer/UI/HealthAnalyzerWindow.xaml.cs
  • Content.IntegrationTests/Tests/Backmen/Body/BodySetupTest.cs
  • Content.Server/Backmen/Surgery/Consciousness/Systems/ServerConsciousnessSystem.cs
  • Content.Server/Medical/DefibrillatorSystem.cs
  • Content.Server/Medical/HealthAnalyzerSystem.cs
  • Content.Shared/Backmen/EntityEffects/Effects/AdjustConsciousness.cs
  • Content.Shared/Backmen/EntityEffects/Effects/AdjustPainFeels.cs
  • Content.Shared/Backmen/EntityEffects/Effects/SuppressPain.cs
  • Content.Shared/Backmen/Surgery/Consciousness/Systems/ConsciousnessSystem.Helpers.cs
  • Content.Shared/Backmen/Surgery/Consciousness/Systems/ConsciousnessSystem.cs
  • Content.Shared/Body/Systems/SharedBloodstreamSystem.cs
  • Content.Shared/Chat/SharedSuicideSystem.cs
  • Content.Shared/MedicalScanner/HealthAnalyzerScannedUserMessage.cs
  • Content.Shared/Mobs/Systems/MobThresholdSystem.cs
  • Resources/Locale/en-US/medical/components/health-analyzer-component.ftl
  • Resources/Locale/ru-RU/medical/components/health-analyzer-component.ftl
🧰 Additional context used
🧬 Code graph analysis (4)
Content.Shared/Mobs/Systems/MobThresholdSystem.cs (1)
Content.IntegrationTests/Tests/Interaction/InteractionTest.Helpers.cs (1)
  • HasComp (1046-1053)
Content.Client/Backmen/Medical/UI/PainCausesDisplay.xaml.cs (1)
Content.Shared/Backmen/Surgery/Consciousness/Systems/ConsciousnessSystem.Helpers.cs (1)
  • ConsciousnessSystem (10-312)
Content.Shared/Backmen/EntityEffects/Effects/AdjustConsciousness.cs (2)
Content.Shared/Backmen/EntityEffects/Effects/AdjustPainFeels.cs (1)
  • Effect (22-56)
Content.Shared/Backmen/EntityEffects/Effects/SuppressPain.cs (1)
  • Effect (22-52)
Content.Shared/Backmen/Surgery/Consciousness/Systems/ConsciousnessSystem.cs (1)
Content.Shared/Mobs/Systems/MobThresholdSystem.cs (1)
  • VerifyThresholds (355-370)
⏰ Context from checks skipped due to timeout of 300000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: Test Packaging
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (54)
Content.Shared/Mobs/Systems/MobThresholdSystem.cs (1)

486-490: Проверьте, что наличие ConsciousnessComponent всегда должно полностью обходить пороги.
Ранний return теперь пропускает CheckThresholds, сетевое событие и UpdateAlerts. Это безопасно только если все сущности с ConsciousnessComponent целиком управляются системой сознания (и их алерты/состояния обновляются через ConsciousnessChangedEvent). Убедитесь, что нет кейсов, где такие сущности всё ещё должны умирать/обновляться по урону.

Content.Shared/Backmen/EntityEffects/Effects/AdjustPainFeels.cs (1)

26-27: Корректный переход на owner для поиска нервной системы.

Смена контекста выглядит согласованной с новым API и не меняет последующую логику.

Content.Shared/Backmen/EntityEffects/Effects/SuppressPain.cs (1)

26-27: ОК: поиск нервной системы через owner.

Контекст цели теперь соответствует обновлённой сигнатуре.

Content.Shared/Backmen/Surgery/Consciousness/Systems/ConsciousnessSystem.Helpers.cs (6)

33-45: ОК: TryGetNerveSystem переведён на Entity<ConsciousnessComponent?>.

Логика резолва и возврата нервной системы выглядит согласованной.


54-58: ОК: CheckConscious работает с композитной целью.

Проверка через Resolve/Comp1 выглядит корректной для новой сигнатуры.


67-69: Единый target‑wrapper в публичных методах.

Сигнатуры ForcePassOut/ForceConscious/ClearForceEffects унифицированы и выглядят согласованно.

Also applies to: 82-84, 94-95


110-118: ОК: перечисление модификаторов и мультипликаторов через target.Comp.

Единый способ резолва повышает предсказуемость API.

Also applies to: 129-136


154-160: Сигнатуры модификаторов/мультипликаторов унифицированы.

Переход на Entity<ConsciousnessComponent?> выглядит консистентно по всему публичному API.

Also applies to: 197-200, 216-222, 237-242, 259-265, 303-305


175-183: ОК: TryGetConsciousnessModifier использует target.Comp.

Логика поиска модификатора читаема и соответствует новой модели.

Content.IntegrationTests/Tests/Backmen/Body/BodySetupTest.cs (1)

196-196: ОК: вызов CheckConscious приведён к новой сигнатуре.

Тест теперь использует композитную цель и выглядит корректно.

Content.Shared/Body/Systems/SharedBloodstreamSystem.cs (1)

178-179: ОК: вызов TryGetNerveSystem использует композитную цель.

Смена аргумента соответствует обновлённой сигнатуре.

Content.Server/Medical/HealthAnalyzerSystem.cs (1)

279-293: LGTM!

Добавление totalPain через _consciousnessSystem.GetTotalPain(target) корректно интегрируется с обновлённой сигнатурой HealthAnalyzerScannedUserMessage. Логика передачи данных в UI выглядит правильно.

Content.Client/Backmen/Medical/UI/PainCausesDisplay.xaml (1)

1-15: LGTM!

Структура XAML-компонента корректна. Вертикальная компоновка с TabContainer для разделения отображения нервной системы и причин боли тела — логичное решение. Контейнеры будут заполняться динамически через code-behind.

Content.Client/HealthAnalyzer/UI/HealthAnalyzerWindow.xaml (2)

4-5: LGTM!

Добавление пространства имён backmen и увеличение MaxHeight до 565 корректно для интеграции нового компонента отображения боли.


232-238: LGTM!

Интеграция PainCausesDisplay вместо ручного построения UI для причин боли — хороший рефакторинг. Компонент инициализируется скрытым (Visible="False") и будет показан программно при наличии данных.

Content.Shared/Backmen/EntityEffects/Effects/AdjustConsciousness.cs (2)

20-21: LGTM!

Использование entity.Owner вместо entity для TryGetNerveSystem согласуется с паттерном в аналогичных файлах (AdjustPainFeels.cs, SuppressPain.cs). Это обеспечивает получение корректного EntityUid из обёртки Entity<MobStateComponent>.


25-42: LGTM!

Изменения в вызовах ChangeConsciousnessModifier и AddConsciousnessModifier с entity на entity.Owner корректны и согласуются с обновлённым API системы сознания.

Content.Client/HealthAnalyzer/UI/HealthAnalyzerWindow.xaml.cs (4)

12-12: LGTM!

Добавленные директивы using необходимы для новой функциональности: Content.Shared.Backmen.Disease для компонента болезни и Robust.Shared.Maths для математических операций.

Also applies to: 30-30


280-291: LGTM!

Логика отображения причин боли упрощена использованием компонента PainCausesDisplay. Условие showPainCauses корректно проверяет наличие причин боли или общего значения боли перед отображением секции.


295-296: Корректное добавление проверки болезни.

Проверка hasDisease через DiseasedComponent интегрирована в условие showAlerts, что соответствует существующему паттерну для других предупреждений.


326-337: Ключ локализации определён корректно.

Ключ health-analyzer-window-entity-diseased-text присутствует в файлах ресурсов en-US.ftl и ru-RU.ftl.

Content.Shared/Chat/SharedSuicideSystem.cs (1)

113-114: LGTM!

Логика добавления модификатора и мультипликатора для суицида корректна — устанавливается отрицательный модификатор равный Cap и нулевой мультипликатор для гарантированной смерти сознания.

Content.Shared/MedicalScanner/HealthAnalyzerScannedUserMessage.cs (1)

22-35: LGTM!

Добавление TotalPain как опционального поля корректно реализовано: параметр конструктора имеет значение по умолчанию null, что обеспечивает обратную совместимость.

Content.Client/Backmen/Medical/UI/PainCausesDisplay.xaml.cs (1)

419-444: LGTM!

Логика интерполяции цветов для индикатора боли реализована корректно с плавными переходами между порогами.

Content.Shared/Backmen/Surgery/Consciousness/Systems/ConsciousnessSystem.cs (2)

44-64: LGTM!

Миграция на Entity<ConsciousnessComponent?> выполнена корректно. Использование uid.Comp для доступа к компоненту и вызов Dirty(uid) соответствуют паттерну ECS.


135-167: LGTM!

Метод CheckRequiredParts корректно обрабатывает требуемые части тела и устанавливает флаги ForceDead/ForceUnconscious. Вызов AsNullable() на строке 166 согласован с обновлённой сигнатурой CheckConscious.

Resources/Locale/en-US/medical/components/health-analyzer-component.ftl (1)

28-43: LGTM!

Локализационные строки корректно добавлены и соответствуют ключам, используемым в PainCausesDisplay.xaml.cs. Цветовая кодировка статусов боли логична и последовательна.

Resources/Locale/ru-RU/medical/components/health-analyzer-component.ftl (2)

17-17: Хорошее добавление статуса заражения.
Текст читаемый и консистентен с остальными статусами.


41-41: Локализация кнопки помощи ок.

Content.Server/Backmen/Surgery/Consciousness/Systems/ServerConsciousnessSystem.cs (25)

12-12: Импорт PainSystem добавлен корректно.


46-46: DI для PainSystem выглядит правильно.


57-57: Подписка на MapInit для первичной синхронизации — ок.


187-206: Переход на AsNullable в обработчике смерти — ок.


209-222: Проверка модификатора через AsNullable согласована с новым API.


261-271: TryGetNerveSystem через AsNullable — корректно.


370-380: CPR: обновление Suffocation через wrapper — ок.


419-437: Rejuvenate: очистка pain‑модификаторов и форс‑сознания — ок.


439-467: Обработка asphyxiation‑урона с AsNullable выглядит корректно.


473-530: После изменений частей тела требования пересчитываются сразу — хорошо.


532-539: Инициализация RawConsciousness защищает от нулевого значения — ок.


541-544: Проверка сознания на MapInit — ок.


550-588: В Update переход на wrapper‑вызовы выглядит корректно.


595-609: CheckConscious с композитной целью обновлён корректно.


614-625: ForcePassOut через Entity<ConsciousnessComponent?> — ок.


628-639: ForceConscious через Entity<ConsciousnessComponent?> — ок.


642-652: ClearForceEffects обновлён под новый target‑wrapper — ок.


659-675: AddConsciousnessModifier с обновлением/dirty — ок.


680-692: RemoveConsciousnessModifier обновлён корректно.


697-712: SetConsciousnessModifier с nullable‑target выглядит корректно.


717-734: ChangeConsciousnessModifier обновлён под новый API — ок.


739-757: AddConsciousnessMultiplier: пересчёты и dirty — ок.


762-776: RemoveConsciousnessMultiplier: пересчёты и dirty — ок.


784-796: GetTotalPain добавлен аккуратно.


804-860: Агрегация причин боли из двух источников выглядит корректно.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Comment on lines +131 to +132
MobStateSys.ChangeMobState(target, newMobState, target);
MobThresholds.VerifyThresholds(target, mobState: target);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

# Find the VerifyThresholds method signature
rg -n "public.*VerifyThresholds" --type cs -A 5

Repository: Rxup/space-station-14

Length of output: 686


🏁 Script executed:

# Check for implicit conversion operators from Entity<T1, T2>
rg -n "public static implicit operator" --type cs | grep -i entity

Repository: Rxup/space-station-14

Length of output: 889


🏁 Script executed:

# Also search for any Entity type definition with implicit operators
rg -n "implicit operator" --type cs -B 2 -A 3 | head -100

Repository: Rxup/space-station-14

Length of output: 7680


🏁 Script executed:

# Find Entity type definition
fd -e cs -x grep -l "struct Entity<" {} \;

Repository: Rxup/space-station-14

Length of output: 47


🏁 Script executed:

# Search for Entity<T1, T2> definition and implicit operators
rg -n "struct Entity<" --type cs -A 20 | head -100

Repository: Rxup/space-station-14

Length of output: 47


🏁 Script executed:

# Search specifically for implicit operator that might convert Entity to component
rg -n "implicit operator.*Entity<" --type cs

Repository: Rxup/space-station-14

Length of output: 47


🏁 Script executed:

# Read the ConsciousnessSystem.cs file around lines 131-132
cat -n Content.Shared/Backmen/Surgery/Consciousness/Systems/ConsciousnessSystem.cs | sed -n '120,145p'

Repository: Rxup/space-station-14

Length of output: 1008


🏁 Script executed:

# Search for Entity definition more broadly
rg -n "type Entity" --type cs | head -20

Repository: Rxup/space-station-14

Length of output: 47


🏁 Script executed:

# Find where Entity<T1, T2> is used to understand its structure
rg -n "Entity<.*,.*>" --type cs -A 2 | head -60

Repository: Rxup/space-station-14

Length of output: 5429


🏁 Script executed:

# Find Entity struct definition in shared code
fd -e cs -path "*/Shared/*" -x grep -l "struct Entity<" {} \;

Repository: Rxup/space-station-14

Length of output: 233


🏁 Script executed:

# Search more broadly for Entity struct
rg -n "struct Entity<" --type cs

Repository: Rxup/space-station-14

Length of output: 47


🏁 Script executed:

# Search for Entity without generics to find the core definition
rg -n "public struct Entity" --type cs -A 10

Repository: Rxup/space-station-14

Length of output: 47


🏁 Script executed:

# Search for Entity definition with different patterns
rg -n "struct Entity\s*\{" --type cs -A 5

Repository: Rxup/space-station-14

Length of output: 47


🏁 Script executed:

# Look for implicit operator from Entity to EntityUid
rg -n "implicit operator EntityUid" --type cs -B 2 -A 5

Repository: Rxup/space-station-14

Length of output: 47


🏁 Script executed:

# Search for Entity in Robust.Shared namespace
rg -n "Entity\s+Owner" --type cs | head -20

Repository: Rxup/space-station-14

Length of output: 517


🏁 Script executed:

# Look at what can be passed to EntityUid parameter - check ChangeMobState first
rg -n "public.*ChangeMobState" --type cs -A 3

Repository: Rxup/space-station-14

Length of output: 517


🏁 Script executed:

# Search for files that might contain Entity definition
fd -type f -name "*.cs" | xargs grep -l "public struct Entity.*Owner" | head -10

Repository: Rxup/space-station-14

Length of output: 235


🏁 Script executed:

# Look at imports in ConsciousnessSystem to understand Entity
head -20 Content.Shared/Backmen/Surgery/Consciousness/Systems/ConsciousnessSystem.cs

Repository: Rxup/space-station-14

Length of output: 777


🏁 Script executed:

# Search for Entity in relation to EntityUid more broadly
rg -n "\.Owner" --type cs -A 1 | grep -E "(Entity|EntityUid)" | head -30

Repository: Rxup/space-station-14

Length of output: 3815


🏁 Script executed:

# Look for Comp1, Comp2 pattern to understand Entity structure
rg -n "\.Comp1|\.Comp2" --type cs | head -20

Repository: Rxup/space-station-14

Length of output: 2672


🏁 Script executed:

# Search for implicit operator conversions on Entity type
rg -n "implicit operator" --type cs | grep -i "entity"

Repository: Rxup/space-station-14

Length of output: 889


🏁 Script executed:

# Look for Entity definition in Robust.Shared or similar
find . -name "*.cs" -type f -exec grep -l "public struct Entity" {} \; | head -5

Repository: Rxup/space-station-14

Length of output: 47


🏁 Script executed:

# Check if Entity is used with .Owner property elsewhere to understand the pattern
rg -n "\.Owner" Content.Shared/Backmen/ --type cs | head -20

Repository: Rxup/space-station-14

Length of output: 2686


🏁 Script executed:

# Look at other calls to VerifyThresholds to see how they pass parameters
rg -n "VerifyThresholds(" --type cs -B 2 -A 2 | head -40

Repository: Rxup/space-station-14

Length of output: 149


🏁 Script executed:

# Check ChangeMobState calls to see the proper parameter pattern
rg -n "ChangeMobState(" --type cs -B 2 -A 2 | head -40

Repository: Rxup/space-station-14

Length of output: 145


🏁 Script executed:

# Search for VerifyThresholds calls with proper escaping
rg -n "VerifyThresholds" --type cs -B 2 -A 2 | head -60

Repository: Rxup/space-station-14

Length of output: 2778


🏁 Script executed:

# Search for ChangeMobState calls
rg -n "ChangeMobState" --type cs -B 2 -A 2 | head -60

Repository: Rxup/space-station-14

Length of output: 4997


Исправьте передачу параметров типов.

Метод ChangeMobState ожидает EntityUid, но передаётся target типа Entity<ConsciousnessComponent?, MobStateComponent?>. Используйте target.Owner (line 131).

Метод VerifyThresholds ожидает EntityUid для первого параметра и MobStateComponent? для параметра mobState, но передаётся target целиком. Используйте target.Owner для первого параметра и target.Comp2 для параметра mobState (line 132).

Текущий код
        MobStateSys.ChangeMobState(target, newMobState, target);
        MobThresholds.VerifyThresholds(target, mobState: target);
🤖 Prompt for AI Agents
In `@Content.Shared/Backmen/Surgery/Consciousness/Systems/ConsciousnessSystem.cs`
around lines 131 - 132, The calls pass the wrong typed parameters: update the
MobStateSys.ChangeMobState and MobThresholds.VerifyThresholds invocations to use
the entity UID and the MobStateComponent from the wrapper. Call ChangeMobState
with target.Owner as the EntityUid (instead of target) and preserve newMobState;
call VerifyThresholds with target.Owner as the first argument and pass
target.Comp2 as the mobState parameter (instead of target).

Comment on lines +26 to +39
health-analyzer-window-tab-nerve-system-pain = Нервная система
health-analyzer-window-tab-body-pain-causes = Причины боли тела
health-analyzer-window-nerve-system-pain-text = Боль нервной системы:
health-analyzer-window-total-pain-from-causes-text = Общая боль от всех причин:
health-analyzer-window-pain-status-none = [color=green]Нет[/color]
health-analyzer-window-pain-status-low = [color=yellow]Низкая[/color]
health-analyzer-window-pain-status-moderate = [color=orange]Умеренная[/color]
health-analyzer-window-pain-status-critical = [color=red]Критическая[/color]
health-analyzer-window-pain-status-fatal = [color=darkred]Смертельная[/color]
health-analyzer-window-pain-cause-wound-pain = Физическая травма (Раны)
health-analyzer-window-pain-cause-suffocation = Кислородное голодание
health-analyzer-window-pain-cause-bloodloss = Кровопотеря
health-analyzer-window-pain-cause-death-threshold = Порог смерти
health-analyzer-window-pain-cause-suicide = Самоубийство
health-analyzer-window-pain-cause-death-threshold = Состояние близкое к смерти
health-analyzer-window-pain-cause-suicide = Самоповреждение
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Поправьте пунктуацию в переводе про порог смерти.
Нужна запятая в обособленном обороте.

✏️ Предлагаемая правка
-health-analyzer-window-pain-cause-death-threshold = Состояние близкое к смерти
+health-analyzer-window-pain-cause-death-threshold = Состояние, близкое к смерти
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
health-analyzer-window-tab-nerve-system-pain = Нервная система
health-analyzer-window-tab-body-pain-causes = Причины боли тела
health-analyzer-window-nerve-system-pain-text = Боль нервной системы:
health-analyzer-window-total-pain-from-causes-text = Общая боль от всех причин:
health-analyzer-window-pain-status-none = [color=green]Нет[/color]
health-analyzer-window-pain-status-low = [color=yellow]Низкая[/color]
health-analyzer-window-pain-status-moderate = [color=orange]Умеренная[/color]
health-analyzer-window-pain-status-critical = [color=red]Критическая[/color]
health-analyzer-window-pain-status-fatal = [color=darkred]Смертельная[/color]
health-analyzer-window-pain-cause-wound-pain = Физическая травма (Раны)
health-analyzer-window-pain-cause-suffocation = Кислородное голодание
health-analyzer-window-pain-cause-bloodloss = Кровопотеря
health-analyzer-window-pain-cause-death-threshold = Порог смерти
health-analyzer-window-pain-cause-suicide = Самоубийство
health-analyzer-window-pain-cause-death-threshold = Состояние близкое к смерти
health-analyzer-window-pain-cause-suicide = Самоповреждение
health-analyzer-window-tab-nerve-system-pain = Нервная система
health-analyzer-window-tab-body-pain-causes = Причины боли тела
health-analyzer-window-nerve-system-pain-text = Боль нервной системы:
health-analyzer-window-total-pain-from-causes-text = Общая боль от всех причин:
health-analyzer-window-pain-status-none = [color=green]Нет[/color]
health-analyzer-window-pain-status-low = [color=yellow]Низкая[/color]
health-analyzer-window-pain-status-moderate = [color=orange]Умеренная[/color]
health-analyzer-window-pain-status-critical = [color=red]Критическая[/color]
health-analyzer-window-pain-status-fatal = [color=darkred]Смертельная[/color]
health-analyzer-window-pain-cause-wound-pain = Физическая травма (Раны)
health-analyzer-window-pain-cause-suffocation = Кислородное голодание
health-analyzer-window-pain-cause-bloodloss = Кровопотеря
health-analyzer-window-pain-cause-death-threshold = Состояние, близкое к смерти
health-analyzer-window-pain-cause-suicide = Самоповреждение
🤖 Prompt for AI Agents
In `@Resources/Locale/ru-RU/medical/components/health-analyzer-component.ftl`
around lines 26 - 39, The Russian translation for the key
health-analyzer-window-pain-cause-death-threshold needs a comma in the
participial phrase; update the value from "Состояние близкое к смерти" to
"Состояние, близкое к смерти" in the health-analyzer-component.ftl entry for
health-analyzer-window-pain-cause-death-threshold.

@Rxup Rxup merged commit ec37d3c into master Jan 16, 2026
13 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Changes: Localization Can be reviewed or fixed by people who are knowledgeable with translation Changes: UI Can be reviewed or fixed by people who are knowledgeable with UI design S: Untriaged size/L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant