Compare commits

...
5 Commits
7 changed files with 392 additions and 158 deletions

No files matched your search

+6
View File
@@ -244,3 +244,9 @@ pullRequests:
enabled: false
summary:
enabled: false
issueLink:
enabled: true
commentAnchor: pull-bot:issue-link
appendCloseKeyword: true
closeKeywordTemplate: "close #{number}"
requireSameRepository: true
+35 -36
View File
@@ -1,4 +1,5 @@
name: Repo Bot
run-name: "Repo Bot #${{ github.event.issue.number || github.event.pull_request.number }} - ${{ github.event_name }}/${{ github.event.action }} - @${{ github.actor }}"
on:
issues:
@@ -11,45 +12,43 @@ on:
types:
- created
- edited
# pull_request_target (not pull_request) is required so that pull requests opened from
# forks can be labelled/commented. Never check out or execute the pull request head here.
pull_request_target:
types:
- opened
- edited
- synchronize
- reopened
- ready_for_review
jobs:
repo-bot:
runs-on: ubuntu-latest
if: >-
github.event.sender.type != 'Bot' &&
(
github.event_name != 'issue_comment' ||
contains(github.event.comment.body, '/fix') ||
contains(github.event.comment.body, '/refresh')
)
uses: ddaodan/bettergi-github-bot/.github/workflows/repo-bot.yml@v1
permissions:
issues: write
pull-requests: write
contents: read
steps:
- name: Detect GitHub App configuration
id: auth-mode
shell: bash
env:
REPO_BOT_GITHUB_APP_ID: ${{ vars.REPO_BOT_GITHUB_APP_ID }}
REPO_BOT_GITHUB_APP_PRIVATE_KEY: ${{ secrets.REPO_BOT_GITHUB_APP_PRIVATE_KEY }}
run: |
if [ -n "$REPO_BOT_GITHUB_APP_ID" ] && [ -n "$REPO_BOT_GITHUB_APP_PRIVATE_KEY" ]; then
echo "use_app=true" >> "$GITHUB_OUTPUT"
else
echo "use_app=false" >> "$GITHUB_OUTPUT"
fi
- name: Checkout repository
uses: actions/checkout@v4
- name: Create GitHub App token
if: ${{ steps.auth-mode.outputs.use_app == 'true' }}
id: app-token
uses: actions/create-github-app-token@v3
with:
app-id: ${{ vars.REPO_BOT_GITHUB_APP_ID }}
private-key: ${{ secrets.REPO_BOT_GITHUB_APP_PRIVATE_KEY }}
- name: Run Repo Bot
uses: ddaodan/bettergi-github-bot@v1
env:
GITHUB_TOKEN: ${{ github.token }}
REPO_BOT_GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
REPO_BOT_AI_API_KEY: ${{ secrets.REPO_BOT_AI_API_KEY }}
REPO_BOT_AI_BASE_URL: ${{ vars.REPO_BOT_AI_BASE_URL }}
with:
config-path: .github/repo-bot.yml
config-overrides-json: ${{ vars.REPO_BOT_CONFIG_OVERRIDES_JSON }}
secrets:
REPO_BOT_AI_API_KEY: ${{ secrets.REPO_BOT_AI_API_KEY }}
REPO_BOT_GITHUB_APP_PRIVATE_KEY: ${{ secrets.REPO_BOT_GITHUB_APP_PRIVATE_KEY }}
with:
config-path: .github/repo-bot.yml
# pull_request_target: only fetch the configuration from the base branch.
# Never check out the pull request head (it would execute untrusted code).
checkout-mode: config-only
config-overrides-json: ${{ vars.REPO_BOT_CONFIG_OVERRIDES_JSON }}
ai-enabled: ${{ vars.REPO_BOT_AI_ENABLED }}
ai-base-url: ${{ vars.REPO_BOT_AI_BASE_URL }}
ai-model: ${{ vars.REPO_BOT_AI_MODEL }}
ai-api-style: ${{ vars.REPO_BOT_AI_API_STYLE }}
ai-timeout-ms: ${{ vars.REPO_BOT_AI_TIMEOUT_MS }}
action-ref: v1
github-app-id: ${{ vars.REPO_BOT_GITHUB_APP_ID }}
@@ -2,7 +2,7 @@
<PropertyGroup>
<AssemblyName>BetterGI</AssemblyName>
<Version>0.66.2-alpha.2</Version>
<Version>0.66.2-alpha.4</Version>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<OutputType>WinExe</OutputType>
<TargetFramework>net8.0-windows10.0.22621.0</TargetFramework>
@@ -25,7 +25,6 @@ using Microsoft.Extensions.Logging;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Threading;
@@ -53,10 +52,6 @@ public class TpTask
private const double DefaultDisplayTpPointZoomLevel = 4.4; // 传送点显示时的默认地图比例
private const double MoonCanonDisplayTpPointZoomLevel = 3.0;
private const int DefaultBigMapOpenTimeoutMs = 5000;
private const int MoonCanonBigMapOpenTimeoutMs = 8000;
private const int UiRecognitionPollIntervalMs = 80;
private const int BigMapOpenCheckIntervalMs = UiRecognitionPollIntervalMs;
private const double TeleportMaxZoomLevel = 6.0;
private const double TeleportFinalZoomDistanceFactor = 36d;
private const double MinTeleportZoomLevel = 1.0;
@@ -85,27 +80,11 @@ public class TpTask
private const double AbsoluteMapClickNeighborErrorRatio = 0.25d;
private const double NearbyMapIconTemplateThreshold = 0.65d;
private const int MapChooseCandidateClickRetryCount = 2;
private const int MapChooseCandidateClickVerificationDelayMs = 600;
private const int MapChooseCandidateClickVerificationIntervalMs = 100;
private const double TeleportFinalZoomMinNeighborScreenDistance = 96d;
private const int TeleportClickableAreaRetryCount = 5;
private const int TeleportClickableAreaRetryDelayMs = 80;
private const int BigMapRectRetryIntervalMs = 150;
private const int MapLayerVerificationPollIntervalMs = UiRecognitionPollIntervalMs;
private const int MapGroundLayerSwitchTimeoutMs = 3000;
private const int TeleportPanelMinimumTimeoutMs = 900;
private const int TeleportPanelInitialDelayMs = 200;
private const int TeleportConfirmTimeoutMs = 5000;
private const int SwitchAreaCandidateTimeoutMs = 1500;
private const int SwitchAreaSelectionTimeoutMs = 600;
private const int SwitchAreaSelectionMinimumWaitMs = 120;
private const int SwitchAreaSelectionStableChecks = 2;
private const int TeleportTimeoutMs = 60_000;
private const int TeleportLoadingPollIntervalMs = 100;
private const int TeleportMinimumCompletionMs = 1000;
private const int TeleportLoadingStableNonUiChecks = 1;
private const int TeleportCompletionStableMainUiChecks = 1;
private const int BlessingCheckIntervalMs = 1000;
private const double MapPositionRecognitionRecoveryZoomStep = 1.0;
private static string? s_lastSuccessfulTeleportMapName;
private double _mapZoomLevelPerWheelNotch = DefaultMapZoomLevelPerWheelNotch;
@@ -948,21 +927,19 @@ public class TpTask
private async Task<bool> WaitForTeleportPanelAndConfirm(GiTpPosition? targetTp)
{
var timeoutMilliseconds = GetTeleportPanelTimeoutMilliseconds();
var initialDelayMs = GetTeleportPanelInitialDelayMilliseconds();
var configuredDelay = TaskContext.Instance().Config.QuickTeleportConfig.WaitTeleportPanelDelay;
var configuredWait = Math.Clamp(configuredDelay <= 0 ? 50 : configuredDelay, 50, 300);
var maxAttemptCount = (int)Math.Ceiling(Math.Max(900, configuredWait * 18) / 80d);
// 地图点选后,先给右侧传送面板一点弹出时间,再开始检查传送按钮 / 候选列表。
var initialDelayMs = Math.Max(200, Math.Clamp(configuredDelay, 0, 500));
if (initialDelayMs > 0)
{
await Delay(initialDelayMs, ct);
}
var stopwatch = Stopwatch.StartNew();
for (var i = 0; i == 0 || stopwatch.ElapsedMilliseconds < timeoutMilliseconds; i++)
for (var attempt = 0; attempt < maxAttemptCount; attempt++)
{
if (i > 0)
{
await Delay(UiRecognitionPollIntervalMs, ct);
}
using var teleportCapture = CaptureToRectArea();
var result = await HandleTeleportPanel(teleportCapture, targetTp);
switch (result)
@@ -976,6 +953,11 @@ public class TpTask
// 本帧既没有传送按钮也没有有效候选,继续轮询。
break;
}
if (attempt + 1 < maxAttemptCount)
{
await Delay(80, ct);
}
}
return false;
@@ -1014,33 +996,16 @@ public class TpTask
return GetDistance(targetClickX, targetClickY, nearClickX, nearClickY);
}
private static int GetTeleportPanelTimeoutMilliseconds()
{
var delay = TaskContext.Instance().Config.QuickTeleportConfig.WaitTeleportPanelDelay;
var configuredWait = Math.Clamp(delay <= 0 ? 50 : delay, 50, 300);
return Math.Max(TeleportPanelMinimumTimeoutMs, configuredWait * 18);
}
/// <summary>
/// 地图点选后,先给右侧传送面板一点弹出时间,再开始检查传送按钮 / 候选列表。
/// </summary>
private static int GetTeleportPanelInitialDelayMilliseconds()
{
var configuredDelay = TaskContext.Instance().Config.QuickTeleportConfig.WaitTeleportPanelDelay;
return Math.Max(TeleportPanelInitialDelayMs, Math.Clamp(configuredDelay, 0, 500));
}
/// <summary>
/// 检查传送是否完成,未完成则等待
/// </summary>
private async Task WaitForTeleportCompletion()
{
var stopwatch = Stopwatch.StartNew();
var observedLoadingState = false;
var consecutiveNonUiChecks = 0;
var consecutiveMainUiChecks = 0;
long nextBlessingCheckAt = BlessingCheckIntervalMs;
while (stopwatch.ElapsedMilliseconds < TeleportTimeoutMs)
var blessingCheckCountdown = 10;
for (var attempt = 0; attempt < 600; attempt++)
{
ct.ThrowIfCancellationRequested();
@@ -1052,8 +1017,8 @@ public class TpTask
{
consecutiveNonUiChecks = 0;
if (observedLoadingState &&
stopwatch.ElapsedMilliseconds >= TeleportMinimumCompletionMs &&
++consecutiveMainUiChecks >= TeleportCompletionStableMainUiChecks)
attempt >= 10 &&
++consecutiveMainUiChecks >= 1)
{
Logger.LogInformation("传送完成");
return;
@@ -1069,17 +1034,27 @@ public class TpTask
// 地图关闭后出现的黑屏、白屏或加载界面均不属于大地图和主界面。
// 必须先观察到这个中间态,避免把传送尚未开始时短暂出现的主界面误判为完成。
consecutiveNonUiChecks = isInBigMapUi ? 0 : consecutiveNonUiChecks + 1;
observedLoadingState = consecutiveNonUiChecks >= TeleportLoadingStableNonUiChecks;
observedLoadingState = consecutiveNonUiChecks >= 1;
}
}
await Delay(TeleportLoadingPollIntervalMs, ct);
if (attempt + 1 >= 600)
{
break;
}
await Delay(100, ct);
if (blessingCheckCountdown > 0)
{
blessingCheckCountdown--;
}
// 打开大地图期间推送的月卡会在传送之后直接显示,导致检测不到传送完成。
if (observedLoadingState && !isInMainUi && stopwatch.ElapsedMilliseconds >= nextBlessingCheckAt)
if (observedLoadingState && !isInMainUi && blessingCheckCountdown == 0)
{
await _blessingOfTheWelkinMoonTask.Start(ct);
ct.ThrowIfCancellationRequested();
nextBlessingCheckAt = stopwatch.ElapsedMilliseconds + BlessingCheckIntervalMs;
blessingCheckCountdown = 10;
}
}
@@ -1199,7 +1174,8 @@ public class TpTask
InputHub.Foreground.SimulateAction(GIActions.OpenMap);
await Delay(100, ct);
var opened = await WaitForBigMapUiAppear(GetBigMapOpenTimeoutMilliseconds(mapName));
var opened = await WaitForBigMapUiAppear(
string.Equals(mapName, MapTypes.MoonCanon.ToString(), StringComparison.Ordinal) ? 100 : 63);
return opened;
}
@@ -1209,17 +1185,19 @@ public class TpTask
return Bv.IsInBigMapUi(capture);
}
private async Task<bool> WaitForBigMapUiAppear(int timeoutMilliseconds)
private async Task<bool> WaitForBigMapUiAppear(int maxAttemptCount)
{
var stopwatch = Stopwatch.StartNew();
for (var i = 0; i == 0 || stopwatch.ElapsedMilliseconds < timeoutMilliseconds; i++)
for (var attempt = 0; attempt < maxAttemptCount; attempt++)
{
if (IsInBigMapUi())
{
return true;
}
await Delay(BigMapOpenCheckIntervalMs, ct);
if (attempt + 1 < maxAttemptCount)
{
await Delay(80, ct);
}
}
return false;
@@ -1637,13 +1615,6 @@ public class TpTask
: DefaultDisplayTpPointZoomLevel;
}
private static int GetBigMapOpenTimeoutMilliseconds(string? mapName)
{
return string.Equals(mapName, MapTypes.MoonCanon.ToString(), StringComparison.Ordinal)
? MoonCanonBigMapOpenTimeoutMs
: DefaultBigMapOpenTimeoutMs;
}
/// <summary>
/// 点击并移动鼠标
/// </summary>
@@ -2454,8 +2425,7 @@ public class TpTask
await Delay(50, ct);
var minCountryLocalized = this.stringLocalizer.WithCultureGet(this.cultureInfo, areaName);
var candidatesText = "";
var stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < SwitchAreaCandidateTimeoutMs)
for (var attempt = 0; attempt < 19; attempt++)
{
ct.ThrowIfCancellationRequested();
using var ra = CaptureToRectArea();
@@ -2475,7 +2445,10 @@ public class TpTask
return true;
}
await Delay(UiRecognitionPollIntervalMs, ct);
if (attempt + 1 < 19)
{
await Delay(80, ct);
}
}
Logger.LogWarning(
@@ -2490,9 +2463,8 @@ public class TpTask
string localizedAreaName,
Rect clickedCandidateRect)
{
var stopwatch = Stopwatch.StartNew();
var consecutiveMissingChecks = 0;
while (stopwatch.ElapsedMilliseconds < SwitchAreaSelectionTimeoutMs)
for (var attempt = 0; attempt < 8; attempt++)
{
ct.ThrowIfCancellationRequested();
using var capture = CaptureToRectArea();
@@ -2501,10 +2473,10 @@ public class TpTask
IsSameSwitchAreaCandidatePosition(clickedCandidateRect, candidate));
if (!clickedCandidateStillVisible &&
stopwatch.ElapsedMilliseconds >= SwitchAreaSelectionMinimumWaitMs)
attempt >= 2)
{
consecutiveMissingChecks++;
if (consecutiveMissingChecks >= SwitchAreaSelectionStableChecks)
if (consecutiveMissingChecks >= 2)
{
return;
}
@@ -2514,7 +2486,10 @@ public class TpTask
consecutiveMissingChecks = 0;
}
await Delay(UiRecognitionPollIntervalMs, ct);
if (attempt + 1 < 8)
{
await Delay(80, ct);
}
}
Logger.LogDebug("区域选择动画等待达到上限:{Country}", areaName);
@@ -2584,9 +2559,7 @@ public class TpTask
var layerSwitchClicked = false;
var groundLayerClicked = false;
// 图层按钮的出现、展开和选中都有固定时长的界面动画,不能随传送操作速度缩短。
var retryInterval = MapLayerVerificationPollIntervalMs;
var stopwatch = Stopwatch.StartNew();
while (stopwatch.ElapsedMilliseconds < MapGroundLayerSwitchTimeoutMs)
for (var attempt = 0; attempt < 38; attempt++)
{
using var capture = CaptureToRectArea();
using var groundButton = capture.Find(
@@ -2596,46 +2569,39 @@ public class TpTask
groundButton.Click();
capture.MoveTo(capture.Width / 2, capture.Height / 2);
groundLayerClicked = true;
await Delay(retryInterval, ct);
continue;
}
using var undergroundButton = capture.Find(
GetQuickTeleportRecognitionObject("MapUndergroundSwitchButton", capture));
var isUnderground = undergroundButton.IsExist();
if (groundLayerClicked)
else
{
if (!isUnderground)
using var undergroundButton = capture.Find(
GetQuickTeleportRecognitionObject("MapUndergroundSwitchButton", capture));
var isUnderground = undergroundButton.IsExist();
if (groundLayerClicked)
{
return;
if (!isUnderground)
{
return;
}
}
await Delay(retryInterval, ct);
continue;
}
if (!isUnderground)
{
if (!layerSwitchClicked && stopwatch.ElapsedMilliseconds >= MapLayerVerificationPollIntervalMs * 2)
else if (!isUnderground)
{
return;
if (!layerSwitchClicked && attempt >= 2)
{
return;
}
}
else if (!layerSwitchClicked)
{
undergroundButton.Click();
capture.MoveTo(capture.Width / 2, capture.Height / 2);
layerSwitchClicked = true;
}
await Delay(retryInterval, ct);
continue;
}
if (!layerSwitchClicked)
if (attempt + 1 < 38)
{
undergroundButton.Click();
capture.MoveTo(capture.Width / 2, capture.Height / 2);
layerSwitchClicked = true;
await Delay(retryInterval, ct);
continue;
await Delay(80, ct);
}
await Delay(retryInterval, ct);
}
Logger.LogWarning("切换到地表地图后校验超时");
@@ -2705,11 +2671,10 @@ public class TpTask
private async Task<TeleportPanelResult> WaitAndPressTeleportConfirm(GiTpPosition? targetTp)
{
var stopwatch = Stopwatch.StartNew();
long nextCandidateVerificationAt = MapChooseCandidateClickVerificationDelayMs;
for (var i = 0; i == 0 || stopwatch.ElapsedMilliseconds < TeleportConfirmTimeoutMs; i++)
var candidateVerificationCountdown = 8;
for (var attempt = 0; attempt < 63; attempt++)
{
await Delay(UiRecognitionPollIntervalMs, ct);
await Delay(80, ct);
var screen = CaptureToRectArea();
using var ownedScreen = screen;
@@ -2729,7 +2694,8 @@ public class TpTask
return TeleportPanelResult.Confirmed;
}
if (stopwatch.ElapsedMilliseconds >= nextCandidateVerificationAt)
candidateVerificationCountdown--;
if (candidateVerificationCountdown == 0)
{
// 同一截图识别一次即可;列表仍在则点击未生效(点了未激活项或点空)。
if (GetPreferredMapChooseCandidate(screen, targetTp) != null)
@@ -2737,8 +2703,7 @@ public class TpTask
return TeleportPanelResult.RetryPoint;
}
nextCandidateVerificationAt = stopwatch.ElapsedMilliseconds +
MapChooseCandidateClickVerificationIntervalMs;
candidateVerificationCountdown = 2;
}
}
@@ -0,0 +1,159 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Security;
using System.Text;
using Microsoft.Win32;
namespace BetterGenshinImpact.Service.ChildSession;
/// <summary>
/// 桌面分身的 Windows 环境预检。
///
/// 桌面分身完全依赖 Windows 自身的 RDP / Child Session 能力(WTSEnableChildSessions +
/// RDP ActiveX 的 ConnectToChildSession),BetterGI 只是唤起这个功能。
/// 当系统缺少前置条件时,RDP ActiveX 只会回报「发生内部错误」以及一个无法定位的断开原因,
/// 用户和日志都无法判断真实原因,因此在这里提前收集可读的环境结论。
/// </summary>
internal static class ChildSessionEnvironmentCheck
{
/// <summary>
/// 「仅允许 Windows Hello 登录」设置所在路径。
/// </summary>
private const string PasswordLessRegistryPath =
@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\PasswordLess\Device";
/// <summary>
/// 远程桌面主机的本机设置所在路径。
/// </summary>
private const string TerminalServerRegistryPath =
@"SYSTEM\CurrentControlSet\Control\Terminal Server";
/// <summary>
/// 远程桌面开关的组策略路径。该键存在时会覆盖本机设置。
/// </summary>
private const string TerminalServerPolicyRegistryPath =
@"SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services";
/// <summary>
/// DevicePasswordLessBuildVersion 为 2 时,系统仅允许 Windows Hello 登录。
/// 注意:该注册表值未见于微软官方文档,属于社区逆向得出的结论,
/// 因此只把 2 判定为「已开启」,其余取值一律视为未开启。
/// </summary>
private const int PasswordLessHelloOnlyValue = 2;
/// <summary>一条环境检查结论。</summary>
internal sealed record Issue(string Title, string Message);
/// <summary>
/// 收集当前系统的环境结论。读取失败(键或值不存在、无权限)时跳过该项,不抛异常。
/// </summary>
internal static IReadOnlyList<Issue> Collect()
{
var issues = new List<Issue>();
CollectRdpHostIssue(issues);
CollectPasswordLessIssue(issues);
return issues;
}
/// <summary>把结论格式化成可直接展示给用户的文本。</summary>
internal static string BuildSummary(IReadOnlyList<Issue> issues)
{
if (issues.Count == 0)
{
return string.Empty;
}
var builder = new StringBuilder();
foreach (var issue in issues)
{
if (builder.Length > 0)
{
builder.AppendLine().AppendLine();
}
builder.Append('【').Append(issue.Title).Append('】').AppendLine();
builder.Append(issue.Message);
}
return builder.ToString();
}
/// <summary>
/// 检查远程桌面主机是否被关闭。组策略中的值会覆盖本机设置,因此优先读取组策略。
/// </summary>
private static void CollectRdpHostIssue(List<Issue> issues)
{
// 组策略中的值会覆盖本机设置,因此优先读取组策略。
var policyValue = ReadInt(
RegistryHive.LocalMachine,
TerminalServerPolicyRegistryPath,
"fDenyTSConnections");
var localValue = policyValue is null
? ReadInt(RegistryHive.LocalMachine, TerminalServerRegistryPath, "fDenyTSConnections")
: null;
var denyTsConnections = policyValue ?? localValue;
if (denyTsConnections != 1)
{
return;
}
// 组策略来源时,改本机注册表没有意义,必须给出不同的修复路径。
var suggestion = policyValue is not null
? "该值由组策略下发,修改本机注册表会被组策略覆盖。"
+ "请在 gpedit.msc 的「计算机配置 - 管理模板 - Windows 组件 - 远程桌面服务 - "
+ "远程桌面会话主机 - 连接」中启用「允许用户通过使用远程桌面服务进行远程连接」,"
+ "或联系域管理员。"
: "可以尝试在管理员权限下执行:" + Environment.NewLine
+ "Set-ItemProperty -Path 'HKLM:\\SYSTEM\\CurrentControlSet\\Control\\Terminal Server' "
+ "-Name fDenyTSConnections -Value 0 -Type DWord" + Environment.NewLine
+ "Restart-Service TermService -Force";
issues.Add(new Issue(
"远程桌面主机已关闭",
$"注册表 fDenyTSConnections = 1({(policyValue is not null ? "组策略" : "本机设置")}),"
+ "本机 RDP 监听器不会启动,桌面分身可能无法建立会话。" + Environment.NewLine
+ suggestion));
}
/// <summary>
/// 检查是否开启了「仅允许 Windows Hello 登录」,该限制会让密码验证必然失败。
/// </summary>
private static void CollectPasswordLessIssue(List<Issue> issues)
{
var passwordLessVersion = ReadInt(
RegistryHive.LocalMachine,
PasswordLessRegistryPath,
"DevicePasswordLessBuildVersion");
if (passwordLessVersion != PasswordLessHelloOnlyValue)
{
return;
}
issues.Add(new Issue(
"仅允许 Windows Hello 登录",
"系统已开启「为了提高安全性,仅允许对此设备上的 Microsoft 帐户使用 Windows Hello 登录」,"
+ "此时 Microsoft 帐户在本机没有可用的密码凭据,桌面分身的登录会一直提示凭据无效,"
+ "无论输入什么密码都会失败。" + Environment.NewLine
+ "可在「设置 - 帐户 - 登录选项」中关闭该选项,然后注销并重新登录(部分情况需要重启系统)。"));
}
/// <summary>
/// 读取注册表 DWORD 值。键或值不存在、类型不符、无权限时返回 null。
/// </summary>
private static int? ReadInt(RegistryHive hive, string path, string name)
{
try
{
using var baseKey = RegistryKey.OpenBaseKey(hive, RegistryView.Registry64);
using var key = baseKey.OpenSubKey(path);
return key?.GetValue(name) as int?;
}
catch (Exception exception) when (exception is SecurityException
or UnauthorizedAccessException
or IOException)
{
return null;
}
}
}
@@ -1,8 +1,10 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
@@ -46,6 +48,7 @@ public sealed class ChildSessionService : IDisposable
private bool _statusTickInProgress;
private bool _disposed;
private string? _lastOperationMessage;
private IReadOnlyList<ChildSessionEnvironmentCheck.Issue> _environmentIssues = [];
public event EventHandler? StateChanged;
@@ -89,11 +92,25 @@ public sealed class ChildSessionService : IDisposable
set => _config.SmallWindowPosition = value;
}
/// <summary>
/// 系统是否已安装并启用 RDP Wrapper。它与桌面分身功能不兼容,界面会在启动前据此提示用户。
/// </summary>
public bool IsRdpWrapperEnabled()
{
return ChildSessionNativeMethods.IsRdpWrapperEnabled();
}
/// <summary>
/// 最近一次启动前环境预检是否发现了可能影响桌面分身的环境设置。
/// </summary>
public bool HasEnvironmentIssue => _environmentIssues.Count > 0;
/// <summary>
/// 最近一次启动前环境预检的结论文本,供界面提示与问题排查使用。
/// </summary>
public string EnvironmentIssueSummary =>
ChildSessionEnvironmentCheck.BuildSummary(_environmentIssues);
public bool HasActiveChildSession()
{
if (!_instanceService.Context.IsRoot)
@@ -125,9 +142,14 @@ public sealed class ChildSessionService : IDisposable
RefreshState();
}
/// <summary>
/// 启动桌面分身:先做一次环境预检,确保 Child Sessions 已启用,然后建立 RDP 连接并等待登录完成。
/// 已经处于已连接状态时直接返回。
/// </summary>
public async Task StartAsync()
{
ThrowIfDisposed();
RefreshEnvironmentCheck();
EnsureChildSessionsEnabled();
RefreshState();
@@ -543,6 +565,9 @@ public sealed class ChildSessionService : IDisposable
}
}
/// <summary>
/// 取当前桌面分身会话 ID;没有可用会话时抛出 <see cref="InvalidOperationException"/>。
/// </summary>
private uint GetRequiredChildSessionId()
{
var childSessionId = ChildSessionNativeMethods.TryGetChildSessionId();
@@ -554,6 +579,24 @@ public sealed class ChildSessionService : IDisposable
return childSessionId.Value;
}
/// <summary>
/// 收集 Windows 环境结论,供界面在启动前提示用户,也供失败诊断使用。
/// 这些检查全部是只读的,不会修改系统设置。
/// </summary>
public void RefreshEnvironmentCheck()
{
ThrowIfDisposed();
_environmentIssues = ChildSessionEnvironmentCheck.Collect();
foreach (var issue in _environmentIssues)
{
_logger.LogWarning(
"桌面分身环境预检:{IssueTitle}。{IssueMessage}",
issue.Title,
issue.Message);
}
}
private void EnsureChildSessionsEnabled()
{
if (!ChildSessionNativeMethods.IsChildSessionsEnabled())
@@ -786,21 +829,33 @@ public sealed class ChildSessionService : IDisposable
}
}
/// <summary>
/// 连接失败的统一收尾:「重试耗尽」与「连接超时」两条路径都经由这里附加诊断信息,
/// 再更新状态并通知订阅者。
/// </summary>
private void CompleteConnectionFailure(ChildSessionConnectionFailedEventArgs e)
{
_lastConnectionFailure = e;
// 统一在这里补充诊断,让「重试耗尽」和「连接超时」两条失败路径给出同样的信息。
var diagnosed = new ChildSessionConnectionFailedEventArgs(
$"{e.Message}{BuildFailureDiagnosis()}",
e.ErrorCode,
e.ExtendedErrorCode);
_lastConnectionFailure = diagnosed;
_autoLaunchBetterGiPending = false;
_initialConnectionRetriesRemaining = 0;
_connectionAttemptCompletionSource?.TrySetResult(false);
_logger.LogError(
"桌面分身 RDP 连接失败:{ErrorMessage},错误代码:{ErrorCode},扩展错误代码:{ExtendedErrorCode}",
e.Message,
e.ErrorCode,
e.ExtendedErrorCode);
RefreshState(e.Message);
ConnectionFailed?.Invoke(this, e);
diagnosed.Message,
diagnosed.ErrorCode,
diagnosed.ExtendedErrorCode);
RefreshState(diagnosed.Message);
ConnectionFailed?.Invoke(this, diagnosed);
}
/// <summary>
/// 构造连接超时的失败信息,并附上 RDP ActiveX 最后报告的失败原因(如果有)。
/// </summary>
private ChildSessionConnectionFailedEventArgs CreateConnectionTimeoutFailure()
{
var timeoutMessage =
@@ -821,6 +876,35 @@ public sealed class ChildSessionService : IDisposable
lastDiagnostic.ExtendedErrorCode);
}
/// <summary>
/// 连接失败后的补充诊断:报告是否存在桌面分身会话,并附上环境预检结论。
/// RDP ActiveX 自身只回报「发生内部错误」和断开原因,单独看这些信息无法定位问题。
/// </summary>
private string BuildFailureDiagnosis()
{
var builder = new StringBuilder();
if (ChildSessionNativeMethods.TryGetChildSessionId() is null)
{
builder.AppendLine().AppendLine();
builder.Append(
"诊断:当前没有可用的桌面分身会话,说明 Windows 未能建立 RDP 会话。"
+ "该状态本身无法确定原因——系统无法创建会话与凭据未通过验证都会得到这个结果,"
+ "请结合上面的 RDP ActiveX 错误信息一并判断。");
}
if (_environmentIssues.Count > 0)
{
builder.AppendLine().AppendLine();
builder.Append(ChildSessionEnvironmentCheck.BuildSummary(_environmentIssues));
}
return builder.ToString();
}
/// <summary>
/// 尝试断开 RDP 主机连接。ActiveX 正在自行断开时可能返回 COM 错误,忽略后仍继续注销 Child Session。
/// </summary>
private void TryDisconnectRdpHost()
{
try
@@ -221,6 +221,10 @@ public partial class ChildSessionWindowViewModel : ViewModel
OnPropertyChanged(nameof(TopmostButtonToolTip));
}
/// <summary>
/// 启动桌面分身的命令入口。启动前依次检查 RDP Wrapper 兼容性与环境预检结论,
/// 命中时先请用户确认;用户选择不继续则中止启动。
/// </summary>
[RelayCommand]
private async Task StartAsync()
{
@@ -240,6 +244,23 @@ public partial class ChildSessionWindowViewModel : ViewModel
}
}
if (_childSessionService.ConnectedState != 1
&& Execute(_childSessionService.RefreshEnvironmentCheck)
&& _childSessionService.HasEnvironmentIssue)
{
// 默认按钮为「是」:这些条件只是风险提示,不应该挡住本来可以连上的用户。
var result = await ThemedMessageBox.WarningAsync(
_childSessionService.EnvironmentIssueSummary
+ "\n\n检测到可能影响桌面分身的环境设置。是否仍要继续?",
"桌面分身环境检查",
MessageBoxButton.YesNo,
MessageBoxResult.Yes);
if (result != MessageBoxResult.Yes)
{
return;
}
}
_startRequested = true;
IsConnectionPromptVisible = false;