From 395b4520a5f9a959582751337f11bd8048d3f38a Mon Sep 17 00:00:00 2001 From: mlopezsegura <90263997+mlopezsegura@users.noreply.github.com> Date: Mon, 30 Nov 2026 21:30:10 +0100 Subject: [PATCH] Sessions: wait longer after boot, and one Windows user per running session After a restart, an autostart RDP session took more than 30 s to sign in (its RDP-Tcp session was there but still without a user) and was marked as failed after 20 tries. The wait is now by time: 30 s, or 2 minutes during the first 5 minutes after boot. Two sessions with the same Windows user ended up in the same Windows session, because starting reuses the RDP session the user already has; stopping either closed both. Starting a session now fails with a clear message while another running session uses the same Windows user. Both from #80. Co-Authored-By: Claude Opus 5.5 --- Core/Api/StreamSessionService.cs | 29 +++++++++ Core/Helpers/RdpSessionCreator.cs | 31 +++++++--- Services/Localization/Locales/bg.json | 1 + Services/Localization/Locales/cs.json | 1 + Services/Localization/Locales/de.json | 1 + Services/Localization/Locales/en.json | 1 + Services/Localization/Locales/en_GB.json | 1 + Services/Localization/Locales/en_US.json | 1 + Services/Localization/Locales/es.json | 1 + Services/Localization/Locales/fr.json | 1 + Services/Localization/Locales/hu.json | 1 + Services/Localization/Locales/it.json | 1 + Services/Localization/Locales/ja.json | 1 + Services/Localization/Locales/ko.json | 1 + Services/Localization/Locales/pl.json | 1 + Services/Localization/Locales/pt.json | 1 + Services/Localization/Locales/pt_BR.json | 1 + Services/Localization/Locales/ru.json | 1 + Services/Localization/Locales/sv.json | 1 + Services/Localization/Locales/tr.json | 1 + Services/Localization/Locales/uk.json | 1 + Services/Localization/Locales/vi.json | 1 + Services/Localization/Locales/zh.json | 1 + Services/Localization/Locales/zh_TW.json | 1 + .../SessionStartGuardsTests.cs | 61 +++++++++++++++++++ 25 files changed, 134 insertions(+), 9 deletions(-) create mode 100644 tests/OpenStreamMS.Tests/SessionStartGuardsTests.cs diff --git a/Core/Api/StreamSessionService.cs b/Core/Api/StreamSessionService.cs index 6fc2f3d4..bdf5ec59 100644 --- a/Core/Api/StreamSessionService.cs +++ b/Core/Api/StreamSessionService.cs @@ -493,6 +493,10 @@ public void Start(Guid id) // Dos Sunshine activos no pueden compartir puertos: el segundo no arrancaría bien. EnsurePortsAvailable(session, ActiveSessions()); + // Ni el mismo usuario de Windows: compartirían su sesión de Windows. + if (FindSameWindowsUser(session, ActiveSessions(), Environment.MachineName) is { } same) + throw new InvalidOperationException(RequestCulture.T("error.userInUse", same.Name)); + session.State = SessionState.Starting; session.ErrorMessage = null; generation = Interlocked.Increment(ref session.LifecycleGeneration); @@ -1624,6 +1628,31 @@ private static void EnsurePortsAvailable(StreamSession session, IEnumerable + /// Usuario de Windows con el que se inicia la sesión, normalizado (.\USUARIO para las + /// cuentas locales); null en la sesión local, que usa el de la consola, y sin usuario. + /// + internal static string? WindowsUserKey(StreamSession s, string machineName) + { + if (s.Local) return null; + if (s.Isolated) return $".\\{s.GetIsolatedUser()}".ToUpperInvariant(); + if (string.IsNullOrWhiteSpace(s.Username)) return null; + var domain = (s.Domain ?? "").Trim(); + if (domain is "" or "." || domain.Equals(machineName, StringComparison.OrdinalIgnoreCase)) domain = "."; + return $"{domain}\\{s.Username.Trim()}".ToUpperInvariant(); + } + + /// + /// Otra sesión de con el mismo usuario de Windows. Al arrancar, la + /// sesión RDP que ya tiene ese usuario se reutiliza: las dos acabarían en la misma sesión de + /// Windows y parar cualquiera de ellas cerraría las dos (issue #80). + /// + internal static StreamSession? FindSameWindowsUser(StreamSession session, IEnumerable others, string machineName) + { + var key = WindowsUserKey(session, machineName); + return key is null ? null : others.FirstOrDefault(o => o.Id != session.Id && WindowsUserKey(o, machineName) == key); + } + private static string PortSignature(StreamSession s) => $"{s.StreamProtocol}|{s.SunshineStreamPort}|{s.WebRtcPort}|{s.WebRtcMediaPortMin}|{s.WebRtcMediaPortMax}"; diff --git a/Core/Helpers/RdpSessionCreator.cs b/Core/Helpers/RdpSessionCreator.cs index 54557cb0..eb61450c 100644 --- a/Core/Helpers/RdpSessionCreator.cs +++ b/Core/Helpers/RdpSessionCreator.cs @@ -742,15 +742,18 @@ static void RunCmdKey(params string[] args) } /// - /// Espera hasta 30 s a que la sesion aparezca en WTS. - /// Los primeros 10 intentos exigen protocolo RDP; del 11 al 20 acepta cualquier sesion - /// no-consola (modo ampliado, por si termsrv reporta protocolo 0 brevemente). + /// Espera a que la sesion aparezca en WTS, como mucho . + /// La primera mitad exige protocolo RDP; la segunda acepta cualquier sesion no-consola + /// (modo ampliado, por si termsrv reporta protocolo 0 brevemente). /// Devuelve -1 si FreeRDP murio o la sesion no aparecio (el llamador distingue /// ambos casos consultando proc.HasExited). /// static int WaitForSession(Process proc, string username) { - for (int i = 0; i < 20; i++) + var limit = SessionWaitLimit(TimeSpan.FromMilliseconds(Environment.TickCount64)); + var waited = Stopwatch.StartNew(); + bool relaxedListed = false; + for (int i = 0; waited.Elapsed < limit; i++) { // WaitForExit con timeout: si FreeRDP muere, reaccionamos al instante // en vez de esperar a que venza el Sleep. @@ -760,27 +763,37 @@ static int WaitForSession(Process proc, string username) return -1; } - bool relaxed = i >= 10; + bool relaxed = waited.Elapsed >= limit / 2; // Solo volcamos el listado completo de sesiones en el primer intento - // y al entrar en modo ampliado — evita 20 bloques identicos en el log. + // y al entrar en modo ampliado: evita bloques identicos en el log. int newSession = FindSessionByUsername(username, rdpOnly: !relaxed, - logSessions: i == 0 || i == 10, + logSessions: i == 0 || (relaxed && !relaxedListed), activeOnly: true); + relaxedListed |= relaxed; if (newSession >= 0) { - Logger.Log($"[RDP] Sesion detectada en intento {i + 1} " + + Logger.Log($"[RDP] Sesion detectada en intento {i + 1}, a los {waited.Elapsed.TotalSeconds:0} s " + $"({(relaxed ? "modo ampliado" : "RDP")}): " + $"{newSession} (FreeRDP PID={proc.Id})"); return newSession; } - Logger.Log($"[RDP] Esperando sesion... intento {i + 1}/20"); + Logger.Log($"[RDP] Esperando sesion... {waited.Elapsed.TotalSeconds:0} s de {limit.TotalSeconds:0}"); } return -1; } + /// + /// Tiempo máximo para que aparezca la sesión: 30 s, o 2 min en los primeros 5 min tras + /// encender el equipo. Al arrancar Windows el inicio de sesión tarda mucho más (servicios + /// y perfil todavía cargando): con 30 s, las sesiones de auto-arranque fallaban tras + /// reiniciar cuando su sesión RDP ya estaba iniciando sesión (issue #80). + /// + internal static TimeSpan SessionWaitLimit(TimeSpan uptime) => + uptime < TimeSpan.FromMinutes(5) ? TimeSpan.FromMinutes(2) : TimeSpan.FromSeconds(30); + // ── Politicas de registro ───────────────────────────────────────────────── /// diff --git a/Services/Localization/Locales/bg.json b/Services/Localization/Locales/bg.json index 6069ca15..4b7d07cf 100644 --- a/Services/Localization/Locales/bg.json +++ b/Services/Localization/Locales/bg.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' не стартира навреме.", "error.compositeMemberDelete": "'{0}' е в съставната сесия '{1}'. Махнете я оттам, преди да я изтриете.", "error.compositeInUse": "'{0}' е в работеща съставна сесия.", + "error.userInUse": "'{0}' вече работи с този потребител на Windows. Две сесии с един и същ потребител биха споделяли една сесия на Windows и спирането на едната би затворило и двете. Използвайте друг потребител или изолирана сесия.", "ext.busy": "Извършва се друга операция с разширения. Изчакайте да приключи.", "ext.notFound": "Разширението '{0}' не е инсталирано.", "ext.invalidSource": "'{0}' не е валидна връзка към GitHub.", diff --git a/Services/Localization/Locales/cs.json b/Services/Localization/Locales/cs.json index 216fcc2c..fe68531b 100644 --- a/Services/Localization/Locales/cs.json +++ b/Services/Localization/Locales/cs.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' se nespustila včas.", "error.compositeMemberDelete": "'{0}' je ve složené relaci '{1}'. Před smazáním ji odtud odeberte.", "error.compositeInUse": "'{0}' je ve spuštěné složené relaci.", + "error.userInUse": "'{0}' už běží s tímto uživatelem Windows. Dvě relace se stejným uživatelem by sdílely jednu relaci Windows a zastavení jedné by ukončilo obě. Použijte jiného uživatele nebo izolovanou relaci.", "ext.busy": "Probíhá jiná operace s rozšířeními. Počkejte, až skončí.", "ext.notFound": "Rozšíření '{0}' není nainstalováno.", "ext.invalidSource": "'{0}' není platný odkaz na GitHub.", diff --git a/Services/Localization/Locales/de.json b/Services/Localization/Locales/de.json index cbfa5bba..375fa032 100644 --- a/Services/Localization/Locales/de.json +++ b/Services/Localization/Locales/de.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' ist nicht rechtzeitig gestartet.", "error.compositeMemberDelete": "'{0}' ist in der kombinierten Sitzung '{1}'. Entferne sie dort, bevor du sie löschst.", "error.compositeInUse": "'{0}' ist in einer laufenden kombinierten Sitzung.", + "error.userInUse": "'{0}' läuft bereits mit diesem Windows-Benutzer. Zwei Sitzungen mit demselben Benutzer würden sich eine Windows-Sitzung teilen, und das Beenden einer Sitzung würde beide schließen. Verwenden Sie einen anderen Benutzer oder eine isolierte Sitzung.", "ext.busy": "Ein anderer Erweiterungsvorgang läuft gerade. Warte, bis er abgeschlossen ist.", "ext.notFound": "Die Erweiterung '{0}' ist nicht installiert.", "ext.invalidSource": "'{0}' ist kein gültiger GitHub-Link.", diff --git a/Services/Localization/Locales/en.json b/Services/Localization/Locales/en.json index ac47cade..b7360584 100644 --- a/Services/Localization/Locales/en.json +++ b/Services/Localization/Locales/en.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' didn't start in time.", "error.compositeMemberDelete": "'{0}' is in the composite session '{1}'. Remove it from there before deleting it.", "error.compositeInUse": "'{0}' is in a running composite session.", + "error.userInUse": "'{0}' is already running with this Windows user. Two sessions with the same user would share one Windows session, and stopping either would close both. Use another user or an isolated session.", "ext.busy": "Another extension operation is in progress. Wait for it to finish.", "ext.notFound": "Extension '{0}' isn't installed.", "ext.invalidSource": "'{0}' isn't a valid GitHub link.", diff --git a/Services/Localization/Locales/en_GB.json b/Services/Localization/Locales/en_GB.json index c8c223eb..f418635f 100644 --- a/Services/Localization/Locales/en_GB.json +++ b/Services/Localization/Locales/en_GB.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' didn't start in time.", "error.compositeMemberDelete": "'{0}' is in the composite session '{1}'. Remove it from there before deleting it.", "error.compositeInUse": "'{0}' is in a running composite session.", + "error.userInUse": "'{0}' is already running with this Windows user. Two sessions with the same user would share one Windows session, and stopping either would close both. Use another user or an isolated session.", "ext.busy": "Another extension operation is in progress. Wait for it to finish.", "ext.notFound": "Extension '{0}' isn't installed.", "ext.invalidSource": "'{0}' isn't a valid GitHub link.", diff --git a/Services/Localization/Locales/en_US.json b/Services/Localization/Locales/en_US.json index c508de99..b94a83fc 100644 --- a/Services/Localization/Locales/en_US.json +++ b/Services/Localization/Locales/en_US.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' didn't start in time.", "error.compositeMemberDelete": "'{0}' is in the composite session '{1}'. Remove it from there before deleting it.", "error.compositeInUse": "'{0}' is in a running composite session.", + "error.userInUse": "'{0}' is already running with this Windows user. Two sessions with the same user would share one Windows session, and stopping either would close both. Use another user or an isolated session.", "ext.busy": "Another extension operation is in progress. Wait for it to finish.", "ext.notFound": "Extension '{0}' isn't installed.", "ext.invalidSource": "'{0}' isn't a valid GitHub link.", diff --git a/Services/Localization/Locales/es.json b/Services/Localization/Locales/es.json index 96e45ccb..53524691 100644 --- a/Services/Localization/Locales/es.json +++ b/Services/Localization/Locales/es.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' no arrancó a tiempo.", "error.compositeMemberDelete": "'{0}' está en la sesión compuesta '{1}'. Quítala de ella antes de borrarla.", "error.compositeInUse": "'{0}' está en una sesión compuesta en marcha.", + "error.userInUse": "'{0}' ya está en marcha con este usuario de Windows. Dos sesiones con el mismo usuario compartirían la misma sesión de Windows y parar una cerraría las dos. Usa otro usuario o una sesión aislada.", "ext.busy": "Hay otra operación de extensiones en curso. Espera a que termine.", "ext.notFound": "La extensión '{0}' no está instalada.", "ext.invalidSource": "'{0}' no es un enlace de GitHub válido.", diff --git a/Services/Localization/Locales/fr.json b/Services/Localization/Locales/fr.json index c7d8e45f..3ccf1e07 100644 --- a/Services/Localization/Locales/fr.json +++ b/Services/Localization/Locales/fr.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' n’a pas démarré à temps.", "error.compositeMemberDelete": "'{0}' fait partie de la session composée '{1}'. Retirez-la avant de la supprimer.", "error.compositeInUse": "'{0}' fait partie d’une session composée en cours.", + "error.userInUse": "'{0}' est déjà en cours avec cet utilisateur Windows. Deux sessions avec le même utilisateur partageraient la même session Windows, et arrêter l'une fermerait les deux. Utilisez un autre utilisateur ou une session isolée.", "ext.busy": "Une autre opération sur les extensions est en cours. Attendez qu'elle se termine.", "ext.notFound": "L'extension '{0}' n'est pas installée.", "ext.invalidSource": "'{0}' n'est pas un lien GitHub valide.", diff --git a/Services/Localization/Locales/hu.json b/Services/Localization/Locales/hu.json index 6f44ca00..bb4fc092 100644 --- a/Services/Localization/Locales/hu.json +++ b/Services/Localization/Locales/hu.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' nem indult el időben.", "error.compositeMemberDelete": "'{0}' szerepel a(z) '{1}' összetett munkamenetben. Törlés előtt vegye ki onnan.", "error.compositeInUse": "'{0}' egy futó összetett munkamenetben van.", + "error.userInUse": "A(z) '{0}' már fut ezzel a Windows-felhasználóval. Két munkamenet ugyanazzal a felhasználóval egy Windows-munkamenetet használna, és az egyik leállítása mindkettőt bezárná. Használjon másik felhasználót vagy elkülönített munkamenetet.", "ext.busy": "Egy másik bővítményművelet van folyamatban. Várd meg, amíg befejeződik.", "ext.notFound": "A(z) '{0}' bővítmény nincs telepítve.", "ext.invalidSource": "'{0}' nem érvényes GitHub-hivatkozás.", diff --git a/Services/Localization/Locales/it.json b/Services/Localization/Locales/it.json index 43ec084a..b73edc8b 100644 --- a/Services/Localization/Locales/it.json +++ b/Services/Localization/Locales/it.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' non si è avviata in tempo.", "error.compositeMemberDelete": "'{0}' è nella sessione composta '{1}'. Rimuovila da lì prima di eliminarla.", "error.compositeInUse": "'{0}' è in una sessione composta in esecuzione.", + "error.userInUse": "'{0}' è già in esecuzione con questo utente di Windows. Due sessioni con lo stesso utente condividerebbero la stessa sessione di Windows e fermarne una chiuderebbe entrambe. Usa un altro utente o una sessione isolata.", "ext.busy": "È in corso un'altra operazione sulle estensioni. Attendi che finisca.", "ext.notFound": "L'estensione '{0}' non è installata.", "ext.invalidSource": "'{0}' non è un link GitHub valido.", diff --git a/Services/Localization/Locales/ja.json b/Services/Localization/Locales/ja.json index 927f7801..888d2006 100644 --- a/Services/Localization/Locales/ja.json +++ b/Services/Localization/Locales/ja.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' が時間内に起動しませんでした。", "error.compositeMemberDelete": "'{0}' は合成セッション '{1}' に入っています。削除する前にそこから外してください。", "error.compositeInUse": "'{0}' は実行中の合成セッションに入っています。", + "error.userInUse": "'{0}' はこの Windows ユーザーで既に実行中です。同じユーザーの 2 つのセッションは 1 つの Windows セッションを共有し、どちらかを停止すると両方が終了します。別のユーザーか分離セッションを使用してください。", "ext.busy": "別の拡張機能の操作が進行中です。完了するまでお待ちください。", "ext.notFound": "拡張機能「{0}」はインストールされていません。", "ext.invalidSource": "「{0}」は有効な GitHub リンクではありません。", diff --git a/Services/Localization/Locales/ko.json b/Services/Localization/Locales/ko.json index 8124d5a1..2c2fe992 100644 --- a/Services/Localization/Locales/ko.json +++ b/Services/Localization/Locales/ko.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}'이(가) 제때 시작되지 않았습니다.", "error.compositeMemberDelete": "'{0}'은(는) 합성 세션 '{1}'에 있습니다. 삭제하기 전에 거기서 빼세요.", "error.compositeInUse": "'{0}'은(는) 실행 중인 합성 세션에 있습니다.", + "error.userInUse": "'{0}'이(가) 이미 이 Windows 사용자로 실행 중입니다. 같은 사용자의 두 세션은 하나의 Windows 세션을 공유하므로 하나를 중지하면 둘 다 닫힙니다. 다른 사용자나 격리된 세션을 사용하세요.", "ext.busy": "다른 확장 작업이 진행 중입니다. 완료될 때까지 기다리세요.", "ext.notFound": "확장 '{0}'이(가) 설치되어 있지 않습니다.", "ext.invalidSource": "'{0}'은(는) 유효한 GitHub 링크가 아닙니다.", diff --git a/Services/Localization/Locales/pl.json b/Services/Localization/Locales/pl.json index 16ceb206..459b1ca5 100644 --- a/Services/Localization/Locales/pl.json +++ b/Services/Localization/Locales/pl.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' nie uruchomiła się na czas.", "error.compositeMemberDelete": "'{0}' jest w sesji złożonej '{1}'. Usuń ją stamtąd przed usunięciem.", "error.compositeInUse": "'{0}' jest w uruchomionej sesji złożonej.", + "error.userInUse": "'{0}' działa już z tym użytkownikiem Windows. Dwie sesje z tym samym użytkownikiem współdzieliłyby jedną sesję Windows, a zatrzymanie jednej zamknęłoby obie. Użyj innego użytkownika lub sesji izolowanej.", "ext.busy": "Trwa inna operacja na rozszerzeniach. Poczekaj, aż się zakończy.", "ext.notFound": "Rozszerzenie '{0}' nie jest zainstalowane.", "ext.invalidSource": "'{0}' nie jest prawidłowym linkiem do GitHub.", diff --git a/Services/Localization/Locales/pt.json b/Services/Localization/Locales/pt.json index 094e1503..d5f3ff18 100644 --- a/Services/Localization/Locales/pt.json +++ b/Services/Localization/Locales/pt.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' não arrancou a tempo.", "error.compositeMemberDelete": "'{0}' está na sessão composta '{1}'. Retire-a de lá antes de a eliminar.", "error.compositeInUse": "'{0}' está numa sessão composta em execução.", + "error.userInUse": "'{0}' já está em execução com este utilizador do Windows. Duas sessões com o mesmo utilizador partilhariam a mesma sessão do Windows e parar uma fecharia as duas. Use outro utilizador ou uma sessão isolada.", "ext.busy": "Está em curso outra operação de extensões. Aguarde que termine.", "ext.notFound": "A extensão '{0}' não está instalada.", "ext.invalidSource": "'{0}' não é uma ligação do GitHub válida.", diff --git a/Services/Localization/Locales/pt_BR.json b/Services/Localization/Locales/pt_BR.json index c5529b47..34a22fa5 100644 --- a/Services/Localization/Locales/pt_BR.json +++ b/Services/Localization/Locales/pt_BR.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' não iniciou a tempo.", "error.compositeMemberDelete": "'{0}' está na sessão composta '{1}'. Remova-a de lá antes de excluí-la.", "error.compositeInUse": "'{0}' está em uma sessão composta em execução.", + "error.userInUse": "'{0}' já está em execução com este usuário do Windows. Duas sessões com o mesmo usuário compartilhariam a mesma sessão do Windows e parar uma fecharia as duas. Use outro usuário ou uma sessão isolada.", "ext.busy": "Outra operação de extensões está em andamento. Aguarde até terminar.", "ext.notFound": "A extensão '{0}' não está instalada.", "ext.invalidSource": "'{0}' não é um link do GitHub válido.", diff --git a/Services/Localization/Locales/ru.json b/Services/Localization/Locales/ru.json index c101684a..281b2c21 100644 --- a/Services/Localization/Locales/ru.json +++ b/Services/Localization/Locales/ru.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' не запустился вовремя.", "error.compositeMemberDelete": "'{0}' входит в составной сеанс '{1}'. Уберите его оттуда перед удалением.", "error.compositeInUse": "'{0}' входит в запущенный составной сеанс.", + "error.userInUse": "'{0}' уже запущен с этим пользователем Windows. Два сеанса с одним пользователем использовали бы один сеанс Windows, и остановка одного закрыла бы оба. Используйте другого пользователя или изолированный сеанс.", "ext.busy": "Выполняется другая операция с расширениями. Дождитесь её завершения.", "ext.notFound": "Расширение '{0}' не установлено.", "ext.invalidSource": "'{0}' не является допустимой ссылкой на GitHub.", diff --git a/Services/Localization/Locales/sv.json b/Services/Localization/Locales/sv.json index 7f75996d..1482cdd9 100644 --- a/Services/Localization/Locales/sv.json +++ b/Services/Localization/Locales/sv.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' startade inte i tid.", "error.compositeMemberDelete": "'{0}' ingår i den sammansatta sessionen '{1}'. Ta bort den därifrån innan du raderar den.", "error.compositeInUse": "'{0}' ingår i en sammansatt session som körs.", + "error.userInUse": "'{0}' körs redan med den här Windows-användaren. Två sessioner med samma användare skulle dela en Windows-session, och att stoppa den ena skulle stänga båda. Använd en annan användare eller en isolerad session.", "ext.busy": "En annan tilläggsåtgärd pågår. Vänta tills den är klar.", "ext.notFound": "Tillägget '{0}' är inte installerat.", "ext.invalidSource": "'{0}' är inte en giltig GitHub-länk.", diff --git a/Services/Localization/Locales/tr.json b/Services/Localization/Locales/tr.json index ef9d50de..5ce720c8 100644 --- a/Services/Localization/Locales/tr.json +++ b/Services/Localization/Locales/tr.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' zamanında başlamadı.", "error.compositeMemberDelete": "'{0}', '{1}' birleşik oturumunda. Silmeden önce oradan çıkarın.", "error.compositeInUse": "'{0}' çalışan bir birleşik oturumda.", + "error.userInUse": "'{0}' zaten bu Windows kullanıcısıyla çalışıyor. Aynı kullanıcıya sahip iki oturum tek bir Windows oturumunu paylaşır ve birini durdurmak ikisini de kapatır. Başka bir kullanıcı veya yalıtılmış oturum kullanın.", "ext.busy": "Başka bir uzantı işlemi sürüyor. Bitmesini bekleyin.", "ext.notFound": "'{0}' uzantısı yüklü değil.", "ext.invalidSource": "'{0}' geçerli bir GitHub bağlantısı değil.", diff --git a/Services/Localization/Locales/uk.json b/Services/Localization/Locales/uk.json index 43e7d664..c0653186 100644 --- a/Services/Localization/Locales/uk.json +++ b/Services/Localization/Locales/uk.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' не запустився вчасно.", "error.compositeMemberDelete": "'{0}' входить до складеного сеансу '{1}'. Приберіть його звідти перед видаленням.", "error.compositeInUse": "'{0}' входить до запущеного складеного сеансу.", + "error.userInUse": "'{0}' вже працює з цим користувачем Windows. Два сеанси з одним користувачем спільно використовували б один сеанс Windows, і зупинка одного закрила б обидва. Використайте іншого користувача або ізольований сеанс.", "ext.busy": "Виконується інша операція з розширеннями. Дочекайтеся її завершення.", "ext.notFound": "Розширення '{0}' не встановлено.", "ext.invalidSource": "'{0}' не є дійсним посиланням на GitHub.", diff --git a/Services/Localization/Locales/vi.json b/Services/Localization/Locales/vi.json index 4d4a4829..cffe1883 100644 --- a/Services/Localization/Locales/vi.json +++ b/Services/Localization/Locales/vi.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' không khởi động kịp.", "error.compositeMemberDelete": "'{0}' nằm trong phiên ghép '{1}'. Hãy gỡ nó ra trước khi xóa.", "error.compositeInUse": "'{0}' nằm trong một phiên ghép đang chạy.", + "error.userInUse": "'{0}' đang chạy với người dùng Windows này. Hai phiên dùng cùng người dùng sẽ chia sẻ một phiên Windows và dừng một phiên sẽ đóng cả hai. Hãy dùng người dùng khác hoặc phiên cách ly.", "ext.busy": "Một thao tác tiện ích mở rộng khác đang diễn ra. Hãy đợi nó hoàn tất.", "ext.notFound": "Tiện ích mở rộng '{0}' chưa được cài đặt.", "ext.invalidSource": "'{0}' không phải là liên kết GitHub hợp lệ.", diff --git a/Services/Localization/Locales/zh.json b/Services/Localization/Locales/zh.json index 9234f961..a5c94bb1 100644 --- a/Services/Localization/Locales/zh.json +++ b/Services/Localization/Locales/zh.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' 未能及时启动。", "error.compositeMemberDelete": "'{0}' 在组合会话 '{1}' 中。删除前请先将其移出。", "error.compositeInUse": "'{0}' 在一个正在运行的组合会话中。", + "error.userInUse": "'{0}' 已在使用此 Windows 用户运行。同一用户的两个会话会共用一个 Windows 会话,停止其中一个会同时关闭两个。请使用其他用户或独立会话。", "ext.busy": "另一个扩展操作正在进行。请等待其完成。", "ext.notFound": "扩展「{0}」未安装。", "ext.invalidSource": "「{0}」不是有效的 GitHub 链接。", diff --git a/Services/Localization/Locales/zh_TW.json b/Services/Localization/Locales/zh_TW.json index 24632e2c..bfcf87ba 100644 --- a/Services/Localization/Locales/zh_TW.json +++ b/Services/Localization/Locales/zh_TW.json @@ -98,6 +98,7 @@ "error.compositeMemberStart": "'{0}' 未能及時啟動。", "error.compositeMemberDelete": "'{0}' 在組合工作階段 '{1}' 中。刪除前請先將其移出。", "error.compositeInUse": "'{0}' 在一個執行中的組合工作階段中。", + "error.userInUse": "'{0}' 已使用此 Windows 使用者執行中。同一使用者的兩個工作階段會共用一個 Windows 工作階段,停止其中一個會同時關閉兩個。請使用其他使用者或獨立工作階段。", "ext.busy": "另一項擴充功能作業正在進行中。請等待其完成。", "ext.notFound": "擴充功能「{0}」未安裝。", "ext.invalidSource": "「{0}」不是有效的 GitHub 連結。", diff --git a/tests/OpenStreamMS.Tests/SessionStartGuardsTests.cs b/tests/OpenStreamMS.Tests/SessionStartGuardsTests.cs new file mode 100644 index 00000000..08a5aed3 --- /dev/null +++ b/tests/OpenStreamMS.Tests/SessionStartGuardsTests.cs @@ -0,0 +1,61 @@ +using OpenStreamMS.Core.Api; +using OpenStreamMS.Core.Helpers; +using Xunit; + +namespace OpenStreamMS.Tests; + +/// +/// Issue #80: tras reiniciar, la sesión RDP de auto-arranque tardaba más de 30 s en iniciar +/// sesión y se daba por fallida; y dos sesiones con el mismo usuario de Windows acababan en la +/// misma sesión de Windows, así que parar una cerraba las dos. +/// +public sealed class SessionStartGuardsTests +{ + [Fact] + public void WaitsLongerRightAfterBoot() + { + Assert.Equal(TimeSpan.FromMinutes(2), RdpSessionCreator.SessionWaitLimit(TimeSpan.FromSeconds(40))); + Assert.Equal(TimeSpan.FromMinutes(2), RdpSessionCreator.SessionWaitLimit(TimeSpan.FromMinutes(4.9))); + Assert.Equal(TimeSpan.FromSeconds(30), RdpSessionCreator.SessionWaitLimit(TimeSpan.FromMinutes(5))); + Assert.Equal(TimeSpan.FromSeconds(30), RdpSessionCreator.SessionWaitLimit(TimeSpan.FromHours(3))); + } + + private static StreamSession Rdp(string name, string user, string domain = ".") => + new() { Id = Guid.NewGuid(), Name = name, Username = user, Domain = domain }; + + [Fact] + public void SameLocalUserIsFoundWhateverTheCaseOrDomainSpelling() + { + var a = Rdp("Salón", "Ti"); + var b = Rdp("Dormitorio", "ti", "PC"); + Assert.Same(a, StreamSessionService.FindSameWindowsUser(b, [a], "PC")); + } + + [Fact] + public void DifferentUsersAndDomainsDoNotClash() + { + var a = Rdp("Salón", "Ti"); + Assert.Null(StreamSessionService.FindSameWindowsUser(Rdp("Otro", "Startic"), [a], "PC")); + Assert.Null(StreamSessionService.FindSameWindowsUser(Rdp("Dominio", "Ti", "EMPRESA"), [a], "PC")); + } + + [Fact] + public void ASessionDoesNotClashWithItself() + { + var a = Rdp("Salón", "Ti"); + Assert.Null(StreamSessionService.FindSameWindowsUser(a, [a], "PC")); + } + + [Fact] + public void LocalAndIsolatedSessionsUseTheirOwnUser() + { + var local = new StreamSession { Id = Guid.NewGuid(), Name = "Local", Local = true }; + var isolatedA = new StreamSession { Id = Guid.NewGuid(), Name = "A", Isolated = true }; + var isolatedB = new StreamSession { Id = Guid.NewGuid(), Name = "B", Isolated = true }; + Assert.Null(StreamSessionService.FindSameWindowsUser(local, [isolatedA, isolatedB], "PC")); + Assert.Null(StreamSessionService.FindSameWindowsUser(isolatedA, [local, isolatedB], "PC")); + // Una aislada que reutiliza el usuario conservado de otra sí choca con ella. + var reused = new StreamSession { Id = Guid.NewGuid(), Name = "C", Isolated = true, IsolatedUsername = isolatedA.GetIsolatedUser() }; + Assert.Same(isolatedA, StreamSessionService.FindSameWindowsUser(reused, [isolatedA], "PC")); + } +}