diff --git a/Directory.Build.props b/Directory.Build.props index e141a91a..4a17bf70 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -1,6 +1,6 @@ - 1.45.10 + 1.45.11 10.0.15 diff --git a/docs/RELEASES.md b/docs/RELEASES.md index 41105c49..a1d1a8fa 100644 --- a/docs/RELEASES.md +++ b/docs/RELEASES.md @@ -1,5 +1,9 @@ # Binary releases +## 1.45.11 + +Account cards show **Sign in** and a dash when an account's login is rejected. Windows preserves file access permissions when saving Switch-owned account data, retires obsolete empty restart records, and remembers the order of account tanks. The dashboard also uses consistent Focus buttons, dismissible notices with countdown bars, and hardware meters without internal tick marks. [Changes and verification](development/RELEASE_1_45_11.md) + ## 1.45.10 Windows account cards can open a dedicated Codex window for each additional account and focus it again while other accounts keep running. Each window has its own login, native home and chat history. Switch verifies its live user and workspace before bringing it forward. The dashboard receives active chat counts and discards an observation when the login changes or the connection closes. Separate account windows are available in manual mode with credit use allowed. diff --git a/docs/development/ACCOUNT_AUTOMATION.md b/docs/development/ACCOUNT_AUTOMATION.md index 91c8ec68..e8b40961 100644 --- a/docs/development/ACCOUNT_AUTOMATION.md +++ b/docs/development/ACCOUNT_AUTOMATION.md @@ -1,6 +1,6 @@ # Account reauthentication and automatic switching -The per-account warning action opens the existing official browser login flow for that account. Hover retains the full refresh error. A different account identity is rejected before registration is changed. Successful reauthentication updates the original registration, retaining its key, alias and usage history. Canonical desktop credentials are applied only through the existing switch action. +The per-account warning action opens the existing official browser login flow for that account. A confirmed login rejection changes the account action to **Sign in** and replaces current quota figures with dashes. The encrypted vault retains usage history and remembers the rejection across restarts. Ordinary refresh failures retain the last usage reading and show the refresh error on hover. A different account identity is rejected before registration is changed. Successful reauthentication updates the original registration, retaining its key, alias and usage history. Canonical desktop credentials are applied only through the existing switch action. The **Auto Switch** toolbar menu contains a persistent On/Off toggle and the next eligible account, with automation disabled by default. Select a remaining-usage threshold of 5, 10 (default), 15 or 20 percent. The evaluator runs after the regular 60-second refresh. It requires one current account, successful observations no older than two minutes, matching bucket/window identities and positive durations, and a candidate with every reported window at least five percentage points above the threshold. Missing/zero/negative durations do not qualify even when both accounts omit the same value. Duplicate or blank quota bucket IDs make a profile ambiguous: a source blocks automatic selection/forecasting and a candidate is skipped while valid alternatives remain eligible. Original quota snapshots remain unchanged; ambiguity is not merged, guessed or accepted through a dictionary exception. A source at exactly the threshold does not trigger. An exhausted source can switch away; restricted candidates cannot be selected. Displaying a different quota in a card does not change this policy. Stale, failed, refreshing, missing or invalid quota data never initiates a handoff. A stopped/disconnected desktop, active login/switch/query, five-minute persisted cooldown or pending recovery also blocks automatic selection. @@ -10,6 +10,10 @@ On Windows, manual account cards offer **Open** or **Focus**. Each additional ac Automatic switching and credit protection manage the primary session. Separate account windows use manual mode with credit use allowed. Existing recovery and login application actions remain explicit. Removing a registration for a closed managed window removes its file login and retains its local chat history. +The Windows dashboard saves tank positions by account key in the encrypted vault. Drag the handle at the start of a tank header or use **Move card** in the account menu. The dashboard keeps the chosen order across restarts and adds new accounts at the end. Automatic switching keeps its own priority list. + +Windows status notices display a remaining-time bar and a close button. Ordinary notices expire after eight seconds and warnings expire after fifteen. Dismissing a recovery notice leaves the recovery action on the account card. + Coordinated account handoff saves checkpoints for chat backup, normal shutdown, credential application, native launch, IPC discovery and chat resume. The switch saves a checkpoint before shutdown or credential application. Transient failures share up to **two additional retries**, saved before each one-second retry wait. An unconfirmed shutdown or launch that reaches its deadline stops for explicit recovery. Once the native desktop is observed running, IPC and chat retries stay in their own stages. A switch with no chats left to resume completes upon observing the desktop. Each retry checks account identity where it authorizes an action. The coordinator recognizes credentials already applied and only observes a Continue whose delivery is uncertain. Windows shows the current step, remaining stage time, chat count, retry number and a cancel action in the account header. The budgets are 45 seconds for preparation or normal shutdown, 60 seconds per name backup or account application, 40 seconds for launch, 30 seconds per connection attempt and 90 seconds per chat resume. Model-profile operations have a separate 180-second budget. Cancellation waits for the current operation to settle. After confirmed shutdown and before any launch request, cancellation or a failed application can trigger one 35-second safety attempt to reopen the verified desktop. A failed automatic handoff disables further automation. @@ -18,6 +22,8 @@ Windows shows the current step, remaining stage time, chat count, retry number a During a same-account restart, Switch reopens each captured chat and confirms that the native client loaded it. Codex controls automatic continuation. Active goals also retain native continuation ownership during account handoff, including while goal metadata is being restored. +On Windows, a verified primary Codex window that started after an empty manual same-account restart request resolves that pending request. Switch checks the current login and preserves any request that recorded chats, applied credentials or model settings, or involved credit protection. + The observed Windows desktop 26.1117.4957.0 used private stdio for its app-server. Switching a saved login in the open window requires both a connection to that server and an operation that can adopt the target login. In a disposable two-login test, a second app-server read login B after the credentials file changed. The original server still reported A through `accountSession/list`. Calling `accountSession/switch` on the original server with B's actual session and workspace IDs returned JSON-RPC error `-32600` on both 0.167.0-alpha.4.1 and 0.171.0-alpha.13. On 0.167.0-alpha.4.1, account and auth refresh requests also left A active. Verify a change of identity on the server serving the desktop before reporting completion. After the utility restarts, an interrupted automatic plan with no retry reserved gets one persisted recovery attempt, counted within the same two-retry budget. A plan that has already reserved a retry requires manual Recover after a utility restart. Explicit user/lifetime cancellation prevents automatic recovery and retains manual Recover. No indefinite timer/restart loop is allowed. Already completed chats and original Continue message identities survive recovery; ambiguous delivery retains the existing no-resend policy. Disabling automation affects future selection, not a checkpointed handoff already in progress. Recovery cannot guarantee launch when the client is missing or its IPC remains unavailable; the pending plan and error remain available for a later retry. diff --git a/docs/development/RELEASE_1_45_11.md b/docs/development/RELEASE_1_45_11.md new file mode 100644 index 00000000..284a292f --- /dev/null +++ b/docs/development/RELEASE_1_45_11.md @@ -0,0 +1,21 @@ +# Release 1.45.11 + +## Account access and recovery + +- Show **Sign in** for a rejected login and open browser reauthentication for the selected account. Replace stale current quota with a dash while preserving usage history. Brief refresh failures retain the last reading. +- Save Switch-owned Windows account files with an atomic rename and preserve destination access permissions. Reopening a prepared account window skips unchanged settings and unnecessary vault writes. +- Clear an empty manual restart record after verifying that the primary Windows Codex window started later under the same login. Plans with saved chats or credential changes remain recoverable. + +## Windows dashboard + +- Give every **Focus** button the same style. Drag a tank by its handle or choose **Move card** in its menu. The vault remembers the layout independently of automatic switching priority. +- Show the remaining time at the bottom of each notice. Ordinary notices expire after eight seconds, warnings after fifteen. The close button dismisses the notice immediately. A dismissed recovery notice leaves its action on the account card. +- Remove the internal vertical ticks from the CPU, memory, GPU and VRAM meters. + +## Verification scope + +The Windows desktop checks cover rejected logins, hidden stale quota, preserved recovery records, account-window file replacement under Windows access controls, saved dashboard order and notice dismissal. Local Windows pixel comparisons use identical fictional hardware readings for both themes and languages. The screenshots are renders of production controls with fictional data. + +[Tank order and matching Focus buttons](../media/release-1.45.11/dashboard-reordered-ko.png) · [Notification timer and close button](../media/release-1.45.11/notification-countdown-ko.png) · [Earlier hardware meters](../media/release-1.45.11/hardware-before.png) · [Hardware meters with ticks removed](../media/release-1.45.11/hardware-after.png) + +Windows x64 and both macOS architectures have self-contained downloads. Both Linux architectures use the existing preview package scope. diff --git a/docs/media/release-1.45.11/dashboard-reordered-ko.png b/docs/media/release-1.45.11/dashboard-reordered-ko.png new file mode 100644 index 00000000..4ee07bc4 Binary files /dev/null and b/docs/media/release-1.45.11/dashboard-reordered-ko.png differ diff --git a/docs/media/release-1.45.11/hardware-after.png b/docs/media/release-1.45.11/hardware-after.png new file mode 100644 index 00000000..6e9decc8 Binary files /dev/null and b/docs/media/release-1.45.11/hardware-after.png differ diff --git a/docs/media/release-1.45.11/hardware-before.png b/docs/media/release-1.45.11/hardware-before.png new file mode 100644 index 00000000..c386c8c8 Binary files /dev/null and b/docs/media/release-1.45.11/hardware-before.png differ diff --git a/docs/media/release-1.45.11/notification-countdown-ko.png b/docs/media/release-1.45.11/notification-countdown-ko.png new file mode 100644 index 00000000..a54e1bfc Binary files /dev/null and b/docs/media/release-1.45.11/notification-countdown-ko.png differ diff --git a/localization/packs/de.json b/localization/packs/de.json index 39584f14..451276c4 100644 --- a/localization/packs/de.json +++ b/localization/packs/de.json @@ -160,6 +160,11 @@ "subscription.left": "Resttage", "subscription.expired_days": "Seit {0}T abgelaufen", "account.relogin": "Im Browser erneut anmelden", + "account.sign_in": "Anmelden", + "dashboard.drag_account": "Kontokarten durch Ziehen sortieren", + "dashboard.move_account": "Karte verschieben", + "dashboard.position": "{0}. {1}", + "account.login_required": "Melden Sie sich erneut an, um die Nutzung zu aktualisieren.", "account.relogin_mismatch": "Mit dem gewählten Konto anmelden. Bestehende Konten wurden beibehalten.", "auto.on": "Auto-Kontowechsel: Ein", "auto.off": "Auto-Kontowechsel: Aus", diff --git a/localization/packs/en.json b/localization/packs/en.json index f9fa822e..f49312d4 100644 --- a/localization/packs/en.json +++ b/localization/packs/en.json @@ -160,6 +160,11 @@ "subscription.left": "Days left", "subscription.expired_days": "Expired {0}d ago", "account.relogin": "Sign in again in browser", + "account.sign_in": "Sign in", + "dashboard.drag_account": "Drag to reorder account cards", + "dashboard.move_account": "Move card", + "dashboard.position": "{0}. {1}", + "account.login_required": "Sign in again to update usage.", "account.relogin_mismatch": "Sign in with the selected account. Existing accounts were preserved.", "auto.on": "Account auto-switch: On", "auto.off": "Account auto-switch: Off", diff --git a/localization/packs/es.json b/localization/packs/es.json index 9e299c33..6bd68e2b 100644 --- a/localization/packs/es.json +++ b/localization/packs/es.json @@ -160,6 +160,11 @@ "subscription.left": "Días restantes", "subscription.expired_days": "Venció hace {0}d", "account.relogin": "Iniciar sesión de nuevo", + "account.sign_in": "Iniciar sesión", + "dashboard.drag_account": "Arrastra para reordenar las tarjetas de cuenta", + "dashboard.move_account": "Mover tarjeta", + "dashboard.position": "{0}. {1}", + "account.login_required": "Vuelve a iniciar sesión para actualizar el uso.", "account.relogin_mismatch": "Inicia sesión con la cuenta seleccionada. Se conservaron las cuentas existentes.", "auto.on": "Cambio de cuenta auto.: Sí", "auto.off": "Cambio de cuenta auto.: No", diff --git a/localization/packs/fr.json b/localization/packs/fr.json index 3626cf52..d087ead8 100644 --- a/localization/packs/fr.json +++ b/localization/packs/fr.json @@ -160,6 +160,11 @@ "subscription.left": "Jours restants", "subscription.expired_days": "Expiré depuis {0}j", "account.relogin": "Se reconnecter dans le navigateur", + "account.sign_in": "Se connecter", + "dashboard.drag_account": "Faites glisser pour réorganiser les cartes", + "dashboard.move_account": "Déplacer la carte", + "dashboard.position": "{0}. {1}", + "account.login_required": "Reconnectez-vous pour actualiser l’utilisation.", "account.relogin_mismatch": "Connectez-vous au compte sélectionné. Les comptes existants ont été conservés.", "auto.on": "Bascule auto de compte : activée", "auto.off": "Bascule auto de compte : désactivée", diff --git a/localization/packs/ja.json b/localization/packs/ja.json index e481a4a8..f34b03a7 100644 --- a/localization/packs/ja.json +++ b/localization/packs/ja.json @@ -160,6 +160,11 @@ "subscription.left": "残り日数", "subscription.expired_days": "{0}日前に期限切れ", "account.relogin": "ブラウザーで再ログイン", + "account.sign_in": "ログイン", + "dashboard.drag_account": "ドラッグしてアカウントカードを並べ替える", + "dashboard.move_account": "カードを移動", + "dashboard.position": "{0}. {1}", + "account.login_required": "使用量を更新するには再度ログインしてください。", "account.relogin_mismatch": "選択したアカウントでログインしてください。既存の登録は保持されました。", "auto.on": "アカウント自動切替: オン", "auto.off": "アカウント自動切替: オフ", diff --git a/localization/packs/ko.json b/localization/packs/ko.json index bd70a2b5..9579083b 100644 --- a/localization/packs/ko.json +++ b/localization/packs/ko.json @@ -160,6 +160,11 @@ "subscription.left": "남은 일수", "subscription.expired_days": "{0}일 지남", "account.relogin": "브라우저에서 다시 로그인", + "account.sign_in": "로그인", + "dashboard.drag_account": "드래그해서 계정 카드 순서 바꾸기", + "dashboard.move_account": "카드 위치 이동", + "dashboard.position": "{0}. {1}", + "account.login_required": "사용량을 확인하려면 다시 로그인하세요.", "account.relogin_mismatch": "선택한 계정으로 로그인해 주세요. 기존 계정 정보는 보존했습니다.", "auto.on": "계정 자동 전환: 켜짐", "auto.off": "계정 자동 전환: 꺼짐", diff --git a/localization/packs/pt-BR.json b/localization/packs/pt-BR.json index c44c9dd5..5647e2b4 100644 --- a/localization/packs/pt-BR.json +++ b/localization/packs/pt-BR.json @@ -160,6 +160,11 @@ "subscription.left": "Dias restantes", "subscription.expired_days": "Expirou há {0}d", "account.relogin": "Entrar novamente no navegador", + "account.sign_in": "Entrar", + "dashboard.drag_account": "Arraste para reordenar os cartões de conta", + "dashboard.move_account": "Mover cartão", + "dashboard.position": "{0}. {1}", + "account.login_required": "Entre novamente para atualizar o uso.", "account.relogin_mismatch": "Entre com a conta selecionada. As contas existentes foram preservadas.", "auto.on": "Troca auto. de conta: Ligada", "auto.off": "Troca auto. de conta: Desligada", diff --git a/localization/packs/zh-CN.json b/localization/packs/zh-CN.json index 3e54ee86..adf24fbb 100644 --- a/localization/packs/zh-CN.json +++ b/localization/packs/zh-CN.json @@ -160,6 +160,11 @@ "subscription.left": "剩余天数", "subscription.expired_days": "已过期{0}天", "account.relogin": "在浏览器中重新登录", + "account.sign_in": "登录", + "dashboard.drag_account": "拖动以调整账户卡片顺序", + "dashboard.move_account": "移动卡片", + "dashboard.position": "{0}. {1}", + "account.login_required": "请重新登录以更新用量。", "account.relogin_mismatch": "请使用所选账号登录。现有账号信息已保留。", "auto.on": "账号自动切换:开启", "auto.off": "账号自动切换:关闭", diff --git a/localization/packs/zh-TW.json b/localization/packs/zh-TW.json index 445d77bb..d0f65012 100644 --- a/localization/packs/zh-TW.json +++ b/localization/packs/zh-TW.json @@ -160,6 +160,11 @@ "subscription.left": "剩餘天數", "subscription.expired_days": "已過期{0}天", "account.relogin": "在瀏覽器中重新登入", + "account.sign_in": "登入", + "dashboard.drag_account": "拖曳以調整帳戶卡片順序", + "dashboard.move_account": "移動卡片", + "dashboard.position": "{0}. {1}", + "account.login_required": "請重新登入以更新使用量。", "account.relogin_mismatch": "請使用所選帳號登入。現有帳號資訊已保留。", "auto.on": "帳號自動切換:開啟", "auto.off": "帳號自動切換:關閉", diff --git a/src/application/AccountLoginRequiredException.cs b/src/application/AccountLoginRequiredException.cs new file mode 100644 index 00000000..0792b744 --- /dev/null +++ b/src/application/AccountLoginRequiredException.cs @@ -0,0 +1,15 @@ +using System; +using System.Text.RegularExpressions; + +namespace CodexAccountDesk; + +internal sealed class AccountLoginRequiredException() : InvalidOperationException("account.login_required") +{ + private static readonly Regex RejectedCredential = new( + @"\b(?:HTTP(?: status)?\s+401|status(?: code)?\s*[:=]?\s*401|401\s+Unauthorized|invalid_grant|refresh_token_(?:expired|reused|invalidated|revoked)|token_revoked|token_expired|please log out and sign in again|not logged in|chatgpt (?:login|authentication) (?:is )?required)\b", + RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + + internal static bool Matches(Exception error) => error is AccountLoginRequiredException || + error is CodexRequestException { Operation: "account/read" or "account/rateLimits/read" } request && + (request.Code == 401 || RejectedCredential.IsMatch(request.Message)); +} diff --git a/src/application/AccountService.cs b/src/application/AccountService.cs index b995d56f..80d0a94b 100644 --- a/src/application/AccountService.cs +++ b/src/application/AccountService.cs @@ -74,13 +74,44 @@ public AccountProfile[] Accounts SubscriptionActiveUntil = p.SubscriptionActiveUntil, SubscriptionLastChecked = p.SubscriptionLastChecked, Subscription = p.Subscription, SubscriptionError = p.SubscriptionError, IsCurrent = p.Key == CurrentKey, RequiresApply = p.RequiresApply, HasAccountWindow = p.HasAccountWindow, - WindowLoginPending = p.WindowLoginPending, Usage = p.Usage, Error = p.Error, + RequiresLogin = p.RequiresLogin, WindowLoginPending = p.WindowLoginPending, Usage = p.RequiresLogin ? null : p.Usage, + Error = p.RequiresLogin ? "account.login_required" : p.Error, IsRefreshing = _queries.IsRunning(p.Key), History = p.History.Select(t => t.Copy()).ToList(), CreditHistory = p.CreditHistory.Select(t => t.Copy()).ToList(), RecoveredCreditHistory = p.RecoveredCreditHistory.ToList() }).ToArray(); } } + internal AccountProfile[] DashboardAccounts() + { + lock (Vault.SyncRoot) + { + var accounts = Accounts.OrderByDescending(account => account.IsCurrent) + .ThenBy(account => account.DisplayName, StringComparer.CurrentCultureIgnoreCase).ToArray(); + if (Vault.Data.DashboardAccountOrder.Count == 0) return accounts; + var byKey = accounts.ToDictionary(account => account.Key, StringComparer.Ordinal); + return Vault.Data.DashboardAccountOrder.Where(byKey.ContainsKey).Concat(accounts.Select(account => account.Key)) + .Distinct(StringComparer.Ordinal).Select(key => byKey[key]).ToArray(); + } + } + + internal void MoveDashboardAccount(string key, string destinationKey) + { + lock (Vault.SyncRoot) + { + var order = DashboardAccounts().Select(account => account.Key).ToList(); + var source = order.IndexOf(key); + var destination = order.IndexOf(destinationKey); + if (source < 0 || destination < 0 || source == destination) return; + order.RemoveAt(source); + order.Insert(destination, key); + var previous = Vault.Data.DashboardAccountOrder; + Vault.Data.DashboardAccountOrder = order; + try { Vault.Save(); } + catch { Vault.Data.DashboardAccountOrder = previous; throw; } + } + } + public async Task InitializeAsync(CancellationToken cancellation) { if (OperatingSystem.IsLinux()) LinuxPrivateFiles.CreateDirectory(CodexHome); @@ -97,6 +128,22 @@ public async Task InitializeAsync(CancellationToken cancellation) { RequireLegacySync(); return SynchronizeCurrentCore(null); } + + internal bool RetireEmptyWindowsRestart(DateTimeOffset primaryStartedAt) + { + if (!OperatingSystem.IsWindows()) return false; + lock (Vault.SyncRoot) + { + var plan = Vault.Data.PendingSwitch; + if (!SwitchRecovery.CanRetireEmptyRestart(plan, CurrentKey, primaryStartedAt) || !CanonicalAuthExists()) return false; + var key = AuthDocument.Parse(ReadCanonicalAuth()).Key; + if (key != CurrentKey) return false; + Vault.Data.PendingSwitch = null; + try { Vault.Save(); } + catch { Vault.Data.PendingSwitch = plan; throw; } + return true; + } + } public async Task SynchronizeCurrentAsync(CancellationToken cancellation) { await using var client = await OpenLinuxAsync(cancellation).ConfigureAwait(false); @@ -179,7 +226,7 @@ private async Task RefreshCoreAsync(string key, CancellationToken cancellation) await using var rpc = await OpenAccountRpcAsync(queryHome, client, workspace, cancellation).ConfigureAwait(false); var accountResult = await rpc.RequestAsync("account/read", new { refreshToken = false }, cancellation).ConfigureAwait(false); if (!accountResult.TryGetProperty("account", out var info) || info.ValueKind != JsonValueKind.Object || JsonValue.String(info, "type") != "chatgpt") - throw new InvalidOperationException("로그인이 만료됐습니다. 계정 추가로 다시 로그인해 주세요."); + throw new AccountLoginRequiredException(); var response = await rpc.RequestAsync("account/rateLimits/read", null, cancellation).ConfigureAwait(false); usage = UsageSnapshot.Parse(response, profile.AccountId); email = JsonValue.String(info, "email"); plan = JsonValue.String(info, "planType"); @@ -211,11 +258,14 @@ private async Task RefreshCoreAsync(string key, CancellationToken cancellation) lock (Vault.SyncRoot) { if (!IsCurrentRevision(profile, revision)) return; + var restoredLogin = profile.RequiresLogin; + profile.RequiresLogin = false; profile.Usage = usage; profile.Error = null; if (usage != null) UsageHistory.Record(profile, usage); if (!string.IsNullOrEmpty(email)) profile.Email = email; if (plan != null) profile.Plan = plan; subscriptionAuth = profile.AuthJson; + if (restoredLogin) Vault.Save(); } Changed?.Invoke(); SubscriptionSnapshot? subscription = null; @@ -234,7 +284,18 @@ private async Task RefreshCoreAsync(string key, CancellationToken cancellation) catch (OperationCanceledException) when (cancellation.IsCancellationRequested) { throw; } catch (Exception error) { - lock (Vault.SyncRoot) { if (profile != null && IsCurrentRevision(profile, revision)) profile.Error = UserErrors.Describe(error); } + lock (Vault.SyncRoot) + { + if (profile != null && IsCurrentRevision(profile, revision)) + { + profile.Error = UserErrors.Describe(error); + if (!profile.RequiresLogin && AccountLoginRequiredException.Matches(error)) + { + profile.RequiresLogin = true; + Vault.Save(); + } + } + } } finally { _querySlots.Release(); Changed?.Invoke(); } } @@ -312,6 +373,10 @@ private AccountRegistration CompleteRegistrationCore(string authJson, string? ex !Vault.Data.Accounts.Any(p => p.Key == expectedAccountKey))) throw new InvalidOperationException(Loc.T("account.relogin_mismatch")); var profile = Vault.Upsert(authJson); + if (profile.RequiresLogin) + { + profile.RequiresLogin = false; profile.Usage = null; profile.CredentialRevision++; + } if (OperatingSystem.IsWindows() && profile.HasAccountWindow) profile.WindowLoginPending = true; var active = CanonicalAuthExists() ? ReadCanonicalAuth() : null; profile.RequiresApply = active != null && AuthDocument.Parse(active).Key == profile.Key && active != profile.AuthJson; @@ -345,6 +410,7 @@ internal async Task OpenAccountWindowAsync(string key, CancellationToken cancell AccountProfile Selected() { var account = Vault.Data.Accounts.Find(a => a.Key == key) ?? throw new InvalidOperationException("선택한 계정이 삭제됐습니다."); + if (account.RequiresLogin) throw new AccountLoginRequiredException(); CheckCredentialBackend(account); var primary = CanonicalAuthExists() ? AuthDocument.Parse(ReadCanonicalAuth()).Key : null; if (primary != expectedPrimary) throw new InvalidOperationException("switch.window_identity"); @@ -364,10 +430,25 @@ void Prepare() if (window == null) return; var native = Path.Combine(Path.GetDirectoryName(installation.DesktopPath)!, "resources", "codex.exe"); if (!File.Exists(native) || !File.Exists(backend)) throw new FileNotFoundException("Codex account-window runtime is missing."); - window.Prepare(account); var binding = new DesktopBackendHost.Configuration(native, window.Home, window.Home, backend); - SecureFiles.AtomicWrite(Path.Combine(window.Home, "window-backend.json"), JsonSerializer.SerializeToUtf8Bytes(binding)); - Vault.Save(); + var managedBefore = account.HasAccountWindow; + var applyBefore = account.WindowLoginPending; + try + { + window.Prepare(account); + var path = Path.Combine(window.Home, "window-backend.json"); + var contents = JsonSerializer.SerializeToUtf8Bytes(binding); + if (!File.Exists(path) || (File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0 || + !File.ReadAllBytes(path).AsSpan().SequenceEqual(contents)) + SecureFiles.AtomicWriteOwned(path, contents); + if (managedBefore != account.HasAccountWindow || applyBefore != account.WindowLoginPending) Vault.Save(); + } + catch + { + account.HasAccountWindow = managedBefore; + account.WindowLoginPending = applyBefore; + throw; + } } } Task Verify(int pid, CancellationToken token) @@ -417,6 +498,7 @@ bool Running() => OperatingSystem.IsLinux() ? LinuxDesktopRuntime.Running(cancel { Installation = installation; var selected = Vault.Data.Accounts.Find(a => a.Key == key) ?? throw new InvalidOperationException("선택한 계정이 삭제됐습니다."); + if (selected.RequiresLogin) throw new AccountLoginRequiredException(); if (policy != null) LinuxClientSession.RequireFile(policy, selected.AccountId); else CheckCredentialBackend(selected); if (AuthDocument.Parse(selected.AuthJson).Key != key) throw new InvalidDataException("선택한 로그인 정보와 계정이 일치하지 않습니다."); var selectedAuth = selected.AuthJson; @@ -464,7 +546,10 @@ public async Task RemoveAsync(string key) if (WindowsAccountWindows.UsesProfile(Installation.DesktopPath, profile.Desktop)) throw new InvalidOperationException("switch.window_busy"); profile.RemoveLogin(); } - Vault.Data.Accounts.RemoveAll(a => a.Key == key); Vault.Data.AutomaticSwitchPriority.RemoveAll(k => k == key); Vault.Save(); + Vault.Data.Accounts.RemoveAll(a => a.Key == key); + Vault.Data.AutomaticSwitchPriority.RemoveAll(k => k == key); + Vault.Data.DashboardAccountOrder.RemoveAll(k => k == key); + Vault.Save(); } Changed?.Invoke(); } @@ -590,6 +675,7 @@ internal static class UserErrors { public static string Describe(Exception error) { + if (AccountLoginRequiredException.Matches(error)) return "account.login_required"; if (error is LinuxDesktopOwnershipException) return Loc.T("msg.linux_desktop_unmanaged"); if (error is LinuxAccountPolicyException policy) return Loc.T(policy.Failure switch { @@ -605,7 +691,6 @@ public static string Describe(Exception error) if (error is CodexRequestException request) { if (request.Operation?.StartsWith("thread", StringComparison.Ordinal) == true) return request.Message; - if (error.Message.Contains("401") || error.Message.Contains("refresh", StringComparison.OrdinalIgnoreCase) || error.Message.Contains("auth", StringComparison.OrdinalIgnoreCase)) return "로그인이 만료되거나 취소됐습니다. 계정 추가로 다시 로그인해 주세요."; return "Codex 서버에서 사용량을 가져오지 못했습니다. 연결을 확인하고 새로 고침해 주세요."; } return error.Message; diff --git a/src/application/AccountWindowProfile.cs b/src/application/AccountWindowProfile.cs index 552c6278..9d91a405 100644 --- a/src/application/AccountWindowProfile.cs +++ b/src/application/AccountWindowProfile.cs @@ -1,5 +1,6 @@ using System; using System.IO; +using System.Text; namespace CodexAccountDesk; @@ -19,8 +20,10 @@ private static void CheckPath(string path) internal string ReadLogin() { - CheckPath(_root); CheckPath(Folder); CheckPath(Desktop); CheckPath(Home); CheckPath(Auth); - var json = File.ReadAllText(Auth); + CheckPath(_root); CheckPath(Folder); CheckPath(Desktop); CheckPath(Home); + string json; + try { CheckPath(Auth); json = File.ReadAllText(Auth); } + catch (FileNotFoundException) { throw new AccountLoginRequiredException(); } if (AuthDocument.Parse(json).Key != key) throw new InvalidOperationException("switch.window_identity"); return json; } @@ -33,10 +36,10 @@ internal void Prepare(AccountProfile account) if (!account.HasAccountWindow && !File.Exists(config)) SecureFiles.AtomicWriteText(config, "cli_auth_credentials_store = \"file\"\n"); var hasLogin = File.Exists(Auth); if (hasLogin) _ = ReadLogin(); - else if (account.HasAccountWindow && !account.WindowLoginPending) throw new InvalidOperationException("switch.window_relogin"); + else if (account.HasAccountWindow && !account.WindowLoginPending) throw new AccountLoginRequiredException(); if (!account.HasAccountWindow || account.WindowLoginPending) { - if (!hasLogin || account.WindowLoginPending) SecureFiles.AtomicWriteText(Auth, account.AuthJson); + if (!hasLogin || account.WindowLoginPending) SecureFiles.AtomicWriteOwned(Auth, Encoding.UTF8.GetBytes(account.AuthJson)); account.HasAccountWindow = true; account.WindowLoginPending = false; } diff --git a/src/application/Storage.cs b/src/application/Storage.cs index 2aabc168..ed0b8512 100644 --- a/src/application/Storage.cs +++ b/src/application/Storage.cs @@ -38,7 +38,11 @@ public AccountProfile Upsert(string authJson) var parsed = AuthDocument.Parse(authJson); var existing = Data.Accounts.Find(a => a.Key == parsed.Key); if (existing == null) { Data.Accounts.Add(parsed); return parsed; } - if (existing.AuthJson != authJson) { existing.AuthJson = authJson; existing.CredentialRevision++; } + if (existing.AuthJson != authJson) + { + existing.AuthJson = authJson; existing.CredentialRevision++; + if (existing.RequiresLogin) { existing.RequiresLogin = false; existing.Usage = null; } + } if (parsed.Email.Length > 0) existing.Email = parsed.Email; if (parsed.Plan != "unknown") existing.Plan = parsed.Plan; return existing; @@ -49,7 +53,7 @@ public void Save() lock (SyncRoot) { var bytes = JsonSerializer.SerializeToUtf8Bytes(Data); - try { SecureFiles.AtomicWrite(FilePath, VaultProtection.Protect(bytes, DirectoryPath)); } + try { SecureFiles.AtomicWriteOwned(FilePath, VaultProtection.Protect(bytes, DirectoryPath)); } finally { CryptographicOperations.ZeroMemory(bytes); } } } diff --git a/src/application/VaultData.cs b/src/application/VaultData.cs index fd41adf4..e54cda55 100644 --- a/src/application/VaultData.cs +++ b/src/application/VaultData.cs @@ -20,6 +20,7 @@ internal sealed class VaultData public int AutomaticSwitchThreshold { get; set; } = 10; public bool AutomaticSwitchUsePriority { get; set; } public List AutomaticSwitchPriority { get; set; } = new(); + public List DashboardAccountOrder { get; set; } = new(); public DateTimeOffset? LastAutomaticSwitchAttempt { get; set; } private static List DefaultDrives() { diff --git a/src/core/AccountSwitchCoordinator.cs b/src/core/AccountSwitchCoordinator.cs index 74357610..c0da2f90 100644 --- a/src/core/AccountSwitchCoordinator.cs +++ b/src/core/AccountSwitchCoordinator.cs @@ -83,6 +83,9 @@ public static bool CanReplaceEmptyRestart(AccountSwitchPlan? plan, string? curre Phase: SwitchPhase.BackingUp or SwitchPhase.Closing, Chats.Count: 0 } && plan.SourceAccountKey == current && plan.TargetAccountKey == current; + public static bool CanRetireEmptyRestart(AccountSwitchPlan? plan, string? current, DateTimeOffset? primaryStartedAt) => + CanReplaceEmptyRestart(plan, current) && plan!.RequestedAt != default && primaryStartedAt > plan.RequestedAt; + public static bool AllowsAccount(AccountSwitchPlan? plan, string target, string? current, bool manualSwitch) => plan == null || plan.CreditProtectionPause || plan.TargetAccountKey == target || manualSwitch && CanReplaceEmptyRestart(plan, current); diff --git a/src/core/AutomaticSwitchPolicy.cs b/src/core/AutomaticSwitchPolicy.cs index d8018f5c..e5188555 100644 --- a/src/core/AutomaticSwitchPolicy.cs +++ b/src/core/AutomaticSwitchPolicy.cs @@ -64,7 +64,7 @@ private static int Rank(IReadOnlyList priority, string key) return int.MaxValue; } private static bool Fresh(AccountProfile profile, DateTimeOffset now, bool allowPendingCredentials = false) => - profile.Error == null && !profile.IsRefreshing && (!profile.RequiresApply || allowPendingCredentials) && profile.Usage != null && + profile.Error == null && !profile.RequiresLogin && !profile.IsRefreshing && (!profile.RequiresApply || allowPendingCredentials) && profile.Usage != null && now >= profile.Usage.CheckedAt && now - profile.Usage.CheckedAt <= MaximumAge; private static bool Numeric(UsageWindow window) => window.Minutes is > 0 && double.IsFinite(window.UsedPercent) && window.UsedPercent is >= 0 and <= 100; private static bool Valid(UsageWindow window, DateTimeOffset now) => Numeric(window) && (window.ResetsAt == null || window.ResetsAt > now.ToUnixTimeSeconds()); diff --git a/src/core/Models.cs b/src/core/Models.cs index c1791d80..b782dadd 100644 --- a/src/core/Models.cs +++ b/src/core/Models.cs @@ -22,6 +22,7 @@ internal sealed class AccountProfile [JsonIgnore] public DateTimeOffset? SubscriptionLastChecked { get; set; } [JsonIgnore] public string? SubscriptionError { get; set; } public bool RequiresApply { get; set; } + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)] public bool RequiresLogin { get; set; } public bool HasAccountWindow { get; set; } public bool WindowLoginPending { get; set; } public UsageSnapshot? Usage { get; set; } diff --git a/src/desktop/AccountCard.cs b/src/desktop/AccountCard.cs index 7d314247..6303ff9c 100644 --- a/src/desktop/AccountCard.cs +++ b/src/desktop/AccountCard.cs @@ -16,7 +16,7 @@ internal sealed class MacAccountCard : Grid private readonly QuotaChoice? _quota; private readonly UsageTrendModel _trend; private readonly TextBlock _depletion, _reset, _subscription; - public static QuotaChoice[] Choices(AccountProfile profile) => profile.Usage?.Buckets.SelectMany(bucket => new[] { + public static QuotaChoice[] Choices(AccountProfile profile) => profile.RequiresLogin ? Array.Empty() : profile.Usage?.Buckets.SelectMany(bucket => new[] { bucket.Primary == null ? null : new QuotaChoice(bucket.Id, "primary", bucket.Primary, bucket.Label), bucket.Secondary == null ? null : new QuotaChoice(bucket.Id, "secondary", bucket.Secondary, bucket.Label) }).OfType().ToArray() ?? Array.Empty(); public static QuotaChoice? Select(AccountProfile profile, string? selection) => Choices(profile).FirstOrDefault(q => q.BucketId + ":" + q.Slot == selection) @@ -78,7 +78,7 @@ public void Update(DateTimeOffset now) ToolTip.SetTip(_subscription, SubscriptionPresentation.Details(_profile)); _subscription.Foreground = _theme.Brush(AccountDateWarnings.Subscription(_profile.SubscriptionActiveUntil, now) ? "warning" : "muted"); _reset.Foreground = _theme.Brush(AccountDateWarnings.Reset(_quota?.Window.ResetsAt, now) ? "warning" : "text"); - if (_quota == null) { _depletion.Text = Loc.T(_profile.IsRefreshing ? "측정중" : "정보 없음"); _reset.Text = "—"; return; } + if (_quota == null) { _depletion.Text = _profile.RequiresLogin ? "—" : Loc.T(_profile.IsRefreshing ? "측정중" : "정보 없음"); _reset.Text = "—"; return; } var forecast = UsagePredictor.Evaluate(_quota.Window, _trend, now); _depletion.Text = forecast.State == ForecastState.ResetsFirst ? Loc.T("리셋 먼저") : forecast.ExhaustsAt is DateTimeOffset end ? Compact(end, now) : Loc.T(forecast.State switch { ForecastState.Collecting or ForecastState.InsufficientChange => "측정중", ForecastState.NoGrowth => "증가 없음", ForecastState.Stale => "갱신 필요", ForecastState.Exhausted => "한도 도달", _ => "갱신 대기" }); diff --git a/src/desktop/DeskWindow.cs b/src/desktop/DeskWindow.cs index 32b28e91..e9dbea3b 100644 --- a/src/desktop/DeskWindow.cs +++ b/src/desktop/DeskWindow.cs @@ -281,10 +281,12 @@ private void RenderAccounts() var allowed = SwitchRecovery.AllowsAccount(pending, profile.Key, _service?.CurrentKey, manualSwitch: true); var activeSwitch = _switchTarget == profile.Key && _switch != null; var text = activeSwitch ? _phase == SwitchPhase.BackingUp ? "백업 중" : _phase == SwitchPhase.Resuming ? "재개 중" : "전환 중" : - resume ? "switch.recover" : profile.RequiresApply ? "로그인 적용" : profile.IsCurrent ? "사용 중" : "전환"; - var button = _theme.Button(Loc.T(text), () => _ = SwitchAsync(profile)); - if (resume || !allowed) ToolTip.SetTip(button, Loc.Error(pending?.Error ?? "switch.recover_pending")); - button.IsEnabled = _ready && _switch == null && _login == null && !_stampingTitles && allowed && (!profile.IsCurrent || profile.RequiresApply || resume); + profile.RequiresLogin ? "account.sign_in" : resume ? "switch.recover" : profile.RequiresApply ? "로그인 적용" : profile.IsCurrent ? "사용 중" : "전환"; + var button = _theme.Button(Loc.T(text), () => _ = profile.RequiresLogin ? AddAccountAsync(profile.Key) : SwitchAsync(profile)); + if (profile.RequiresLogin) ToolTip.SetTip(button, Loc.T("account.relogin")); + else if (resume || !allowed) ToolTip.SetTip(button, Loc.Error(pending?.Error ?? "switch.recover_pending")); + button.IsEnabled = _ready && _switch == null && _login == null && !_stampingTitles && + (profile.RequiresLogin || allowed && (!profile.IsCurrent || profile.RequiresApply || resume)); button.FontSize = 10; button.Padding = new Thickness(5, 2); var more = _theme.IconButton(DeskButtonIconKind.More, Loc.T("계정 메뉴"), () => { }); more.Width = 25; more.Padding = new Thickness(3, 2); more.Click += (_, _) => AccountMenu(more, profile); @@ -334,6 +336,7 @@ await RunAsync(async _ => private async Task SwitchAsync(AccountProfile profile, bool automatic = false, bool creditPause = false, bool restart = false, CodexModelProfile? modelProfile = null) { if (!_ready || _switch != null || _login != null || _stampingTitles) return; + if (profile.RequiresLogin) { _statusMessage = Loc.T("account.login_required"); _status.Text = _statusMessage; return; } var pending = _service!.Vault.Data.ActivePendingSwitch; var manual = !automatic && !creditPause && !restart && modelProfile == null; if (!SwitchRecovery.AllowsAccount(pending, profile.Key, _service.CurrentKey, manual) || diff --git a/src/macos/Info.plist b/src/macos/Info.plist index fce3f934..836ac04c 100644 --- a/src/macos/Info.plist +++ b/src/macos/Info.plist @@ -7,8 +7,8 @@ CFBundleExecutableCodexSwitch CFBundlePackageTypeAPPL CFBundleInfoDictionaryVersion6.0 - CFBundleShortVersionString1.45.10 - CFBundleVersion1.45.10 + CFBundleShortVersionString1.45.11 + CFBundleVersion1.45.11 CFBundleIconFileapp-icon.icns LSMinimumSystemVersion15.0 LSApplicationCategoryTypepublic.app-category.utilities diff --git a/src/platforms/client/WindowsAccountWindows.cs b/src/platforms/client/WindowsAccountWindows.cs index 7b28b07d..cd352f32 100644 --- a/src/platforms/client/WindowsAccountWindows.cs +++ b/src/platforms/client/WindowsAccountWindows.cs @@ -101,16 +101,20 @@ private static IntPtr Window(Root root) } internal static bool HasManagedWindow(string executable) => Roots(executable, true).Any(root => root.Managed); - internal static Dictionary Inventory(string executable) + internal static (Dictionary Windows, DateTimeOffset? PrimaryStartedAt) Inventory(string executable) { var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + DateTimeOffset? primaryStartedAt = null; foreach (var root in Roots(executable)) { if (!root.Managed && root.Directory != null) continue; var directory = root.Directory ?? ""; if (!result.TryAdd(directory, root.Pid)) result[directory] = 0; + if (!root.Managed && directory.Length == 0 && result[directory] > 0 && + Window(root) != IntPtr.Zero) + primaryStartedAt = new DateTimeOffset(DateTime.FromFileTimeUtc(root.Created)); } - return result; + return (result, result.TryGetValue("", out var primary) && primary > 0 ? primaryStartedAt : null); } internal static bool UsesProfile(string executable, string profile) => Roots(executable, true).Any(root => string.Equals(root.Directory, profile, StringComparison.OrdinalIgnoreCase)); diff --git a/src/platforms/protocol/CodexRpc.cs b/src/platforms/protocol/CodexRpc.cs index 3a087b08..7b879d32 100644 --- a/src/platforms/protocol/CodexRpc.cs +++ b/src/platforms/protocol/CodexRpc.cs @@ -101,7 +101,7 @@ private async Task ReadAsync() var root = document.RootElement; if (root.TryGetProperty("id", out var id) && id.ValueKind == JsonValueKind.Number && _pending.TryGetValue(id.GetInt32(), out var completion)) { - if (root.TryGetProperty("error", out var error)) completion.TrySetException(new CodexRequestException(JsonValue.String(error, "message") ?? "Codex 조회에 실패했습니다.", _methods.TryGetValue(id.GetInt32(), out var operation) ? operation : null)); + if (root.TryGetProperty("error", out var error)) completion.TrySetException(new CodexRequestException(JsonValue.String(error, "message") ?? "Codex 조회에 실패했습니다.", _methods.TryGetValue(id.GetInt32(), out var operation) ? operation : null, JsonValue.Int(error, "code"))); else if (root.TryGetProperty("result", out var result)) completion.TrySetResult(result.Clone()); else completion.TrySetException(new InvalidDataException("Codex 응답에 결과가 없습니다.")); } @@ -139,5 +139,7 @@ public async ValueTask DisposeAsync() internal sealed class CodexRequestException : Exception { public string? Operation { get; } - public CodexRequestException(string message, string? operation = null) : base(message) { Operation = operation; } + public int? Code { get; } + public CodexRequestException(string message, string? operation = null, int? code = null) : base(message) + { Operation = operation; Code = code; } } diff --git a/src/platforms/security/SecureFiles.cs b/src/platforms/security/SecureFiles.cs index ce7c7db9..5e8b185f 100644 --- a/src/platforms/security/SecureFiles.cs +++ b/src/platforms/security/SecureFiles.cs @@ -33,7 +33,13 @@ public static void CreatePrivateDirectory(string path) InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow)); new DirectoryInfo(path).SetAccessControl(acl); } - public static void AtomicWrite(string target, byte[] bytes) + public static void AtomicWrite(string target, byte[] bytes) => AtomicWrite(target, bytes, ownedFile: false); + + // These files contain only application-managed data and live under a private directory. + // Publish the staged file by rename without the Windows attribute and stream merge. + internal static void AtomicWriteOwned(string target, byte[] bytes) => AtomicWrite(target, bytes, ownedFile: true); + + private static void AtomicWrite(string target, byte[] bytes, bool ownedFile) { if (OperatingSystem.IsLinux()) { LinuxPrivateFiles.Write(target, bytes); return; } var absolute = Path.GetFullPath(target); @@ -49,7 +55,21 @@ public static void AtomicWrite(string target, byte[] bytes) using (var stream = new FileStream(staging, options)) { stream.Write(bytes); stream.Flush(true); } if (!OperatingSystem.IsWindows()) File.Move(staging, absolute, true); - else if (File.Exists(absolute)) File.Replace(staging, absolute, null); + else if (File.Exists(absolute)) + { + if (ownedFile) + { + var destination = new FileInfo(absolute); + var stagedFile = new FileInfo(staging); + var permissions = new FileSecurity(); + permissions.SetSecurityDescriptorBinaryForm(destination.GetAccessControl(AccessControlSections.Access).GetSecurityDescriptorBinaryForm(), + AccessControlSections.Access); + stagedFile.SetAccessControl(permissions); + if ((destination.Attributes & FileAttributes.Encrypted) != 0) File.Encrypt(staging); + File.Move(staging, absolute, overwrite: true); + } + else File.Replace(staging, absolute, null); + } else File.Move(staging, absolute); } finally { if (File.Exists(staging)) File.Delete(staging); } diff --git a/src/windows/AccountAutomationEvidence.cs b/src/windows/AccountAutomationEvidence.cs index 72ee13e8..54ef316b 100644 --- a/src/windows/AccountAutomationEvidence.cs +++ b/src/windows/AccountAutomationEvidence.cs @@ -95,7 +95,7 @@ MenuItem OpenMenu() var card = Descendants(window).Single(c => ((TextBlock)typeof(AccountTankCard).GetField("_plan", fields)!.GetValue(c)!).Text == "Free"); card.MenuButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent)); var accountMenu = card.MenuButton.ContextMenu!; - var priority = accountMenu.Items.OfType().Single(i => i.Items.Count == 4); + var priority = accountMenu.Items.OfType().Single(i => i.Name == "AutomaticSwitchPriorityMenuItem"); priority.IsSubmenuOpen = true; await Task.Delay(120); _ = NativeHandle((MenuItem)priority.Items[0], "Account priority submenu"); ((MenuItem)priority.Items[0]).RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent)); accountMenu.IsOpen = false; diff --git a/src/windows/AccountCardHeader.cs b/src/windows/AccountCardHeader.cs index 63a4a2d3..37b8debb 100644 --- a/src/windows/AccountCardHeader.cs +++ b/src/windows/AccountCardHeader.cs @@ -1,6 +1,10 @@ using System.Collections.Generic; using System.Windows; using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Shapes; namespace CodexAccountDesk; @@ -25,6 +29,34 @@ public AccountCardHeader(string name, string metadata, Burn0Theme theme, StackPa foreach (Button button in actions.Children) _sizes[button] = (button.Padding, button.MinHeight, button.FontSize); Grid.SetColumn(actions, 1); Children.Add(actions); } + internal void EnableReordering(Burn0Theme theme, System.Action start) + { + foreach (UIElement child in Children) SetColumn(child, GetColumn(child) + 1); + ColumnDefinitions.Insert(0, new ColumnDefinition { Width = GridLength.Auto }); + var dots = new UniformGrid { Rows = 3, Columns = 2, Width = 8, Height = 13, IsHitTestVisible = false }; + for (var i = 0; i < 6; i++) + dots.Children.Add(new Ellipse { Width = 2, Height = 2, Fill = theme.Color("muted") }); + var grip = new Border { Width = 16, Margin = new Thickness(0, 0, 4, 0), Background = Brushes.Transparent, + Cursor = Cursors.SizeAll, ToolTip = Loc.T("dashboard.drag_account"), Child = dots }; + Children.Add(grip); + Point? origin = null; + grip.MouseLeftButtonDown += (_, args) => + { + if (grip.CaptureMouse()) { origin = args.GetPosition(grip); args.Handled = true; } + }; + grip.LostMouseCapture += (_, _) => origin = null; + grip.MouseLeftButtonUp += (_, _) => grip.ReleaseMouseCapture(); + grip.MouseMove += (_, args) => + { + if (origin is not { } from || args.LeftButton != MouseButtonState.Pressed) return; + var distance = args.GetPosition(grip) - from; + if (System.Math.Abs(distance.X) < SystemParameters.MinimumHorizontalDragDistance && + System.Math.Abs(distance.Y) < SystemParameters.MinimumVerticalDragDistance) return; + grip.ReleaseMouseCapture(); + start(grip); + }; + } + public void SetCompact(bool compact) { if (!ReferenceEquals(Actions.Parent, this)) diff --git a/src/windows/AccountTankCard.cs b/src/windows/AccountTankCard.cs index fe74967c..73f5bbb1 100644 --- a/src/windows/AccountTankCard.cs +++ b/src/windows/AccountTankCard.cs @@ -12,6 +12,7 @@ internal sealed record QuotaChoice(string BucketId, string Slot, UsageWindow Win internal sealed class AccountTankCard : Grid { internal Button MenuButton { get; } + internal string AccountKey => _profile.Key; private readonly AccountProfile _profile; private readonly QuotaChoice? _choice; private readonly Burn0Theme _theme; @@ -29,7 +30,18 @@ internal sealed class AccountTankCard : Grid private readonly DockPanel _last; private readonly WrapPanel? _windows; private bool? _compact; - public static QuotaChoice[] Choices(AccountProfile profile) => profile.Usage?.Buckets.SelectMany(bucket => + private Border? _dropTarget; + internal void ShowDropTarget(bool active) + { + if (_dropTarget == null && active) + { + _dropTarget = new Border { BorderBrush = _theme.Color("accent"), BorderThickness = new Thickness(2), + CornerRadius = new CornerRadius(_theme.Number("radius")), IsHitTestVisible = false }; + Children.Add(_dropTarget); + } + if (_dropTarget != null) _dropTarget.Visibility = active ? Visibility.Visible : Visibility.Collapsed; + } + public static QuotaChoice[] Choices(AccountProfile profile) => profile.RequiresLogin ? Array.Empty() : profile.Usage?.Buckets.SelectMany(bucket => new[] { bucket.Primary == null ? null : new QuotaChoice(bucket.Id, "primary", bucket.Primary, bucket.Label), bucket.Secondary == null ? null : new QuotaChoice(bucket.Id, "secondary", bucket.Secondary, bucket.Label) }).OfType().ToArray() ?? Array.Empty(); public static QuotaChoice? SelectQuota(AccountProfile profile, string? selected = null) @@ -103,19 +115,20 @@ public AccountTankCard(AccountProfile profile, QuotaChoice? choice, Burn0Theme t _daysLabel = Text(Loc.T("subscription.left"), 11, "muted"); _daysLabel.Margin = new Thickness(8, 0, 0, 0); _subscriptionLine.Children.Add(_endsLabel); _subscriptionLine.Children.Add(_subscriptionDate); _subscriptionLine.Children.Add(_daysLabel); _subscriptionLine.Children.Add(_subscriptionDays); - var resetCredits = profile.Usage?.AvailableResets; + var usage = profile.RequiresLogin ? null : profile.Usage; + var resetCredits = usage?.AvailableResets; _resetCredits = Text(resetCredits is int count ? Loc.F("초기화권 {0}장", count) : Loc.T("초기화권 —"), 11, "muted"); _resetCredits.ToolTip = resetCredits is int available ? Loc.Count("초기화권 {0}개", available) : Loc.T("초기화권 정보 없음"); - if (profile.Error != null) _resetCredits.ToolTip += "\n" + Loc.T("갱신 실패 · 이전 값"); + if (profile.Error != null && usage != null) _resetCredits.ToolTip += "\n" + Loc.T("갱신 실패 · 이전 값"); _resetCredits.HorizontalAlignment = HorizontalAlignment.Right; _resetCredits.LineHeight = 14; _resetCredits.Margin = new Thickness(8, 0, 0, 0); Grid.SetColumn(_resetCredits, 2); Grid.SetRow(_resetCredits, 1); footer.Children.Add(_resetCredits); _last = new DockPanel { Margin = new Thickness(0, 6, 0, 0) }; - var creditBucket = profile.Usage?.Buckets.FirstOrDefault(b => b.Id == choice?.BucketId) ?? profile.Usage?.Buckets.FirstOrDefault(b => b.Id == "codex") ?? profile.Usage?.Buckets.FirstOrDefault(); + var creditBucket = usage?.Buckets.FirstOrDefault(b => b.Id == choice?.BucketId) ?? usage?.Buckets.FirstOrDefault(b => b.Id == "codex") ?? usage?.Buckets.FirstOrDefault(); _credits = Text(CreditLabel(creditBucket), 11, "muted", FontWeights.Medium); _credits.LineHeight = 14; _credits.VerticalAlignment = VerticalAlignment.Center; _credits.Margin = new Thickness(8, 0, 0, 0); _credits.ToolTip = creditBucket?.UnlimitedCredits == true ? Loc.T("크레딧 제한 없음") : creditBucket?.CreditBalance is string balance ? Loc.F("크레딧 {0}", balance) : Loc.T("크레딧 정보 없음"); DockPanel.SetDock(_credits, Dock.Right); _last.Children.Add(_credits); - _state = Text(profile.Error != null ? Loc.T("갱신 실패 · 이전 값") : profile.IsRefreshing ? Loc.T("갱신 중…") : profile.IsCurrent ? Loc.T("현재 로그인") : Loc.T("등록 계정"), 11, profile.Error != null ? "warning" : "muted"); + _state = Text(profile.RequiresLogin ? Loc.T("account.login_required") : profile.Error != null ? Loc.T("갱신 실패 · 이전 값") : profile.IsRefreshing ? Loc.T("갱신 중…") : profile.IsCurrent ? Loc.T("현재 로그인") : Loc.T("등록 계정"), 11, profile.Error != null ? "warning" : "muted"); _state.VerticalAlignment = VerticalAlignment.Center; _state.TextTrimming = TextTrimming.CharacterEllipsis; _state.ToolTip = profile.Error == null ? null : Loc.Error(profile.Error); _state.Margin = new Thickness(10, 0, 0, 0); _subscriptionLine.Children.Add(_state); _last.Children.Add(_subscriptionLine); Grid.SetRow(_last, 2); Grid.SetColumnSpan(_last, 3); footer.Children.Add(_last); Grid.SetRow(footer, 2); _layout.Children.Add(footer); @@ -196,7 +209,8 @@ public void Update(DateTimeOffset now) _reset.Foreground = _theme.Color(AccountDateWarnings.Reset(_choice?.Window.ResetsAt, now) ? "warning" : "text"); if (_choice == null) { - _depletion.Text = Loc.T(_profile.IsRefreshing ? "측정중" : "정보 없음"); _reset.Text = "—"; return; + _depletion.Text = _profile.RequiresLogin ? "—" : Loc.T(_profile.IsRefreshing ? "측정중" : "정보 없음"); + _reset.Text = "—"; return; } var window = _choice.Window; var forecast = UsagePredictor.Evaluate(window, _trend, now); _depletion.Text = forecast.State == ForecastState.ResetsFirst ? Loc.T("리셋 먼저") diff --git a/src/windows/MainWindow.cs b/src/windows/MainWindow.cs index 54a02c9e..21308f28 100644 --- a/src/windows/MainWindow.cs +++ b/src/windows/MainWindow.cs @@ -35,6 +35,10 @@ internal sealed class MainWindow : Window private readonly TextBlock _status = new(), _loginText = new(); private readonly Border _switchPanel = new() { Name = "AccountSwitchStatus" }; private readonly TextBlock _switchText = new() { TextWrapping = TextWrapping.Wrap, VerticalAlignment = VerticalAlignment.Center }; + private NotificationContent _switchNotification = null!, _footerNotification = null!; + private NotificationDeadline? _switchNotice, _footerNotice; + private string? _noticedRecoveryId; + private readonly DispatcherTimer _notificationTimer = new() { Interval = TimeSpan.FromMilliseconds(100) }; private readonly SessionUsagePanel _sessionCount = new(); private readonly Button _refresh = new(), _add = new(), _cancelLogin = new(), _cancelSwitch = new(); private readonly MenuItem _automaticSwitch = new(); @@ -48,6 +52,9 @@ internal sealed class MainWindow : Window private MenuItem? _importCurrent; private readonly Border _loginPanel = new(); private readonly List _tankCards = new(); + private const string DashboardDragFormat = "CodexSwitch.DashboardAccount"; + private string? _draggingAccount; + private long _lastDragScroll; private readonly Dictionary _selectedQuotas = new(); private readonly Dictionary _details = new(); private readonly HashSet _operations = new(); @@ -80,6 +87,12 @@ internal sealed class MainWindow : Window internal string? EvidenceReloginAccount { get; private set; } private object? _languageInteraction; private object? _alternateWindowFrame; + private readonly record struct NotificationDeadline(long StartedAt, double Seconds) + { + internal static NotificationDeadline Start(bool warning) => new(Stopwatch.GetTimestamp(), warning ? 15 : 8); + internal double Remaining(long now) => Math.Clamp(1 - Stopwatch.GetElapsedTime(StartedAt, now).TotalSeconds / Seconds, 0, 1); + } + public MainWindow(AccountService service, Program.Options options) { _service = service; _options = options; @@ -98,6 +111,7 @@ public MainWindow(AccountService service, Program.Options options) ApplyTheme(); _scroll.SizeChanged += (_, _) => LayoutCards(); _scroll.ScrollChanged += (_, args) => { if (args.ViewportWidthChange != 0) LayoutCards(); }; + _scroll.PreviewDragOver += ScrollAccountDrag; _refresh.Click += async (_, _) => await RefreshAsync(); _add.Click += async (_, _) => await AddAsync(); _cancelLogin.Click += (_, _) => _loginCancellation?.Cancel(); @@ -114,11 +128,13 @@ public MainWindow(AccountService service, Program.Options options) { UpdateFolderMeasurement(); if (IsVisible) _ = RefreshAccountWindowsAsync(); else _windowWatch?.Cancel(); + UpdateNotifications(Stopwatch.GetTimestamp()); }; StateChanged += (_, _) => UpdateFolderMeasurement(); StateChanged += (_, _) => { if (_maximizeButton != null) _maximizeButton.Content = Burn0Theme.Icon(WindowState == WindowState.Maximized ? "window-restore" : "window-maximize", Color("muted"), 12, true); }; _refreshTimer.Tick += async (_, _) => { if (CanRefresh) await RefreshAsync(); }; _clockTimer.Tick += (_, _) => UpdateCountdowns(); + _notificationTimer.Tick += (_, _) => UpdateNotifications(Stopwatch.GetTimestamp()); Activated += (_, _) => _ = RefreshAccountWindowsAsync(); Loaded += async (_, _) => await StartAsync(); Closing += OnClosing; @@ -197,6 +213,7 @@ private void ApplyTheme() _hardwarePanel.Refresh(_hardware.Current, _theme); _drivePanel.Refresh(_drives.Current, _theme); _status.TextWrapping = TextWrapping.NoWrap; _status.TextTrimming = TextTrimming.CharacterEllipsis; + _status.VerticalAlignment = VerticalAlignment.Center; _loginText.Text = Loc.T("브라우저에서 추가할 계정으로 로그인해 주세요."); _loginPanel.Background = Color("surface"); _loginPanel.CornerRadius = new CornerRadius(_theme.Number("radius")); _loginPanel.Padding = new Thickness(12); Content = BuildRoot(); RenderAccounts(); UpdateControls(); RenderStatus(); @@ -253,20 +270,33 @@ private UIElement BuildRoot() Grid.SetColumn(_automaticState, 2); toolbarRow.Children.Add(_automaticState); var login = new DockPanel(); DockPanel.SetDock(_cancelLogin, Dock.Right); login.Children.Add(_cancelLogin); _loginText.TextWrapping = TextWrapping.Wrap; _loginText.VerticalAlignment = VerticalAlignment.Center; _loginText.Margin = new Thickness(0, 0, 12, 0); login.Children.Add(_loginText); _loginPanel.Child = login; _loginPanel.Margin = new Thickness(0, 0, 0, 16); Grid.SetRow(_loginPanel, 1); body.Children.Add(_loginPanel); - var switchContent = new DockPanel(); _cancelSwitch.VerticalAlignment = VerticalAlignment.Center; _cancelSwitch.Margin = new Thickness(8, 0, 0, 0); - DockPanel.SetDock(_cancelSwitch, Dock.Right); - switchContent.Children.Add(_cancelSwitch); switchContent.Children.Add(_switchText); - _switchPanel.Child = switchContent; + _switchNotification = new NotificationContent(_switchText, NotificationClose("DismissSwitchNotification", DismissSwitchNotice), _theme, _cancelSwitch); + _switchPanel.Child = _switchNotification; _switchPanel.Background = Color("surface"); _switchPanel.CornerRadius = new CornerRadius(_theme.Number("radius")); _switchPanel.Padding = new Thickness(10, 6, 10, 6); _switchPanel.Margin = new Thickness(0, 0, 0, 6); modelHeader.Children.Add(_switchPanel); _scroll.Content = _rows; Grid.SetRow(_scroll, 2); body.Children.Add(_scroll); var footer = new StackPanel { Margin = new Thickness(0, 4, 0, 0) }; _hardwarePanel.Margin = new Thickness(0, 0, 0, 4); footer.Children.Add(_hardwarePanel); - footer.Children.Add(_drivePanel); footer.Children.Add(_status); + _footerNotification = new NotificationContent(_status, NotificationClose("DismissFooterNotification", DismissFooterNotice), _theme); + footer.Children.Add(_drivePanel); footer.Children.Add(_footerNotification); Grid.SetRow(footer, 3); body.Children.Add(footer); Grid.SetRow(body, 1); root.Children.Add(body); return root; } + private Button NotificationClose(string name, Action dismiss) + { + var button = NewButton("", "close"); + button.Name = name; + button.ToolTip = Loc.T("닫기"); + System.Windows.Automation.AutomationProperties.SetName(button, Loc.T("닫기")); + button.Width = button.Height = 23; + button.MinHeight = 0; + button.Padding = new Thickness(0); + button.Margin = new Thickness(8, 0, 0, 0); + button.VerticalAlignment = VerticalAlignment.Center; + button.Click += (_, _) => dismiss(); + return button; + } internal ContextMenu HomeActionsMenu() { foreach (var item in new[] { _providers, _automaticSwitch, _restartCodex, _stampTitles }) @@ -716,8 +746,16 @@ private async Task RefreshAccountWindowsAsync() _windowWatch?.Cancel(); _windowWatch?.Dispose(); _windowWatch = CancellationTokenSource.CreateLinkedTokenSource(_lifetime.Token); var token = _windowWatch.Token; - _accountWindows = await Task.Run(() => WindowsAccountWindows.Inventory(_service.Installation.DesktopPath), token); + var (windows, primaryStartedAt) = await Task.Run(() => WindowsAccountWindows.Inventory(_service.Installation.DesktopPath), token); if (_closing || token.IsCancellationRequested) return; + _accountWindows = windows; + if (!_switching && primaryStartedAt is { } started && _service.RetireEmptyWindowsRestart(started)) + { + ClearSwitchNotice(); + _switchWarning = false; + UpdateControls(); + UpdateTray(); + } _windowActivity.Clear(); RenderAccounts(); foreach (var pid in _accountWindows.Values.Where(id => id > 0)) _ = ObserveWindowExitAsync(pid, token); @@ -785,28 +823,31 @@ private string AccountWindowAction(AccountProfile profile) } private void RenderAccounts() { + if (_draggingAccount != null) return; var offset = _scroll.VerticalOffset; _rows.Children.Clear(); _tankCards.Clear(); - var accounts = _service.Accounts; + var accounts = _service.DashboardAccounts(); var pending = PendingSwitch(); RenderSessions(); if (accounts.Length == 0) { var message = Label(Loc.T("현재 계정을 가져오거나 다른 계정으로 로그인하세요."), 14, "muted"); message.Margin = new Thickness(0, 18, 0, 0); _rows.Children.Add(message); return; } - foreach (var profile in accounts.OrderByDescending(a => a.IsCurrent).ThenBy(a => a.DisplayName, StringComparer.CurrentCultureIgnoreCase)) + foreach (var profile in accounts) { var actions = new StackPanel { Orientation = Orientation.Horizontal }; var pendingResume = pending?.TargetAccountKey == profile.Key; - var windowAction = AccountWindowAction(profile); - var allowed = windowAction == "switch.show_window" || SwitchRecovery.AllowsAccount(pending, profile.Key, _service.CurrentKey, manualSwitch: true); + var windowAction = profile.RequiresLogin ? "account.sign_in" : AccountWindowAction(profile); + var allowed = profile.RequiresLogin || windowAction == "switch.show_window" || + SwitchRecovery.AllowsAccount(pending, profile.Key, _service.CurrentKey, manualSwitch: true); var label = profile.Key == _queuedKey && _switching && _switchProgress?.Stage != SwitchStage.AccountWindow ? _switchPhase == SwitchPhase.BackingUp ? "백업 중" : _switchPhase == SwitchPhase.Resuming ? "재개 중" : "전환 중" : windowAction; - var switchButton = NewButton(label, null, !profile.IsCurrent); + var switchButton = NewButton(label, null, true); switchButton.Tag = "account-switch-action"; - switchButton.ToolTip = !allowed ? Loc.Error(pending?.Error ?? "switch.recover_pending") : Loc.T("switch.window_help"); + switchButton.ToolTip = !allowed ? Loc.Error(pending?.Error ?? "switch.recover_pending") : + Loc.T(profile.RequiresLogin ? "account.relogin" : "switch.window_help"); ToolTipService.SetShowOnDisabled(switchButton, !allowed); switchButton.Margin = new Thickness(0); switchButton.FontSize = 12; switchButton.Padding = new Thickness(8, 5, 8, 5); switchButton.IsEnabled = _ready && !_switching && !_stampingTitles && !_loggingIn && !_closing && allowed; - switchButton.Click += async (_, _) => await ShowAccountWindowAsync(profile); actions.Children.Add(switchButton); - if (!_switching && (pendingResume || profile.RequiresApply)) + switchButton.Click += async (_, _) => await ActivateAccountAsync(profile); actions.Children.Add(switchButton); + if (!_switching && !profile.RequiresLogin && (pendingResume || profile.RequiresApply)) { var recovery = NewButton(pendingResume ? "switch.recover" : "로그인 적용"); recovery.Tag = "account-switch-action"; recovery.Margin = new Thickness(3, 0, 0, 0); @@ -823,6 +864,11 @@ private void RenderAccounts() _selectedQuotas.TryGetValue(profile.Key, out var selected); var card = new AccountTankCard(profile, AccountTankCard.SelectQuota(profile, selected), _theme, titleRow, more, selection => { _selectedQuotas[profile.Key] = selection; RenderAccounts(); }); + if (_ready && accounts.Length > 1) + { + titleRow.EnableReordering(_theme, grip => DragAccount(grip, profile.Key)); + SetAccountDropTarget(card); + } _tankCards.Add(card); _rows.Children.Add(card); } LayoutCards(); RefreshDetails(accounts); @@ -831,12 +877,58 @@ private void RenderAccounts() internal string[] EvidenceAccountActions(string key) { if (_options.UiEvidenceDirectory == null) throw new InvalidOperationException("Evidence mode is required."); - var profiles = _service.Accounts.OrderByDescending(a => a.IsCurrent).ThenBy(a => a.DisplayName, StringComparer.CurrentCultureIgnoreCase).ToArray(); - var index = Array.FindIndex(profiles, profile => profile.Key == key); - if (index < 0) throw new InvalidOperationException("Evidence account missing."); - return Descendants(_rows.Children[index]).OfType