diff --git a/Directory.Build.props b/Directory.Build.props
index d03a60a0..e141a91a 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -1,6 +1,6 @@
- 1.45.9
+ 1.45.10
10.0.15
diff --git a/docs/FOLDER_MONITORING.md b/docs/FOLDER_MONITORING.md
index 4e5107ff..9a5a5a6b 100644
--- a/docs/FOLDER_MONITORING.md
+++ b/docs/FOLDER_MONITORING.md
@@ -14,7 +14,7 @@ The visible scan shares one metadata budget across all configured drives: at mos
A spinner appears immediately to the right of a drive's capacity label while uncached directory measurement is active. Cached traversal, permission requests and idle waits do not keep it spinning. It clears after every work slice, completion, cancellation and failure, and does not spin for unrelated drives. The tooltip reports indexed folder/file counts so a large first index shows actual progress. Its animation stops when the indicator is hidden.
-The Windows gauge keeps drive metadata above a separate12px allocation bar. Tracked folders use opaque colors with diagonal texture and visible separators; other used space is neutral and free space stays unfilled. Wide folder segments show their share directly. Small segments retain their measured width and expose the exact share on hover. Drives without tracked folders use the same used/free scale.
+The Windows gauge keeps drive metadata above a separate12px allocation bar. Tracked folders use opaque colors with diagonal texture; other used space is neutral and free space stays unfilled. Wide folder segments show their share directly. A positive allocation smaller than one screen pixel gets one colored pixel, with separators reserved for wider segments. The tooltip retains the actual allocation and share. Drives without tracked folders use the same used/free scale.
CPU, memory, GPU and VRAM use the same separated metadata/current-percentage bars. Quarter marks help compare utilization; missing readings stay empty with an unavailable value. Historical trend graphs remain in the resource tooltip rather than behind the text.
@@ -24,6 +24,10 @@ Up to eight folders can be tracked per drive. Paths must be absolute and inside
Folder measurements run independently after configuration changes. The initial measurement reads tracked trees in bounded cancellable slices and checkpoints directory snapshots, file allocations and pending changes together. Windows filesystem notifications wake the indexer; journal replay identifies actual changes and ignores timestamp-only activity that cannot change allocation. Notifications are grouped for two seconds, and unchanged subtrees are not enumerated again. Cached readings remain available between slices. Root/ancestor identity is checked when restoring an index, rather than repeatedly while unchanged monitoring is idle. Allocation totals for unrelated drives are reused. New or renamed trees are measured at their new paths, deleted entries are removed, and hard-link allocation is counted once per drive. Idle folders have no recurring full-tree scan. Very large first indexes can take longer than one minute and retain completed work when closed.
+The monitor retains each drive's journal status across scan slices. A filesystem change triggers journal replay only on the affected drive with a readable journal. A drive without journal support, such as a mapped drive, can finish its first bounded measurement and update changed directories from live notifications. The monitor rechecks journal support when the watcher resets or the user requests a refresh. Idle index retries consult known failures and reuse successful directory snapshots.
+
+Metadata changes on a tracked folder itself recheck its identity and listing access. Directory timestamp notices generated by traversal do not invalidate their parent listings. Structural changes, file allocation changes, and attribute or security notifications still refresh the affected data. A routine file change does not discard the folder's directory snapshots.
+
Each completed folder/work slice is published immediately. Indexing does not overlap or delay existing disk I/O samples or the UI thread. Removed configurations cancel pending work, and version checks prevent old results from reappearing. Lost notifications use retained journal coverage where available; missing ranges require rebuilding affected data. Deleted roots are watched through an existing ancestor until they return. Unavailable watchers report partial coverage; failed observations and connections retry on the existing sixty-second schedule. Empty, missing, inaccessible, partial, cached and pending readings remain distinct. Tracked file contents are unchanged. Administrative approval is requested only after the user activates the journal-setup lock.
Index-owned SQLite writes are excluded from change invalidation to prevent self-triggered indexing. Their actual allocation is still measured and included when the cache directory is inside a tracked folder. Private cache maintenance is separate from recursive user-folder traversal.
diff --git a/docs/RELEASES.md b/docs/RELEASES.md
index d28401aa..41105c49 100644
--- a/docs/RELEASES.md
+++ b/docs/RELEASES.md
@@ -1,5 +1,13 @@
# Binary releases
+## 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.
+
+Account recovery now shows the current stage, time remaining, retries and cancellation in a dedicated status area. IPC reconnection and chat resume retries reuse a confirmed desktop launch. Empty restarts refresh the chat snapshot before replacement. Ambiguous Continue delivery retains its original message identity. The Windows Store execution alias preserves the registered taskbar identity for account windows.
+
+Drive usage bars retain small tracked-folder segments. Folder monitoring reuses unchanged readings to reduce repeated traversal. The Windows 11 test suite exercised two fictional accounts, focus after rediscovery and reopening one closed window while the other stayed alive. The screenshots show production WPF controls rendered with fictional accounts and a pending recovery. [Earlier account actions](media/release-1.45.10/previous-actions-ko.png) · [Open and Focus](media/release-1.45.10/account-windows-ko.png)
+
[Release1.45.0](https://github.com/Gaebabi/codex-switch/releases/tag/v1.45.0) adds live Windows native/custom model selection, native encrypted-history recovery and deferred custom tool discovery. It retains native OpenAI operation with the Switch editor closed after explicit initial backend setup. macOS/Linux retain their existing support scope. [Changes, setup and publication gates](development/RELEASE_1_45_0.md). The release verification manifest records package provenance and publication checks.
[Release1.44.0](https://github.com/Gaebabi/codex-switch/releases/tag/v1.44.0) simplifies Home around the existing quota tanks: Add/Refresh remain visible while one Settings gear groups global actions. It includes the corrected built-in image endpoints and bounded concurrent handling for image-heavy chats. Windows x64, macOS15+ Apple Silicon/Intel and Linux x64/ARM64 integration preview packages are published; all twelve public assets match their sizes/SHA256, and the Windows ZIP passes99self-tests. [Verification and installation gates](development/RELEASE_1_44_0.md).
diff --git a/docs/development/ACCOUNT_AUTOMATION.md b/docs/development/ACCOUNT_AUTOMATION.md
index af53b121..91c8ec68 100644
--- a/docs/development/ACCOUNT_AUTOMATION.md
+++ b/docs/development/ACCOUNT_AUTOMATION.md
@@ -6,12 +6,20 @@ The **Auto Switch** toolbar menu contains a persistent On/Off toggle and the nex
Choose **Expires soonest first** (default) to consume the earliest known subscription date among eligible accounts, then maximize the lowest remaining percentage across quota windows. Past dates retain priority when fresh usage still qualifies; unknown dates follow known dates, and equal/unknown dates use remaining usage and stable account keys. A past date never overrides a server restriction or creates entitlement. This compares reported percentages, not inferred token counts or purchased credits. **Custom priority** chooses the first eligible account in the saved order. Each account's menu has **Priority 1/2/...**; choosing a position moves that account there, shifts the others and selects custom mode without enabling automation. The menu also shows the next eligible account even before the current quota crosses its threshold, using the same candidate guards/ranking. This read-only forecast does not reserve or start a handoff, can change after a refresh, and retains an existing pending-recovery target. It refreshes on menu opening and normal UI updates; there is no extra poller. No eligible account is explicit. The toolbar tooltip retains On/Off state and the forecast. The menu also shows the complete custom order. Invalid or restricted high-priority accounts are skipped; priority never bypasses freshness, minimum remaining, cooldown or recovery guards. Unranked/new accounts follow saved ranks in stable key order. Returning to automatic mode preserves the saved custom order.
-Automatic handoff uses the same checkpointed backup, normal shutdown, account application, launch and eligible continuation coordinator as manual switching. Checkpoints are saved before shutdown and credential application. A transient I/O, discovery timeout or native launch failure gets at most **two additional retries**, with a one-second cancellable wait between attempts. The retry budget is shared across all stages and saved before each retry. Both UIs keep the target action disabled in its current switching/resuming state throughout these retries; **Recover** appears only after recovery is exhausted or a non-retryable refusal stops the operation. Confirmed names, applied credentials and completed chats are preserved. Each retry checks account identity again; a write that already reached the target is reconciled without applying it twice. Ambiguous Continue delivery can only be observed, never resent.
+On Windows, manual account cards offer **Open** or **Focus**. Each additional account has a private native home and Electron profile on the same machine. Chat history belongs to that account window. Open discovers the window from its executable, profile argument and process creation time. An existing account window confirms the selected user and workspace through its live app-server before Switch brings it forward. Closing and reopening Switch rediscovers running windows. The dashboard subscribes to active chat counts for verified account windows. A login change or disconnection invalidates that observation. This view shares activity counts and keeps each account's conversation content in its own home.
-Cancellation and account mismatch stop the switch immediately. Integrity or permission refusals do not trigger a retry. After cancellation or a failed account application following confirmed shutdown, the coordinator retains one bounded (35-second) safety attempt to reopen the recorded source/target desktop without changing credentials or sending Continue. Exhausted launch retries do not add a fourth launch. A failed/unconfirmed shutdown never invokes the launcher or applies credentials; its recovery record remains available. A failed automatic handoff disables further automatic switching. **Recover** remains available on the recorded target even while the original account is still current, and other targets cannot replace the pending plan. Clicking Recover explicitly starts a fresh two-retry budget.
+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.
+
+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.
+
+**Recover** remains available on the recorded account even while the original account is current. Clicking it starts a fresh two-retry budget. An explicit switch can replace a manual, pre-application same-account restart only when it has zero saved chats and no model or credit action. Recovering that empty restart also captures the current chats again. The original checkpoint stays in place until the same source login and fresh chat capture are both verified.
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.
+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.
Both UIs distinguish **Renews** from **Expires** and show **Days left** in Korean calendar days. Subscription data is read from the official first-party `GET /backend-api/accounts/check/v4-2023-04-27` endpoint using the selected account's managed access token and `ChatGPT-Account-ID`. This internal endpoint is observed in the official desktop26.1106.6628.0 billing flow; it is not a documented public API. Only the exact matching account entry is accepted. Active auto-renewal uses `entitlement.renews_at`; a non-renewing subscription uses `expires_at`, then `cancels_at` when expiration is absent. Missing dates stay unknown and malformed dates fail explicitly. Successful queries, including inactive results, replace the encrypted billing snapshot. Login claims are not current billing evidence: even successful token refresh can return an old period. Credential synchronization cannot overwrite a verified billing snapshot. Identity/revision guards discard obsolete results; a billing failure keeps the previous successful timestamp and displays an error while quota refresh remains available. No extra token rotation, account switching, browser cookies or owner restart is needed.
diff --git a/docs/media/release-1.45.10/account-windows-ko.png b/docs/media/release-1.45.10/account-windows-ko.png
new file mode 100644
index 00000000..ecf5aa10
Binary files /dev/null and b/docs/media/release-1.45.10/account-windows-ko.png differ
diff --git a/docs/media/release-1.45.10/previous-actions-ko.png b/docs/media/release-1.45.10/previous-actions-ko.png
new file mode 100644
index 00000000..f84037fd
Binary files /dev/null and b/docs/media/release-1.45.10/previous-actions-ko.png differ
diff --git a/localization/packs/de.json b/localization/packs/de.json
index 1a19ad7d..39584f14 100644
--- a/localization/packs/de.json
+++ b/localization/packs/de.json
@@ -125,6 +125,8 @@
"restart.title": "Restart Codex",
"restart.help": "Restart Codex with the current login and reopen eligible unfinished chats. Running/completed work is checked before sending Continue.",
"restart.done": "Codex restarted and eligible chats resumed.",
+ "restart.opened": "Codex wurde neu gestartet.",
+ "switch.opened": "Das Konto wurde gewechselt und Codex geöffnet.",
"restart.login_changed": "The current login changed or is unavailable. Restart was cancelled.",
"credits.history": "Credits",
"credits.balance": "Guthaben",
@@ -166,6 +168,35 @@
"auto.threshold": "Unter {0}% verbleibend",
"auto.paused": "Automatischer Wechsel pausiert. Beim ausstehenden Konto Fortsetzen wählen.",
"switch.recover": "Fortsetzen",
+ "switch.window_alias": "Aktivieren Sie den App-Ausführungsalias für ChatGPT Desktop in Windows.",
+ "switch.active_chats": "Laufende Chats · {0}",
+ "switch.window_peer": "Der Server des Fensters konnte nicht bestätigt werden.",
+ "switch.window_parent": "Die Verbindung gehört zu einem anderen Fenster.",
+ "switch.window_policy": "Automatischer Wechsel und Guthabenschutz erfordern eine einzelne Codex-Sitzung.",
+ "switch.window_policy_change": "Schließen Sie die separaten Kontofenster, bevor Sie diese Einstellung ändern.",
+ "switch.open_window": "Öffnen",
+ "switch.show_window": "Anzeigen",
+ "switch.find_action": "Fenster suchen",
+ "switch.window_help": "Codex für dieses Konto öffnen oder in den Vordergrund holen.",
+ "switch.primary_ready": "Das Hauptfenster von Codex ist im Vordergrund.",
+ "switch.find_window": "Kontofenster wird gesucht…",
+ "switch.window_ready": "Codex-Fenster für {0} geöffnet.",
+ "switch.window_focus": "Wählen Sie das Kontofenster in der Taskleiste.",
+ "switch.window_lost": "Das Fenster wurde geschlossen. Wählen Sie erneut Wechseln.",
+ "switch.window_wait": "Prüfen Sie den Start oder die Anmeldung von Codex.",
+ "switch.window_identity": "Das Konto des Fensters konnte nicht bestätigt werden.",
+ "switch.window_relogin": "Melden Sie sich mit diesem Konto erneut an.",
+ "switch.window_busy": "Schließen Sie das Kontofenster, um die Anmeldung zu übernehmen oder die Registrierung zu entfernen.",
+ "switch.window_shutdown": "Schließen Sie separate Kontofenster vor dem Neustart von Codex.",
+ "switch.discovering": "Anmeldung und laufende Chats werden geprüft…",
+ "switch.connecting": "Codex-Chatverbindung wird geprüft…",
+ "switch.model_profile": "Codex-Modellprofil wird geprüft…",
+ "switch.recover_pending": "Wählen Sie beim betreffenden Konto „Fortsetzen“, um den ausstehenden Wechsel oder Neustart abzuschließen.",
+ "switch.countdown": "{0} · Noch bis zu {1} s",
+ "switch.settling": "{0} · Ergebnis wird geprüft",
+ "switch.cancelling": "Kontowechsel wird abgebrochen…",
+ "switch.timeout": "{0} Das Zeitlimit von {1} s wurde erreicht.",
+ "switch.retrying": "Wiederholung {0} von {1}",
"switch.restart_failed": "Codex konnte nicht starten. Fortsetzen erneut versuchen: {0}",
"io.read": "Datenträger lesen",
"io.write": "Datenträger schreiben",
diff --git a/localization/packs/en.json b/localization/packs/en.json
index b201964a..f9fa822e 100644
--- a/localization/packs/en.json
+++ b/localization/packs/en.json
@@ -125,6 +125,8 @@
"restart.title": "Restart Codex",
"restart.help": "Restart Codex with the current login and reopen eligible unfinished chats. Running/completed work is checked before sending Continue.",
"restart.done": "Codex restarted and eligible chats resumed.",
+ "restart.opened": "Codex restarted.",
+ "switch.opened": "Account switched and Codex opened.",
"restart.login_changed": "The current login changed or is unavailable. Restart was cancelled.",
"credits.history": "Credits",
"credits.balance": "Balance",
@@ -166,6 +168,35 @@
"auto.threshold": "Below {0}% remaining",
"auto.paused": "Automatic switching paused. Use Recover on the pending account.",
"switch.recover": "Recover",
+ "switch.window_alias": "Enable the ChatGPT Desktop app execution alias in Windows settings to open a separate account window.",
+ "switch.active_chats": "Running chats: {0}",
+ "switch.window_peer": "Could not verify the account window’s backend.",
+ "switch.window_parent": "The account connection belongs to another window.",
+ "switch.window_policy": "Automatic switching and credit protection require one Codex session. Your current settings prevent opening a separate account window.",
+ "switch.window_policy_change": "Close the separate Codex account windows before changing this setting.",
+ "switch.open_window": "Open",
+ "switch.show_window": "Focus",
+ "switch.find_action": "Find window",
+ "switch.window_help": "Open this account’s Codex window or bring it to the front.",
+ "switch.primary_ready": "The primary Codex window is in front.",
+ "switch.find_window": "Finding the account window…",
+ "switch.window_ready": "Opened the Codex window for {0}.",
+ "switch.window_focus": "Windows kept the other window in front. Select the account window on the taskbar.",
+ "switch.window_lost": "The account window closed during activation. Select Switch to open it again.",
+ "switch.window_wait": "Codex has not shown a window for this account yet. Check its startup or login prompt.",
+ "switch.window_identity": "Could not verify which account owns this window.",
+ "switch.window_relogin": "Sign in again for this account.",
+ "switch.window_busy": "Close this account’s Codex window to apply the new login or remove the registration.",
+ "switch.window_shutdown": "Close the separate account windows before restarting the primary Codex desktop.",
+ "switch.discovering": "Checking the login and active chats…",
+ "switch.connecting": "Checking Codex’s chat connection…",
+ "switch.model_profile": "Checking the Codex model profile…",
+ "switch.recover_pending": "Recover the pending switch or restart using the Recover button on its account.",
+ "switch.countdown": "{0} · Up to {1} s left",
+ "switch.settling": "{0} · Confirming the outcome",
+ "switch.cancelling": "Cancelling the switch…",
+ "switch.timeout": "{0} The {1} s time limit was reached.",
+ "switch.retrying": "Retry {0} of {1}",
"switch.restart_failed": "Codex could not restart. Retry Recover: {0}",
"io.read": "Disk read",
"io.write": "Disk write",
diff --git a/localization/packs/es.json b/localization/packs/es.json
index 2c254363..9e299c33 100644
--- a/localization/packs/es.json
+++ b/localization/packs/es.json
@@ -125,6 +125,8 @@
"restart.title": "Restart Codex",
"restart.help": "Restart Codex with the current login and reopen eligible unfinished chats. Running/completed work is checked before sending Continue.",
"restart.done": "Codex restarted and eligible chats resumed.",
+ "restart.opened": "Se reinició Codex.",
+ "switch.opened": "Se cambió la cuenta y se abrió Codex.",
"restart.login_changed": "The current login changed or is unavailable. Restart was cancelled.",
"credits.history": "Créditos",
"credits.balance": "Saldo",
@@ -166,6 +168,35 @@
"auto.threshold": "Por debajo del {0}%",
"auto.paused": "Cambio automático pausado. Usa Recuperar en la cuenta pendiente.",
"switch.recover": "Recuperar",
+ "switch.window_alias": "Activa el alias de ejecución de ChatGPT Desktop en Windows.",
+ "switch.active_chats": "Chats activos · {0}",
+ "switch.window_peer": "No se pudo verificar el servidor de la ventana.",
+ "switch.window_parent": "La conexión pertenece a otra ventana.",
+ "switch.window_policy": "El cambio automático y la protección de créditos requieren una sola sesión de Codex.",
+ "switch.window_policy_change": "Cierra las ventanas de otras cuentas antes de cambiar esta opción.",
+ "switch.open_window": "Abrir",
+ "switch.show_window": "Enfocar",
+ "switch.find_action": "Buscar ventana",
+ "switch.window_help": "Abrir Codex para esta cuenta o mostrar su ventana.",
+ "switch.primary_ready": "La ventana principal de Codex está en primer plano.",
+ "switch.find_window": "Buscando la ventana de la cuenta…",
+ "switch.window_ready": "Se abrió la ventana de Codex de {0}.",
+ "switch.window_focus": "Selecciona la ventana de la cuenta en la barra de tareas.",
+ "switch.window_lost": "La ventana se cerró. Vuelve a seleccionar Cambiar.",
+ "switch.window_wait": "Revisa el inicio de Codex o el inicio de sesión.",
+ "switch.window_identity": "No se pudo verificar la cuenta de esta ventana.",
+ "switch.window_relogin": "Vuelve a iniciar sesión en esta cuenta.",
+ "switch.window_busy": "Cierra la ventana de esta cuenta para aplicar el acceso o quitar el registro.",
+ "switch.window_shutdown": "Cierra las ventanas de las otras cuentas antes de reiniciar Codex.",
+ "switch.discovering": "Comprobando la sesión y los chats activos…",
+ "switch.connecting": "Comprobando la conexión con los chats de Codex…",
+ "switch.model_profile": "Comprobando el perfil de modelos de Codex…",
+ "switch.recover_pending": "Usa el botón Recuperar de la cuenta correspondiente para continuar el cambio o reinicio pendiente.",
+ "switch.countdown": "{0} · Quedan hasta {1} s",
+ "switch.settling": "{0} · Confirmando el resultado",
+ "switch.cancelling": "Cancelando el cambio de cuenta…",
+ "switch.timeout": "{0} Se alcanzó el límite de {1} s.",
+ "switch.retrying": "Reintento {0} de {1}",
"switch.restart_failed": "No se pudo reiniciar Codex. Reintenta Recuperar: {0}",
"io.read": "Lectura de disco",
"io.write": "Escritura de disco",
diff --git a/localization/packs/fr.json b/localization/packs/fr.json
index b554b029..3626cf52 100644
--- a/localization/packs/fr.json
+++ b/localization/packs/fr.json
@@ -125,6 +125,8 @@
"restart.title": "Restart Codex",
"restart.help": "Restart Codex with the current login and reopen eligible unfinished chats. Running/completed work is checked before sending Continue.",
"restart.done": "Codex restarted and eligible chats resumed.",
+ "restart.opened": "Codex a redémarré.",
+ "switch.opened": "Le compte a été changé et Codex a été ouvert.",
"restart.login_changed": "The current login changed or is unavailable. Restart was cancelled.",
"credits.history": "Crédits",
"credits.balance": "Solde",
@@ -166,6 +168,35 @@
"auto.threshold": "Sous {0}% restant",
"auto.paused": "Changement automatique suspendu. Choisissez Reprendre sur le compte en attente.",
"switch.recover": "Reprendre",
+ "switch.window_alias": "Activez l’alias d’exécution de ChatGPT Desktop dans Windows.",
+ "switch.active_chats": "Conversations en cours · {0}",
+ "switch.window_peer": "Impossible de vérifier le serveur de cette fenêtre.",
+ "switch.window_parent": "La connexion appartient à une autre fenêtre.",
+ "switch.window_policy": "Le changement automatique et la protection des crédits exigent une seule session Codex.",
+ "switch.window_policy_change": "Fermez les fenêtres des autres comptes avant de modifier ce réglage.",
+ "switch.open_window": "Ouvrir",
+ "switch.show_window": "Afficher",
+ "switch.find_action": "Chercher",
+ "switch.window_help": "Ouvrir ou afficher la fenêtre Codex de ce compte.",
+ "switch.primary_ready": "La fenêtre principale de Codex est au premier plan.",
+ "switch.find_window": "Recherche de la fenêtre du compte…",
+ "switch.window_ready": "La fenêtre Codex de {0} est ouverte.",
+ "switch.window_focus": "Sélectionnez la fenêtre du compte dans la barre des tâches.",
+ "switch.window_lost": "La fenêtre a été fermée. Relancez le changement de compte.",
+ "switch.window_wait": "Vérifiez le démarrage ou la connexion de Codex.",
+ "switch.window_identity": "Impossible de vérifier le compte de cette fenêtre.",
+ "switch.window_relogin": "Reconnectez-vous à ce compte.",
+ "switch.window_busy": "Fermez la fenêtre de ce compte pour appliquer la connexion ou supprimer son inscription.",
+ "switch.window_shutdown": "Fermez les fenêtres des autres comptes avant de redémarrer Codex.",
+ "switch.discovering": "Vérification de la connexion et des conversations actives…",
+ "switch.connecting": "Vérification de la connexion aux conversations Codex…",
+ "switch.model_profile": "Vérification du profil de modèles Codex…",
+ "switch.recover_pending": "Utilisez le bouton Reprendre du compte concerné pour poursuivre le changement ou le redémarrage en attente.",
+ "switch.countdown": "{0} · Jusqu’à {1} s restantes",
+ "switch.settling": "{0} · Vérification du résultat",
+ "switch.cancelling": "Annulation du changement de compte…",
+ "switch.timeout": "{0} Le délai de {1} s est écoulé.",
+ "switch.retrying": "Nouvelle tentative {0} sur {1}",
"switch.restart_failed": "Impossible de relancer Codex. Réessayez Reprendre : {0}",
"io.read": "Lecture disque",
"io.write": "Écriture disque",
diff --git a/localization/packs/ja.json b/localization/packs/ja.json
index 7a20222b..e481a4a8 100644
--- a/localization/packs/ja.json
+++ b/localization/packs/ja.json
@@ -125,6 +125,8 @@
"restart.title": "Restart Codex",
"restart.help": "Restart Codex with the current login and reopen eligible unfinished chats. Running/completed work is checked before sending Continue.",
"restart.done": "Codex restarted and eligible chats resumed.",
+ "restart.opened": "Codex を再起動しました。",
+ "switch.opened": "アカウントを切り替え、Codex を開きました。",
"restart.login_changed": "The current login changed or is unavailable. Restart was cancelled.",
"credits.history": "クレジット",
"credits.balance": "残高",
@@ -166,6 +168,35 @@
"auto.threshold": "残量{0}%未満",
"auto.paused": "自動切替を停止しました。対象アカウントの復旧を選択してください。",
"switch.recover": "復旧",
+ "switch.window_alias": "Windows 設定で ChatGPT Desktop のアプリ実行エイリアスを有効にしてください。",
+ "switch.active_chats": "進行中のチャット {0} 件",
+ "switch.window_peer": "ウィンドウのバックエンドを確認できません。",
+ "switch.window_parent": "別のウィンドウの接続です。",
+ "switch.window_policy": "自動切り替えとクレジット保護には単一の Codex セッションが必要です。",
+ "switch.window_policy_change": "この設定を変更する前に別のアカウントのウィンドウを閉じてください。",
+ "switch.open_window": "開く",
+ "switch.show_window": "前面へ",
+ "switch.find_action": "検索",
+ "switch.window_help": "このアカウントの Codex を開くか前面に表示します。",
+ "switch.primary_ready": "メインの Codex ウィンドウを前面に表示しました。",
+ "switch.find_window": "アカウントのウィンドウを検索中…",
+ "switch.window_ready": "{0} の Codex ウィンドウを開きました。",
+ "switch.window_focus": "タスクバーからアカウントのウィンドウを選択してください。",
+ "switch.window_lost": "ウィンドウが閉じました。もう一度切り替えてください。",
+ "switch.window_wait": "ウィンドウが表示されません。起動やログインの画面を確認してください。",
+ "switch.window_identity": "ウィンドウのアカウントを確認できません。",
+ "switch.window_relogin": "このアカウントで再度ログインしてください。",
+ "switch.window_busy": "ログインの適用や登録の削除にはアカウントのウィンドウを閉じてください。",
+ "switch.window_shutdown": "再起動する前に別のアカウントのウィンドウを閉じてください。",
+ "switch.discovering": "ログインと進行中のチャットを確認中…",
+ "switch.connecting": "Codex のチャット接続を確認中…",
+ "switch.model_profile": "Codex のモデルプロファイルを確認中…",
+ "switch.recover_pending": "該当するアカウントの「復旧」ボタンで切り替えまたは再起動を続けてください。",
+ "switch.countdown": "{0} · 残り最大 {1} 秒",
+ "switch.settling": "{0} · 結果を確認中",
+ "switch.cancelling": "切り替えをキャンセル中…",
+ "switch.timeout": "{0} 制限時間の {1} 秒に達しました。",
+ "switch.retrying": "再試行 {0}/{1}",
"switch.restart_failed": "Codexを再起動できませんでした。復旧を再試行: {0}",
"io.read": "ディスク読み取り",
"io.write": "ディスク書き込み",
diff --git a/localization/packs/ko.json b/localization/packs/ko.json
index 17e64c62..bd70a2b5 100644
--- a/localization/packs/ko.json
+++ b/localization/packs/ko.json
@@ -125,6 +125,8 @@
"restart.title": "Restart Codex",
"restart.help": "현재 로그인을 유지해 Codex를 재시작하고 미완료 채팅을 다시 엽니다. 실행 중이거나 완료된 작업을 확인한 뒤 필요한 채팅에만 이어가기를 보냅니다.",
"restart.done": "Codex를 재시작하고 재개 대상 채팅을 이어갔습니다.",
+ "restart.opened": "Codex를 재시작했습니다.",
+ "switch.opened": "계정을 전환하고 Codex를 열었습니다.",
"restart.login_changed": "현재 로그인이 변경되었거나 확인되지 않아 재시작을 중단했습니다.",
"credits.history": "크레딧",
"credits.balance": "잔액",
@@ -166,6 +168,35 @@
"auto.threshold": "잔여량 {0}% 미만",
"auto.paused": "자동 전환을 중지했습니다. 대상 계정의 복구 버튼을 눌러 주세요.",
"switch.recover": "복구",
+ "switch.window_alias": "별도 계정 창을 열려면 Windows의 앱 실행 별칭 설정에서 ChatGPT Desktop을 켜세요.",
+ "switch.active_chats": "진행 중인 채팅 {0}개",
+ "switch.window_peer": "계정 창의 백엔드를 확인할 수 없습니다.",
+ "switch.window_parent": "다른 창의 계정 연결이 감지됐습니다.",
+ "switch.window_policy": "자동 전환이나 크레딧 보호를 사용하려면 Codex 세션이 하나여야 합니다. 현재 설정에서는 별도 계정 창을 열 수 없습니다.",
+ "switch.window_policy_change": "이 설정을 변경하기 전에 별도로 연 계정 창을 닫으세요.",
+ "switch.open_window": "켜기",
+ "switch.show_window": "창으로 이동",
+ "switch.find_action": "창 찾기",
+ "switch.window_help": "이 계정의 Codex 창을 열거나 앞으로 가져옵니다.",
+ "switch.primary_ready": "기본 Codex 창을 앞으로 가져왔습니다.",
+ "switch.find_window": "계정 창을 찾는 중…",
+ "switch.window_ready": "{0} 계정의 Codex 창을 열었습니다.",
+ "switch.window_focus": "Windows가 다른 창을 앞에 유지했습니다. 작업표시줄에서 계정 창을 선택하세요.",
+ "switch.window_lost": "전환 중 계정 창이 닫혔습니다. 전환을 다시 누르면 열립니다.",
+ "switch.window_wait": "계정 창이 아직 나타나지 않았습니다. Codex의 시작 또는 로그인 화면을 확인하세요.",
+ "switch.window_identity": "이 창에 연결된 계정을 확인할 수 없습니다.",
+ "switch.window_relogin": "이 계정으로 다시 로그인하세요.",
+ "switch.window_busy": "새 로그인 적용 또는 등록 제거를 위해 해당 계정의 Codex 창을 닫으세요.",
+ "switch.window_shutdown": "기본 Codex를 재시작하려면 별도로 연 계정 창을 먼저 닫으세요.",
+ "switch.discovering": "로그인과 진행 중인 채팅 확인 중…",
+ "switch.connecting": "Codex 채팅 연결 확인 중…",
+ "switch.model_profile": "Codex 모델 프로필 확인 중…",
+ "switch.recover_pending": "해당 계정의 ‘복구’ 버튼으로 남은 전환 또는 재시작을 이어가세요.",
+ "switch.countdown": "{0} · 최대 {1}초 남음",
+ "switch.settling": "{0} · 처리 결과 확인 중",
+ "switch.cancelling": "전환 취소 중…",
+ "switch.timeout": "{0} 제한 시간 {1}초를 넘겼습니다.",
+ "switch.retrying": "재시도 {0}/{1}",
"switch.restart_failed": "Codex를 다시 열지 못했습니다. 복구를 다시 시도해 주세요: {0}",
"io.read": "디스크 읽기",
"io.write": "디스크 쓰기",
diff --git a/localization/packs/pt-BR.json b/localization/packs/pt-BR.json
index fffe2802..c44c9dd5 100644
--- a/localization/packs/pt-BR.json
+++ b/localization/packs/pt-BR.json
@@ -125,6 +125,8 @@
"restart.title": "Restart Codex",
"restart.help": "Restart Codex with the current login and reopen eligible unfinished chats. Running/completed work is checked before sending Continue.",
"restart.done": "Codex restarted and eligible chats resumed.",
+ "restart.opened": "O Codex foi reiniciado.",
+ "switch.opened": "A conta foi trocada e o Codex foi aberto.",
"restart.login_changed": "The current login changed or is unavailable. Restart was cancelled.",
"credits.history": "Créditos",
"credits.balance": "Saldo",
@@ -166,6 +168,35 @@
"auto.threshold": "Abaixo de {0}% restante",
"auto.paused": "Troca automática pausada. Use Recuperar na conta pendente.",
"switch.recover": "Recuperar",
+ "switch.window_alias": "Ative o alias de execução do ChatGPT Desktop no Windows.",
+ "switch.active_chats": "Conversas em andamento · {0}",
+ "switch.window_peer": "Não foi possível verificar o servidor da janela.",
+ "switch.window_parent": "A conexão pertence a outra janela.",
+ "switch.window_policy": "A troca automática e a proteção de créditos exigem uma única sessão do Codex.",
+ "switch.window_policy_change": "Feche as janelas das outras contas antes de alterar essa configuração.",
+ "switch.open_window": "Abrir",
+ "switch.show_window": "Focar",
+ "switch.find_action": "Localizar",
+ "switch.window_help": "Abra ou traga para frente a janela do Codex desta conta.",
+ "switch.primary_ready": "A janela principal do Codex está em primeiro plano.",
+ "switch.find_window": "Procurando a janela da conta…",
+ "switch.window_ready": "A janela do Codex de {0} foi aberta.",
+ "switch.window_focus": "Selecione a janela da conta na barra de tarefas.",
+ "switch.window_lost": "A janela foi fechada. Selecione Trocar novamente.",
+ "switch.window_wait": "Verifique a inicialização ou o login do Codex.",
+ "switch.window_identity": "Não foi possível confirmar a conta da janela.",
+ "switch.window_relogin": "Entre novamente nesta conta.",
+ "switch.window_busy": "Feche a janela da conta para aplicar o login ou remover o cadastro.",
+ "switch.window_shutdown": "Feche as janelas das outras contas antes de reiniciar o Codex.",
+ "switch.discovering": "Verificando o login e as conversas ativas…",
+ "switch.connecting": "Verificando a conexão com as conversas do Codex…",
+ "switch.model_profile": "Verificando o perfil de modelos do Codex…",
+ "switch.recover_pending": "Use o botão Recuperar na conta correspondente para continuar a troca ou a reinicialização pendente.",
+ "switch.countdown": "{0} · Restam até {1} s",
+ "switch.settling": "{0} · Confirmando o resultado",
+ "switch.cancelling": "Cancelando a troca de conta…",
+ "switch.timeout": "{0} O limite de {1} s foi atingido.",
+ "switch.retrying": "Nova tentativa {0} de {1}",
"switch.restart_failed": "Não foi possível reiniciar Codex. Tente Recuperar: {0}",
"io.read": "Leitura do disco",
"io.write": "Gravação do disco",
diff --git a/localization/packs/zh-CN.json b/localization/packs/zh-CN.json
index 8f94f17e..3e54ee86 100644
--- a/localization/packs/zh-CN.json
+++ b/localization/packs/zh-CN.json
@@ -125,6 +125,8 @@
"restart.title": "Restart Codex",
"restart.help": "Restart Codex with the current login and reopen eligible unfinished chats. Running/completed work is checked before sending Continue.",
"restart.done": "Codex restarted and eligible chats resumed.",
+ "restart.opened": "已重启 Codex。",
+ "switch.opened": "已切换账户并打开 Codex。",
"restart.login_changed": "The current login changed or is unavailable. Restart was cancelled.",
"credits.history": "点数",
"credits.balance": "余额",
@@ -166,6 +168,35 @@
"auto.threshold": "剩余低于{0}%",
"auto.paused": "自动切换已停止。请在目标账号上选择恢复。",
"switch.recover": "恢复",
+ "switch.window_alias": "请在 Windows 设置中启用 ChatGPT Desktop 的应用执行别名。",
+ "switch.active_chats": "正在进行的聊天 {0} 个",
+ "switch.window_peer": "无法验证此窗口的后台进程。",
+ "switch.window_parent": "此连接属于其他窗口。",
+ "switch.window_policy": "自动切换和额度保护需要单个 Codex 会话。",
+ "switch.window_policy_change": "更改此设置前请关闭单独的账户窗口。",
+ "switch.open_window": "打开",
+ "switch.show_window": "切至窗口",
+ "switch.find_action": "查找窗口",
+ "switch.window_help": "打开此账户的 Codex 或将其窗口置于前台。",
+ "switch.primary_ready": "Codex 主窗口已置于前台。",
+ "switch.find_window": "正在查找账户窗口…",
+ "switch.window_ready": "已打开 {0} 的 Codex 窗口。",
+ "switch.window_focus": "请从任务栏选择该账户的窗口。",
+ "switch.window_lost": "窗口已关闭。请再次选择切换。",
+ "switch.window_wait": "请检查 Codex 的启动或登录窗口。",
+ "switch.window_identity": "无法验证此窗口所属的账户。",
+ "switch.window_relogin": "请重新登录此账户。",
+ "switch.window_busy": "请关闭此账户的窗口以应用新登录或移除注册。",
+ "switch.window_shutdown": "请先关闭单独的账户窗口,再重启 Codex。",
+ "switch.discovering": "正在检查登录状态和进行中的聊天…",
+ "switch.connecting": "正在检查 Codex 聊天连接…",
+ "switch.model_profile": "正在检查 Codex 模型配置…",
+ "switch.recover_pending": "请使用对应账户的“恢复”按钮继续未完成的切换或重启。",
+ "switch.countdown": "{0} · 最多还需 {1} 秒",
+ "switch.settling": "{0} · 正在确认结果",
+ "switch.cancelling": "正在取消切换…",
+ "switch.timeout": "{0} 已达到 {1} 秒的时限。",
+ "switch.retrying": "重试 {0}/{1}",
"switch.restart_failed": "无法重启Codex。请重试恢复:{0}",
"io.read": "磁盘读取",
"io.write": "磁盘写入",
diff --git a/localization/packs/zh-TW.json b/localization/packs/zh-TW.json
index d7c71fec..445d77bb 100644
--- a/localization/packs/zh-TW.json
+++ b/localization/packs/zh-TW.json
@@ -125,6 +125,8 @@
"restart.title": "Restart Codex",
"restart.help": "Restart Codex with the current login and reopen eligible unfinished chats. Running/completed work is checked before sending Continue.",
"restart.done": "Codex restarted and eligible chats resumed.",
+ "restart.opened": "已重新啟動 Codex。",
+ "switch.opened": "已切換帳戶並開啟 Codex。",
"restart.login_changed": "The current login changed or is unavailable. Restart was cancelled.",
"credits.history": "點數",
"credits.balance": "餘額",
@@ -166,6 +168,35 @@
"auto.threshold": "剩餘低於{0}%",
"auto.paused": "自動切換已停止。請在目標帳號上選擇復原。",
"switch.recover": "復原",
+ "switch.window_alias": "請在 Windows 設定中啟用 ChatGPT Desktop 的應用程式執行別名。",
+ "switch.active_chats": "進行中的聊天 {0} 個",
+ "switch.window_peer": "無法驗證此視窗的背景程序。",
+ "switch.window_parent": "此連線屬於其他視窗。",
+ "switch.window_policy": "自動切換和額度保護需要單一 Codex 工作階段。",
+ "switch.window_policy_change": "變更此設定前請關閉獨立帳戶視窗。",
+ "switch.open_window": "開啟",
+ "switch.show_window": "切換視窗",
+ "switch.find_action": "尋找視窗",
+ "switch.window_help": "開啟此帳戶的 Codex 或將其視窗移至前景。",
+ "switch.primary_ready": "Codex 主視窗已移至前景。",
+ "switch.find_window": "正在尋找帳戶視窗…",
+ "switch.window_ready": "已開啟 {0} 的 Codex 視窗。",
+ "switch.window_focus": "請從工作列選取該帳戶的視窗。",
+ "switch.window_lost": "視窗已關閉。請再次選取切換。",
+ "switch.window_wait": "請檢查 Codex 的啟動或登入視窗。",
+ "switch.window_identity": "無法確認此視窗所屬的帳戶。",
+ "switch.window_relogin": "請重新登入此帳戶。",
+ "switch.window_busy": "請關閉此帳戶的視窗以套用新登入或移除註冊。",
+ "switch.window_shutdown": "請先關閉獨立帳戶視窗,再重新啟動 Codex。",
+ "switch.discovering": "正在檢查登入狀態與進行中的聊天…",
+ "switch.connecting": "正在檢查 Codex 聊天連線…",
+ "switch.model_profile": "正在檢查 Codex 模型設定…",
+ "switch.recover_pending": "請使用對應帳戶的「復原」按鈕繼續未完成的切換或重新啟動。",
+ "switch.countdown": "{0} · 最多還需 {1} 秒",
+ "switch.settling": "{0} · 正在確認結果",
+ "switch.cancelling": "正在取消切換…",
+ "switch.timeout": "{0} 已達到 {1} 秒的時間上限。",
+ "switch.retrying": "重試 {0}/{1}",
"switch.restart_failed": "無法重新啟動Codex。請重試復原:{0}",
"io.read": "磁碟讀取",
"io.write": "磁碟寫入",
diff --git a/scripts/export-disk-evidence.py b/scripts/export-disk-evidence.py
index e647d09c..012bd032 100644
--- a/scripts/export-disk-evidence.py
+++ b/scripts/export-disk-evidence.py
@@ -9,7 +9,7 @@
args=parser.parse_args()
if not re.fullmatch('[a-f0-9]{40}',args.revision):raise SystemExit('Exact disk evidence revision required')
data=json.loads(Path('artifacts/disk-io-native.json').read_text(encoding='utf-8'))
-if data['failed'] or data['passed']!=72 or len(data['checks'])!=72:raise SystemExit('Hardware/disk/folder contracts did not pass')
+if data['failed'] or data['passed']!=74 or len(data['checks'])!=74:raise SystemExit('Hardware/disk/folder contracts did not pass')
native=data['nativeDiskIo']
if native['state']!='Available' or not native['readAvailable'] or not native['writeAvailable']:raise SystemExit('Native disk counters were not actually available')
if native['profile'] not in {'Unknown','SeekPenalty','NoSeekPenalty','Mixed'}:raise SystemExit('Invalid disk capability profile')
diff --git a/scripts/verify-recovery-evidence.py b/scripts/verify-recovery-evidence.py
index c362d63c..e2b46f89 100644
--- a/scripts/verify-recovery-evidence.py
+++ b/scripts/verify-recovery-evidence.py
@@ -7,7 +7,7 @@
source, destination = map(Path, sys.argv[1:3])
result = json.loads((source / 'recovery-receipt.json').read_text(encoding='utf-8'))
-if result.get('passed') is not True or result.get('pendingLabel') != 'Recover' or result.get('completedLabel') != 'Switch':
+if result.get('passed') is not True or result.get('pendingActions') != ['Open', 'Recover'] or result.get('completedActions') != ['Open']:
raise SystemExit('Recovery UI assertions failed')
destination.mkdir(parents=True, exist_ok=True)
images = []
diff --git a/src/application/AccountService.cs b/src/application/AccountService.cs
index 150099ae..b995d56f 100644
--- a/src/application/AccountService.cs
+++ b/src/application/AccountService.cs
@@ -73,7 +73,8 @@ public AccountProfile[] Accounts
Key = p.Key, Alias = p.Alias, Email = p.Email, AccountId = p.AccountId, Plan = p.Plan,
SubscriptionActiveUntil = p.SubscriptionActiveUntil, SubscriptionLastChecked = p.SubscriptionLastChecked,
Subscription = p.Subscription, SubscriptionError = p.SubscriptionError,
- IsCurrent = p.Key == CurrentKey, RequiresApply = p.RequiresApply, Usage = p.Usage, Error = p.Error,
+ IsCurrent = p.Key == CurrentKey, RequiresApply = p.RequiresApply, HasAccountWindow = p.HasAccountWindow,
+ WindowLoginPending = p.WindowLoginPending, Usage = p.Usage, Error = 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()
@@ -156,20 +157,26 @@ private async Task RefreshCoreAsync(string key, CancellationToken cancellation)
if (profile == null) return;
await using var client = await OpenLinuxAsync(cancellation, workspace).ConfigureAwait(false);
string authJson;
+ AccountWindowProfile? windowHome;
lock (Vault.SyncRoot)
{
profile = Vault.Data.Accounts.Find(a => a.Key == key);
if (profile == null) return;
+ revision = profile.CredentialRevision;
+ windowHome = OperatingSystem.IsWindows() && profile.HasAccountWindow && !profile.WindowLoginPending && key != CurrentKey
+ ? new(Vault.DirectoryPath, key) : null;
var canonical = CanonicalAuthExists() ? ReadCanonicalAuth() : null;
if (canonical != null && !profile.RequiresApply && AuthDocument.Parse(canonical).Key == key) Vault.Upsert(canonical);
+ if (windowHome != null) Vault.Upsert(windowHome.ReadLogin());
authJson = profile.AuthJson; revision = profile.CredentialRevision;
}
- await using var home = new RuntimeHome(Vault.DirectoryPath, authJson);
+ await using var home = windowHome == null ? new RuntimeHome(Vault.DirectoryPath, authJson) : null;
+ var queryHome = windowHome?.Home ?? home!.Path;
UsageSnapshot? usage = null;
string? email = null, plan = null;
try
{
- await using var rpc = await OpenAccountRpcAsync(home.Path, client, workspace, cancellation).ConfigureAwait(false);
+ 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("로그인이 만료됐습니다. 계정 추가로 다시 로그인해 주세요.");
@@ -179,16 +186,16 @@ private async Task RefreshCoreAsync(string key, CancellationToken cancellation)
}
finally
{
- if (File.Exists(Path.Combine(home.Path, "auth.json")))
+ if (File.Exists(Path.Combine(queryHome, "auth.json")))
{
- var refreshed = home.ReadAuth();
+ var refreshed = windowHome?.ReadLogin() ?? home!.ReadAuth();
if (AuthDocument.Parse(refreshed).Key != key) throw new InvalidOperationException("조회 중 로그인 계정이 변경됐습니다.");
if (client != null) await client.RequireFileAsync(cancellation, workspace).ConfigureAwait(false);
lock (Vault.SyncRoot)
{
if (IsCurrentRevision(profile, revision))
{
- if (refreshed != authJson)
+ if (windowHome == null && refreshed != authJson)
{
var canonical = CanonicalAuthExists() ? ReadCanonicalAuth() : null;
if (!profile.RequiresApply && canonical == authJson) SecureFiles.AtomicWriteText(AuthPath, refreshed);
@@ -305,6 +312,7 @@ 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 (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;
profile.Error = null; key = profile.Key; Vault.Save();
@@ -313,6 +321,76 @@ private AccountRegistration CompleteRegistrationCore(string authJson, string? ex
var refresh = RefreshAccountAsync(key, CancellationToken.None, true);
return new AccountRegistration(Accounts.Single(a => a.Key == key), refresh);
}
+ internal async Task OpenAccountWindowAsync(string key, CancellationToken cancellation)
+ {
+ if (!OperatingSystem.IsWindows()) throw new PlatformNotSupportedException();
+ await _switchGate.WaitAsync(cancellation).ConfigureAwait(false);
+ TaskCompletionSource? finished = null;
+ try
+ {
+ AccountWindowProfile? window;
+ string? expectedPrimary;
+ lock (Vault.SyncRoot)
+ {
+ expectedPrimary = CurrentKey;
+ var saved = Vault.Data.Accounts.Find(a => a.Key == key);
+ window = key == expectedPrimary && saved?.HasAccountWindow != true ? null : new(Vault.DirectoryPath, key);
+ _switchTargets = new HashSet { key };
+ finished = _switchFinished = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ }
+ await _queries.CancelAndDrainAsync(_switchTargets, cancellation).ConfigureAwait(false);
+ var installation = await RuntimeLocator.FindAsync(cancellation).ConfigureAwait(false);
+ if (string.IsNullOrEmpty(installation.DesktopPath)) throw new FileNotFoundException("Codex 데스크톱 앱을 찾을 수 없습니다.");
+ var backend = Path.Combine(AppContext.BaseDirectory, "backend", "CodexSwitch.Backend.exe");
+ AccountProfile Selected()
+ {
+ var account = Vault.Data.Accounts.Find(a => a.Key == key) ?? throw new InvalidOperationException("선택한 계정이 삭제됐습니다.");
+ CheckCredentialBackend(account);
+ var primary = CanonicalAuthExists() ? AuthDocument.Parse(ReadCanonicalAuth()).Key : null;
+ if (primary != expectedPrimary) throw new InvalidOperationException("switch.window_identity");
+ return account;
+ }
+ void Prepare()
+ {
+ lock (Vault.SyncRoot)
+ {
+ var account = Selected();
+ if (!SwitchRecovery.AllowsAccount(Vault.Data.ActivePendingSwitch, key, CurrentKey, true))
+ throw new InvalidOperationException("switch.recover_pending");
+ if (!AccountAutomation.CanUse(this, account, DateTimeOffset.UtcNow))
+ throw new InvalidOperationException("credits.resume_blocked");
+ if (window != null && (!Vault.Data.AllowCreditUse || Vault.Data.AutomaticSwitchEnabled))
+ throw new InvalidOperationException("switch.window_policy");
+ 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();
+ }
+ }
+ Task Verify(int pid, CancellationToken token)
+ {
+ lock (Vault.SyncRoot)
+ {
+ var account = Selected();
+ if (window == null) return Task.CompletedTask;
+ if (account.WindowLoginPending) throw new InvalidOperationException("switch.window_busy");
+ _ = window.ReadLogin();
+ }
+ return AccountWindowIdentity.VerifyAsync(window.Home, key, pid, token);
+ }
+ await WindowsAccountWindows.OpenAsync(installation.DesktopPath, window?.Desktop, window?.Home ?? CodexHome, backend,
+ Prepare, Verify, cancellation).ConfigureAwait(false);
+ }
+ finally
+ {
+ lock (Vault.SyncRoot) { _switchTargets.Clear(); _switchFinished = null; }
+ finished?.TrySetResult(true); _switchGate.Release(); Changed?.Invoke();
+ }
+ }
+
public async Task ApplySwitchAsync(string key, Func? desktopRunning, bool launch, CancellationToken cancellation,
string? expectedSource = null, bool verifySource = false, bool requireCliQuiescence = false)
{
@@ -333,7 +411,7 @@ bool Running() => OperatingSystem.IsLinux() ? LinuxDesktopRuntime.Running(cancel
_switchTargets = new HashSet(new[] { key, CurrentKey ?? "" });
finished = _switchFinished = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
}
- await _queries.CancelAndDrainAsync(_switchTargets).ConfigureAwait(false);
+ await _queries.CancelAndDrainAsync(_switchTargets, cancellation).ConfigureAwait(false);
var policy = client == null ? null : await client.RequireFileAsync(cancellation, workspace).ConfigureAwait(false);
lock (Vault.SyncRoot)
{
@@ -380,6 +458,12 @@ public async Task RemoveAsync(string key)
if (key == CurrentKey) throw new InvalidOperationException("현재 로그인 계정은 제거할 수 없습니다.");
if (Vault.Data.ActivePendingSwitch?.TargetAccountKey == key || Vault.Data.ActivePendingSwitch?.SourceAccountKey == key)
throw new InvalidOperationException("남은 채팅 재개 작업을 먼저 처리해 주세요.");
+ if (OperatingSystem.IsWindows() && Vault.Data.Accounts.Find(a => a.Key == key) is { HasAccountWindow: true })
+ {
+ var profile = new AccountWindowProfile(Vault.DirectoryPath, 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();
}
Changed?.Invoke();
diff --git a/src/application/AccountWindowActivity.cs b/src/application/AccountWindowActivity.cs
new file mode 100644
index 00000000..4e6b9dc4
--- /dev/null
+++ b/src/application/AccountWindowActivity.cs
@@ -0,0 +1,29 @@
+using System.Threading.Tasks;
+
+namespace CodexAccountDesk;
+
+internal sealed class AccountWindowActivity
+{
+ private readonly object _gate = new();
+ private int _running;
+ private long _accountGeneration;
+ private TaskCompletionSource _changed = new(TaskCreationOptions.RunContinuationsAsynchronously);
+
+ internal (int Running, long AccountGeneration, Task Changed) Snapshot()
+ {
+ lock (_gate) return (_running, _accountGeneration, _changed.Task);
+ }
+
+ internal void Update(int count, bool accountChanged = false)
+ {
+ lock (_gate)
+ {
+ if (!accountChanged && count == _running) return;
+ _running = count;
+ if (accountChanged) _accountGeneration++;
+ var prior = _changed;
+ _changed = new(TaskCreationOptions.RunContinuationsAsynchronously);
+ prior.TrySetResult();
+ }
+ }
+}
diff --git a/src/application/AccountWindowIdentity.cs b/src/application/AccountWindowIdentity.cs
new file mode 100644
index 00000000..59bf5405
--- /dev/null
+++ b/src/application/AccountWindowIdentity.cs
@@ -0,0 +1,124 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.IO.Pipes;
+using System.Linq;
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace CodexAccountDesk;
+
+internal static class AccountWindowIdentity
+{
+ internal static string Pipe(string home) => "CodexSwitch.Window." + SecureFiles.Hash(Path.GetFullPath(home).ToUpperInvariant());
+
+ internal static async Task ServeAsync(string home, Func> rpc, AccountWindowActivity activity, CancellationToken stop)
+ {
+ var clients = new List();
+ try
+ {
+ while (!stop.IsCancellationRequested)
+ {
+ clients.RemoveAll(client => client.IsCompletedSuccessfully);
+ if (clients.Count >= 6) await (await Task.WhenAny(clients).ConfigureAwait(false)).ConfigureAwait(false);
+ var pipe = new NamedPipeServerStream(Pipe(home), PipeDirection.InOut, NamedPipeServerStream.MaxAllowedServerInstances, PipeTransmissionMode.Byte,
+ PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
+ try { await pipe.WaitForConnectionAsync(stop).ConfigureAwait(false); }
+ catch { pipe.Dispose(); throw; }
+ clients.Add(AnswerAsync(pipe, home, rpc, activity, stop));
+ }
+ }
+ catch (OperationCanceledException) when (stop.IsCancellationRequested) { }
+ finally { await Task.WhenAll(clients).ConfigureAwait(false); }
+ }
+
+ private static async Task AnswerAsync(NamedPipeServerStream pipe, string home,
+ Func> rpc, AccountWindowActivity activity, CancellationToken stop)
+ {
+ using (pipe)
+ try
+ {
+ using var request = CancellationTokenSource.CreateLinkedTokenSource(stop);
+ request.CancelAfter(TimeSpan.FromSeconds(6));
+ var command = new byte[1];
+ try { if (await pipe.ReadAsync(command, request.Token).ConfigureAwait(false) != 1 || command[0] is not (1 or 2)) return; }
+ catch (OperationCanceledException) when (!stop.IsCancellationRequested) { return; }
+ string key;
+ var generation = activity.Snapshot().AccountGeneration;
+ try
+ {
+ var sessions = await rpc("accountSession/list", new() { ["refreshWorkspaceMetadata"] = false }).WaitAsync(TimeSpan.FromSeconds(4), stop).ConfigureAwait(false);
+ var json = File.ReadAllText(Path.Combine(home, "auth.json"));
+ key = sessions?["activeSessionId"]?.GetValue() == null ? "?" : VerifiedKey(json, sessions);
+ }
+ catch (Exception error) when (!stop.IsCancellationRequested && error is IOException or TimeoutException or
+ InvalidOperationException or FormatException or JsonException or UnauthorizedAccessException)
+ {
+ await Console.Error.WriteLineAsync("Account window identity unavailable: " + error.GetType().Name).ConfigureAwait(false);
+ key = "?";
+ }
+ if (generation != activity.Snapshot().AccountGeneration) key = "?";
+ await pipe.WriteAsync(Encoding.ASCII.GetBytes(key + "\n"), stop).ConfigureAwait(false);
+ if (command[0] != 2 || key.Length != 64) return;
+ var disconnected = pipe.ReadAsync(command, stop).AsTask();
+ while (!disconnected.IsCompleted)
+ {
+ var view = activity.Snapshot();
+ if (view.AccountGeneration != generation) return;
+ await pipe.WriteAsync(BitConverter.GetBytes(view.Running), stop).ConfigureAwait(false);
+ await Task.WhenAny(view.Changed, disconnected).ConfigureAwait(false);
+ }
+ await disconnected.ConfigureAwait(false);
+ }
+ catch (OperationCanceledException) when (stop.IsCancellationRequested) { }
+ catch (IOException) { /* Client disconnected while waiting for a state change. */ }
+ }
+
+ internal static string VerifiedKey(string json, JsonNode? sessions)
+ {
+ var account = AuthDocument.Parse(json);
+ using var auth = JsonDocument.Parse(json);
+ using var claims = AuthDocument.DecodeClaims(auth.RootElement.GetProperty("tokens").GetProperty("id_token").GetString()!);
+ var user = claims.RootElement.TryGetProperty("https://api.openai.com/auth", out var ids)
+ ? JsonValue.String(ids, "chatgpt_user_id") ?? JsonValue.String(ids, "user_id") : null;
+ var sessionId = sessions?["activeSessionId"]?.GetValue();
+ if (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(sessionId)) return "";
+ var active = sessions?["sessions"]?.AsArray().SingleOrDefault(row => row?["sessionId"]?.GetValue() == sessionId);
+ return active?["isActive"]?.GetValue() == true && active["selectedWorkspaceAccountId"]?.GetValue() == account.AccountId &&
+ active["userId"]?.GetValue() == user ? account.Key : "";
+ }
+
+ internal static async Task VerifyAsync(string home, string key, int rootPid, CancellationToken cancellation, Action? activity = null)
+ {
+ if (!OperatingSystem.IsWindows()) throw new PlatformNotSupportedException();
+ var config = JsonSerializer.Deserialize(SecureFiles.ReadPrivateBytes(Path.Combine(home, "window-backend.json")));
+ if (config?.AccountWindowBackend == null) throw new InvalidOperationException("switch.window_identity");
+ using var pipe = new NamedPipeClientStream(".", Pipe(home), PipeDirection.InOut, PipeOptions.Asynchronous | PipeOptions.CurrentUserOnly);
+ await pipe.ConnectAsync(750, cancellation).ConfigureAwait(false);
+ WindowsAccountWindows.VerifyBackend(pipe.SafePipeHandle, config.AccountWindowBackend, rootPid);
+ await pipe.WriteAsync(new byte[] { activity == null ? (byte)1 : (byte)2 }, cancellation).ConfigureAwait(false);
+ var expected = Encoding.ASCII.GetBytes(key + "\n");
+ var actual = new byte[expected.Length];
+ var count = 0;
+ while (count < actual.Length)
+ {
+ var size = await pipe.ReadAsync(actual.AsMemory(count), cancellation).ConfigureAwait(false);
+ if (size == 0) break;
+ count += size;
+ }
+ if (count == 2 && actual[0] == '?' && actual[1] == '\n') throw new TimeoutException("switch.window_wait");
+ if (count != expected.Length || !actual.AsSpan().SequenceEqual(expected)) throw new InvalidOperationException("switch.window_identity");
+ if (activity == null) return;
+ var frame = new byte[sizeof(int)];
+ while (true)
+ {
+ await pipe.ReadExactlyAsync(frame, cancellation).ConfigureAwait(false);
+ var running = BitConverter.ToInt32(frame);
+ if (running < 0) throw new InvalidDataException("Invalid account window activity.");
+ activity(running);
+ }
+ }
+}
diff --git a/src/application/AccountWindowProfile.cs b/src/application/AccountWindowProfile.cs
new file mode 100644
index 00000000..552c6278
--- /dev/null
+++ b/src/application/AccountWindowProfile.cs
@@ -0,0 +1,49 @@
+using System;
+using System.IO;
+
+namespace CodexAccountDesk;
+
+internal sealed class AccountWindowProfile(string directory, string key)
+{
+ private readonly string _root = Path.Combine(directory, "account-windows");
+ private string Folder => Path.Combine(_root, SecureFiles.Hash(key));
+ internal string Home => Path.Combine(Folder, "home");
+ internal string Desktop => Path.Combine(Folder, "desktop");
+ private string Auth => Path.Combine(Home, "auth.json");
+
+ private static void CheckPath(string path)
+ {
+ if ((File.GetAttributes(path) & FileAttributes.ReparsePoint) != 0)
+ throw new IOException("Account window storage contains a linked path.");
+ }
+
+ internal string ReadLogin()
+ {
+ CheckPath(_root); CheckPath(Folder); CheckPath(Desktop); CheckPath(Home); CheckPath(Auth);
+ var json = File.ReadAllText(Auth);
+ if (AuthDocument.Parse(json).Key != key) throw new InvalidOperationException("switch.window_identity");
+ return json;
+ }
+
+ internal void Prepare(AccountProfile account)
+ {
+ if (AuthDocument.Parse(account.AuthJson).Key != key) throw new InvalidOperationException("switch.window_identity");
+ foreach (var path in new[] { _root, Folder, Home, Desktop }) SecureFiles.CreatePrivateDirectory(path);
+ var config = Path.Combine(Home, "config.toml");
+ 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");
+ if (!account.HasAccountWindow || account.WindowLoginPending)
+ {
+ if (!hasLogin || account.WindowLoginPending) SecureFiles.AtomicWriteText(Auth, account.AuthJson);
+ account.HasAccountWindow = true;
+ account.WindowLoginPending = false;
+ }
+ }
+
+ internal void RemoveLogin()
+ {
+ if (File.Exists(Auth)) { _ = ReadLogin(); File.Delete(Auth); }
+ }
+}
diff --git a/src/application/DesktopBackendHost.cs b/src/application/DesktopBackendHost.cs
index 8f6c3323..f816403b 100644
--- a/src/application/DesktopBackendHost.cs
+++ b/src/application/DesktopBackendHost.cs
@@ -16,14 +16,14 @@ namespace CodexAccountDesk;
internal sealed class DesktopBackendHost : IAsyncDisposable
{
- internal sealed record Configuration(string NativeExecutable, string Home, string Directory);
+ internal sealed record Configuration(string NativeExecutable, string Home, string Directory, string? AccountWindowBackend = null);
private sealed class Session
{
internal string? Model, Revision;
internal bool Custom, Ephemeral;
internal JsonObject Settings = new();
}
- private sealed class RpcFailure(JsonObject error) : Exception(error["message"]?.GetValue())
+ private sealed class RpcFailure(JsonObject error) : InvalidOperationException(error["message"]?.GetValue())
{ internal JsonObject Error { get; } = error; }
private readonly Configuration _config;
private readonly Process _native;
@@ -39,6 +39,9 @@ private sealed class RpcFailure(JsonObject error) : Exception(error["message"]?.
private readonly CancellationTokenSource _stop = new();
private readonly string _prefix = "switch:" + Guid.NewGuid().ToString("N") + ":";
private int _sequence;
+ private Task? _windowIdentity;
+ private readonly AccountWindowActivity _windowActivity = new();
+ private Task? _windowSessionRead;
private ModelGateway? _gateway;
private readonly string? _diagnosticUrl;
private readonly byte[]? _diagnosticKey;
@@ -60,6 +63,10 @@ internal static async Task RunAsync(string[] arguments)
return 0;
}
var configuration = JsonSerializer.Deserialize(SecureFiles.ReadPrivateBytes(path)) ?? throw new InvalidDataException("The desktop backend configuration is empty.");
+ if (Environment.GetEnvironmentVariable("CODEX_SWITCH_WINDOW_HOME") is string windowHome &&
+ (configuration.AccountWindowBackend == null ||
+ !string.Equals(Path.GetFullPath(windowHome), Path.GetFullPath(configuration.Home), StringComparison.OrdinalIgnoreCase)))
+ throw new InvalidOperationException("The account window and native home do not match.");
await using var host = new DesktopBackendHost(configuration, arguments);
return await host.RunAsync(arguments.Contains("app-server", StringComparer.Ordinal)).ConfigureAwait(false);
}
@@ -86,9 +93,11 @@ private DesktopBackendHost(Configuration config, string[] arguments)
};
start.Environment["CODEX_HOME"] = config.Home;
start.Environment.Remove("CODEX_CLI_PATH");
+ start.Environment.Remove("CODEX_SWITCH_WINDOW_HOME");
+ start.Environment.Remove("CODEX_SWITCH_BACKEND_CONFIG");
start.Environment.Remove(DiagnosticGatewayEndpoint.RelayUrlVariable);
start.Environment.Remove(DiagnosticGatewayEndpoint.KeyVariable);
- if (arguments.Contains("app-server", StringComparer.Ordinal))
+ if (config.AccountWindowBackend == null && arguments.Contains("app-server", StringComparer.Ordinal))
{ start.ArgumentList.Add("-c"); start.ArgumentList.Add("thread_unload_delay_secs=0"); }
foreach (var argument in arguments) start.ArgumentList.Add(argument);
_native = Process.Start(start) ?? throw new IOException("The native Codex backend did not start.");
@@ -126,6 +135,7 @@ private async Task RunAsync(bool appServer)
_stop.Cancel();
foreach (var waiter in _pending.Values) waiter.TrySetCanceled();
await worker.ConfigureAwait(false);
+ if (_windowIdentity != null) await _windowIdentity.ConfigureAwait(false);
_native.StandardInput.Close();
}
await outputPump.ConfigureAwait(false);
@@ -157,7 +167,8 @@ private async Task ProcessRequestAsync(JsonObject message)
try
{
JsonNode? result;
- if (method == "model/list") (result, catalogReceipt) = await ModelsAsync(parameters).ConfigureAwait(false);
+ if (_config.AccountWindowBackend != null) result = await RequestAsync(method, parameters).ConfigureAwait(false);
+ else if (method == "model/list") (result, catalogReceipt) = await ModelsAsync(parameters).ConfigureAwait(false);
else result = await HandleAsync(method, parameters).ConfigureAwait(false);
reply = new() { ["id"] = message["id"]!.DeepClone(), ["result"] = result };
}
@@ -165,11 +176,23 @@ private async Task ProcessRequestAsync(JsonObject message)
catch (Exception error)
{ reply = new() { ["id"] = message["id"]!.DeepClone(), ["error"] = new JsonObject { ["code"] = -32000, ["message"] = error.Message } }; }
await WriteClientAsync(reply).ConfigureAwait(false);
+ if (_config.AccountWindowBackend != null && method == "initialize" && reply["error"] == null)
+ _windowIdentity ??= AccountWindowIdentity.ServeAsync(_config.Home, ReadWindowSessionsAsync, _windowActivity, _stop.Token);
if (catalogReceipt != null)
SecureFiles.AtomicWrite(Path.Combine(_config.Directory, DesktopBackendCatalog.ObservedFileName), JsonSerializer.SerializeToUtf8Bytes(new { revision = catalogReceipt, backendPid = Environment.ProcessId, nativePid = _native.Id, contextSettingsVersion = 1 }));
}
finally { gate.Release(); }
}
+ private Task ReadWindowSessionsAsync(string method, JsonObject parameters)
+ {
+ lock (_windowActivity)
+ {
+ if (_windowSessionRead == null || _windowSessionRead.IsCompleted)
+ _windowSessionRead = RequestAsync(method, parameters);
+ return _windowSessionRead;
+ }
+ }
+
private async Task ReadNativeAsync()
{
try
@@ -180,11 +203,14 @@ private async Task ReadNativeAsync()
var id = message["id"]?.ToJsonString();
if (id != null && _pending.TryRemove(id, out var waiter)) { waiter.TrySetResult(message); continue; }
var method = message["method"]?.GetValue();
+ if (_config.AccountWindowBackend != null && method == "account/updated") _windowActivity.Update(_active.Count, true);
var thread = message["params"]?["threadId"]?.GetValue();
if (thread != null)
{
if (method == "turn/started") _active[thread] = 0;
if (method is "turn/completed" or "thread/closed") _active.TryRemove(thread, out _);
+ if (_config.AccountWindowBackend != null && method is "turn/started" or "turn/completed" or "thread/closed")
+ _windowActivity.Update(_active.Count);
if (method == "thread/closed" && _handoffs.ContainsKey(thread)) continue;
}
await WriteClientAsync(message).ConfigureAwait(false);
diff --git a/src/application/DesktopSwitchBackend.cs b/src/application/DesktopSwitchBackend.cs
index 46e3d670..252c5ce8 100644
--- a/src/application/DesktopSwitchBackend.cs
+++ b/src/application/DesktopSwitchBackend.cs
@@ -35,7 +35,7 @@ public async Task CaptureAsync(CancellationToken cancellation)
if (!File.Exists(_service.Installation.DesktopPath)) throw new FileNotFoundException("Codex 데스크톱 앱을 찾을 수 없습니다.");
if (!RuntimeLocator.IsDesktopRunning(_service.Installation.DesktopPath)) return Array.Empty();
}
- await _sessions.WaitForDiscoveryAsync(cancellation);
+ await _sessions.WaitForDiscoveryAsync(cancellation, TimeSpan.FromSeconds(25));
var chats = _sessions.Threads.Where(thread => thread.Status == "active" || _restartOnly && thread.Status == "idle" && thread.Goal == "active").Select(thread => new SwitchChat {
Id = thread.Id, OriginalTitle = thread.Title ?? "", OriginalTurnId = thread.LastTurnId, OriginalGoal = thread.Goal }).ToArray();
foreach (var chat in chats.Where(chat => OperatingSystem.IsLinux() || string.IsNullOrWhiteSpace(chat.OriginalTitle)))
@@ -53,8 +53,10 @@ private async Task MetadataAsync(CancellationToken cancellation)
throw new PlatformNotSupportedException("Desktop metadata actions require a verified desktop lifecycle and peer provider.");
if (_metadata == null)
{
- _metadata = new CodexRpc(_service.Installation.CliPath, _service.CodexHome, true);
- await _metadata.InitializeAsync(cancellation);
+ var candidate = new CodexRpc(_service.Installation.CliPath, _service.CodexHome, true);
+ try { await candidate.InitializeAsync(cancellation); }
+ catch { await candidate.DisposeAsync(); throw; }
+ _metadata = candidate;
}
return _metadata;
}
@@ -118,15 +120,39 @@ public async Task LaunchDesktopAsync(CancellationToken cancellation)
{
if (OperatingSystem.IsLinux())
{
- if (_service.LinuxDesktop == null) return;
- await _service.LinuxDesktop.StartAsync(cancellation);
+ if (_service.LinuxDesktop == null)
+ {
+ if (LinuxDesktopRuntime.Running(cancellation).Length != 0) throw new LinuxDesktopOwnershipException();
+ return;
+ }
+ try { await _service.LinuxDesktop.StartAsync(cancellation); }
+ catch (TimeoutException error) { throw new InvalidOperationException(error.Message, error); }
+ return;
}
- else if (!RuntimeLocator.IsDesktopRunning(_service.Installation.DesktopPath)) RuntimeLocator.LaunchDesktop(_service.Installation.DesktopPath);
- await _sessions.WaitForDiscoveryAsync(cancellation);
+ await Task.Run(async () =>
+ {
+ var executable = _service.Installation.DesktopPath;
+ if (RuntimeLocator.IsDesktopRunning(executable)) return;
+ cancellation.ThrowIfCancellationRequested();
+ RuntimeLocator.LaunchDesktop(executable);
+ try
+ {
+ while (!RuntimeLocator.IsDesktopRunning(executable))
+ await Task.Delay(200, cancellation);
+ }
+ catch (IOException error) { throw new InvalidOperationException(error.Message, error); }
+ }, cancellation);
}
+ public Task WaitForDesktopConnectionAsync(CancellationToken cancellation) => _sessions.WaitForDiscoveryAsync(cancellation);
public async Task ResumeAsync(SwitchChat chat, Action sending, CancellationToken cancellation)
{
var expectedAccount = _targetAccountKey ?? _service.CurrentKey;
+ cancellation.ThrowIfCancellationRequested();
+ if (_sessions.Current.Available && chat.ResumeState is ChatResumeState.Sending or ChatResumeState.Unconfirmed &&
+ _sessions.Threads.FirstOrDefault(candidate => candidate.Id == chat.Id && candidate.ResumeState == "resumed" &&
+ candidate.Status is "idle" or "active") is { } opened &&
+ SwitchContinuation.Decide(chat, opened, _restartOnly) is { } observed)
+ return observed;
if (OperatingSystem.IsLinux())
{
var metadata = await RequestMetadataAsync("thread/read", new { threadId = chat.Id, includeTurns = false }, cancellation);
diff --git a/src/core/AccountSwitchCoordinator.cs b/src/core/AccountSwitchCoordinator.cs
index 8d4e9204..74357610 100644
--- a/src/core/AccountSwitchCoordinator.cs
+++ b/src/core/AccountSwitchCoordinator.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
@@ -12,6 +13,34 @@ namespace CodexAccountDesk;
internal enum SwitchPhase { BackingUp, Closing, Applying, Launching, Resuming, Finished, CreditPaused }
internal enum ChatResumeState { Pending, Sending, Resumed, AlreadyRunning, Completed, Unconfirmed, Failed }
internal enum CodexModelProfile { Native, Switch }
+internal enum SwitchStage { Discovering, BackingUp, Closing, Applying, ModelProfile, Launching, Connecting, Resuming, Reopening, Retrying, AccountWindow }
+
+internal sealed record SwitchProgress(SwitchStage Stage, TimeSpan Budget, int Completed = 0, int Total = 0)
+{
+ private readonly long _started = Stopwatch.GetTimestamp();
+ public int SecondsLeft => Math.Max(0, (int)Math.Ceiling((Budget - Stopwatch.GetElapsedTime(_started)).TotalSeconds));
+ public bool CanCancel => Stage is SwitchStage.Discovering or SwitchStage.BackingUp or SwitchStage.Connecting or SwitchStage.Resuming or SwitchStage.Retrying or SwitchStage.AccountWindow;
+ public string Label => Stage switch
+ {
+ SwitchStage.Discovering => Loc.T("switch.discovering"),
+ SwitchStage.AccountWindow => Loc.T("switch.find_window"),
+ SwitchStage.BackingUp => Loc.F("채팅 이름 백업 {0}/{1}", Completed, Total),
+ SwitchStage.Closing => Loc.T("Codex 정상 종료 중…"),
+ SwitchStage.Applying => Loc.T("계정 적용 중…"),
+ SwitchStage.ModelProfile => Loc.T("switch.model_profile"),
+ SwitchStage.Launching or SwitchStage.Reopening => Loc.T("Codex 여는 중…"),
+ SwitchStage.Connecting => Loc.T("switch.connecting"),
+ SwitchStage.Resuming => Loc.F("채팅 재개 {0}/{1}", Completed, Total),
+ SwitchStage.Retrying => Loc.F("switch.retrying", Completed, Total),
+ _ => throw new ArgumentOutOfRangeException(nameof(Stage))
+ };
+}
+
+internal sealed class SwitchDeadlineException(SwitchProgress progress, Exception cause) :
+ TimeoutException(Loc.F("switch.timeout", progress.Label, (int)Math.Ceiling(progress.Budget.TotalSeconds)), cause)
+{
+ public SwitchStage Stage => progress.Stage;
+}
internal sealed class SwitchChat
{
@@ -48,6 +77,16 @@ internal sealed class AccountSwitchPlan
internal static class SwitchRecovery
{
+ public static bool CanReplaceEmptyRestart(AccountSwitchPlan? plan, string? current) =>
+ current != null && plan is { RestartOnly: true, Automatic: false, AccountApplied: false,
+ CreditProtectionPause: false, PreventDepletedSourceRelaunch: false, ModelProfile: null, ModelProfileApplied: false,
+ Phase: SwitchPhase.BackingUp or SwitchPhase.Closing, Chats.Count: 0 } &&
+ plan.SourceAccountKey == current && plan.TargetAccountKey == current;
+
+ public static bool AllowsAccount(AccountSwitchPlan? plan, string target, string? current, bool manualSwitch) =>
+ plan == null || plan.CreditProtectionPause || plan.TargetAccountKey == target ||
+ manualSwitch && CanReplaceEmptyRestart(plan, current);
+
public static AccountSwitchPlan? Active(AccountSwitchPlan? plan) =>
plan is { Phase: SwitchPhase.Finished, AccountApplied: true, DesktopRestartRequired: false, CreditProtectionPause: false } &&
(plan.ModelProfile == null || plan.ModelProfileApplied) &&
@@ -74,6 +113,7 @@ internal interface IAccountSwitchBackend : IAsyncDisposable
Task CloseDesktopAsync(CancellationToken cancellation);
Task ApplyAccountAsync(string key, string? source, CancellationToken cancellation);
Task LaunchDesktopAsync(CancellationToken cancellation);
+ Task WaitForDesktopConnectionAsync(CancellationToken cancellation) => Task.CompletedTask;
Task ResumeAsync(SwitchChat chat, Action sending, CancellationToken cancellation);
}
@@ -101,39 +141,64 @@ internal sealed class AccountSwitchCoordinator
private readonly Func _describeError;
private readonly Func? _applyModelProfile;
private readonly Func? _validateModelProfile;
+ private readonly Action? _progress;
+ private readonly Func _budget;
public AccountSwitchCoordinator(IAccountSwitchBackend backend, Action save, Action changed, Func describeError,
Func? applyModelProfile = null,
- Func? validateModelProfile = null)
- { _backend = backend; _save = save; _changed = changed; _describeError = describeError; _applyModelProfile = applyModelProfile; _validateModelProfile = validateModelProfile; }
- public async Task PrepareAsync(string target, DateTimeOffset at, CancellationToken cancellation, bool creditPause = false)
+ Func? validateModelProfile = null, Action? progress = null,
+ Func? budget = null)
+ {
+ _backend = backend; _save = save; _changed = changed; _describeError = describeError;
+ _applyModelProfile = applyModelProfile; _validateModelProfile = validateModelProfile;
+ _progress = progress; _budget = budget ?? DefaultBudget;
+ }
+ public async Task PrepareAsync(string target, DateTimeOffset at, CancellationToken cancellation, bool creditPause = false,
+ string? expectedSource = null)
{
- var source = await _backend.CurrentAccountAsync(cancellation);
- if (creditPause && (source == null || source != target)) throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
- var chats = await _backend.CaptureAsync(cancellation);
+ var (source, chats) = await InStageAsync(SwitchStage.Discovering, async token =>
+ {
+ var account = await _backend.CurrentAccountAsync(token);
+ if (creditPause && account != target || expectedSource != null && account != expectedSource)
+ throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
+ var captured = await _backend.CaptureAsync(token);
+ if (expectedSource != null && await _backend.CurrentAccountAsync(token) != expectedSource)
+ throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
+ return (account, captured);
+ }, cancellation);
+ cancellation.ThrowIfCancellationRequested();
foreach (var chat in chats) chat.BackupTitle = SwitchTitle.Stamp(chat.OriginalTitle, at);
var plan = new AccountSwitchPlan { SourceAccountKey = source, TargetAccountKey = target, RequestedAt = at, Chats = chats.ToList(), CreditProtectionPause = creditPause, PreventDepletedSourceRelaunch = creditPause };
Checkpoint(plan, SwitchPhase.BackingUp); return plan;
}
public async Task PrepareRestartAsync(string account, DateTimeOffset at, CancellationToken cancellation, CodexModelProfile? modelProfile = null)
{
- var source = await _backend.CurrentAccountAsync(cancellation);
- if (source == null || source != account) throw new InvalidOperationException(Loc.T("restart.login_changed"));
- var chats = await _backend.CaptureAsync(cancellation);
+ var chats = await InStageAsync(SwitchStage.Discovering, async token =>
+ {
+ if (await _backend.CurrentAccountAsync(token) != account) throw new InvalidOperationException(Loc.T("restart.login_changed"));
+ var captured = await _backend.CaptureAsync(token);
+ if (await _backend.CurrentAccountAsync(token) != account) throw new InvalidOperationException(Loc.T("restart.login_changed"));
+ return captured;
+ }, cancellation);
+ cancellation.ThrowIfCancellationRequested();
foreach (var chat in chats) { chat.BackupTitle = chat.OriginalTitle; chat.NameSaved = true; }
- if (await _backend.CurrentAccountAsync(cancellation) != source) throw new InvalidOperationException(Loc.T("restart.login_changed"));
- var plan = new AccountSwitchPlan { SourceAccountKey = source, TargetAccountKey = source, RequestedAt = at, Chats = chats.ToList(), RestartOnly = true, ModelProfile = modelProfile };
+ var plan = new AccountSwitchPlan { SourceAccountKey = account, TargetAccountKey = account, RequestedAt = at, Chats = chats.ToList(), RestartOnly = true, ModelProfile = modelProfile };
Checkpoint(plan, SwitchPhase.BackingUp); return plan;
}
public async Task RetargetCreditPauseAsync(AccountSwitchPlan plan, string target, CancellationToken cancellation)
{
if (!plan.CreditProtectionPause || plan.SourceAccountKey == null || plan.TargetAccountKey != plan.SourceAccountKey)
throw new InvalidOperationException("남은 채팅 재개 작업을 먼저 처리해 주세요.");
- if (await _backend.CurrentAccountAsync(cancellation) != plan.SourceAccountKey)
- throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
- var chats = ProposedChats(plan, await _backend.CaptureAsync(cancellation));
- await _backend.ValidateChatsForTargetAsync(chats, target, cancellation);
- if (await _backend.CurrentAccountAsync(cancellation) != plan.SourceAccountKey)
- throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
+ var chats = await InStageAsync(SwitchStage.Discovering, async token =>
+ {
+ if (await _backend.CurrentAccountAsync(token) != plan.SourceAccountKey)
+ throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
+ var captured = ProposedChats(plan, await _backend.CaptureAsync(token));
+ await _backend.ValidateChatsForTargetAsync(captured, target, token);
+ if (await _backend.CurrentAccountAsync(token) != plan.SourceAccountKey)
+ throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
+ return captured;
+ }, cancellation);
+ cancellation.ThrowIfCancellationRequested();
plan.Chats = chats.ToList();
plan.CreditProtectionPause = false; plan.TargetAccountKey = target; plan.AccountApplied = target == plan.SourceAccountKey;
plan.Error = null; plan.AutomaticRecoveryAttempts = 0;
@@ -141,12 +206,18 @@ public async Task RetargetCreditPauseAsync(AccountSwitchPlan plan, string target
}
public async Task RearmCreditPauseAsync(AccountSwitchPlan plan, CancellationToken cancellation)
{
- if (!plan.CreditProtectionPause || plan.Phase != SwitchPhase.CreditPaused || plan.SourceAccountKey == null || plan.SourceAccountKey != plan.TargetAccountKey ||
- await _backend.CurrentAccountAsync(cancellation) != plan.SourceAccountKey)
- throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
- var chats = ProposedChats(plan, await _backend.CaptureAsync(cancellation));
- if (await _backend.CurrentAccountAsync(cancellation) != plan.SourceAccountKey)
+ if (!plan.CreditProtectionPause || plan.Phase != SwitchPhase.CreditPaused || plan.SourceAccountKey == null || plan.SourceAccountKey != plan.TargetAccountKey)
throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
+ var chats = await InStageAsync(SwitchStage.Discovering, async token =>
+ {
+ if (await _backend.CurrentAccountAsync(token) != plan.SourceAccountKey)
+ throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
+ var captured = ProposedChats(plan, await _backend.CaptureAsync(token));
+ if (await _backend.CurrentAccountAsync(token) != plan.SourceAccountKey)
+ throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
+ return captured;
+ }, cancellation);
+ cancellation.ThrowIfCancellationRequested();
plan.Chats = chats.ToList();
plan.AccountApplied = false; plan.AutomaticRecoveryAttempts = 0; plan.Error = null;
Checkpoint(plan, SwitchPhase.BackingUp);
@@ -174,11 +245,11 @@ public async Task RunAsync(AccountSwitchPlan plan, CancellationToken cance
{
if (plan.ModelProfile != null && (!plan.RestartOnly || plan.CreditProtectionPause || _applyModelProfile == null || !Enum.IsDefined(plan.ModelProfile.Value)))
throw new InvalidOperationException("The saved Codex model profile restart cannot be applied by this client.");
- var current = await _backend.CurrentAccountAsync(cancellation);
+ var current = await InStageAsync(SwitchStage.Discovering, _backend.CurrentAccountAsync, cancellation);
if (plan.RestartOnly && (plan.SourceAccountKey == null || plan.SourceAccountKey != plan.TargetAccountKey || current != plan.SourceAccountKey))
throw new InvalidOperationException(Loc.T("restart.login_changed"));
if (plan.ModelProfile is { } requestedProfile && !plan.ModelProfileApplied && _validateModelProfile != null)
- await _validateModelProfile(requestedProfile, cancellation);
+ await InStageAsync(SwitchStage.ModelProfile, token => _validateModelProfile(requestedProfile, token), cancellation);
if (plan.CreditProtectionPause && (plan.SourceAccountKey == null || plan.SourceAccountKey != plan.TargetAccountKey || current != plan.SourceAccountKey))
throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
if (plan.CreditProtectionPause && plan.Phase == SwitchPhase.CreditPaused) return false;
@@ -188,50 +259,48 @@ public async Task RunAsync(AccountSwitchPlan plan, CancellationToken cance
{
if (current != plan.SourceAccountKey) throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
Checkpoint(plan, SwitchPhase.BackingUp);
+ var saved = plan.Chats.Count(chat => chat.NameSaved);
foreach (var chat in plan.Chats.Where(chat => !chat.NameSaved))
{
- cancellation.ThrowIfCancellationRequested();
- await RetryStepAsync(plan, async () =>
+ await RetryStepAsync(plan, SwitchStage.BackingUp, async token =>
{
- if (await _backend.CurrentAccountAsync(cancellation) != plan.SourceAccountKey)
+ if (await _backend.CurrentAccountAsync(token) != plan.SourceAccountKey)
throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
- await _backend.BackupNameAsync(chat, plan.RequestedAt, cancellation);
- }, cancellation);
- chat.NameSaved = true; Checkpoint(plan, SwitchPhase.BackingUp);
+ await _backend.BackupNameAsync(chat, plan.RequestedAt, token);
+ }, cancellation, saved, plan.Chats.Count);
+ chat.NameSaved = true; saved++; Checkpoint(plan, SwitchPhase.BackingUp);
}
- if (await _backend.CurrentAccountAsync(cancellation) != plan.SourceAccountKey)
- throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
cancellation.ThrowIfCancellationRequested();
plan.DesktopRestartRequired = true;
Checkpoint(plan, SwitchPhase.Closing);
- await RetryStepAsync(plan, async () =>
+ await RetryStepAsync(plan, SwitchStage.Closing, async token =>
{
- if (await _backend.CurrentAccountAsync(cancellation) != plan.SourceAccountKey)
+ if (await _backend.CurrentAccountAsync(token) != plan.SourceAccountKey)
throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
- await _backend.CloseDesktopAsync(cancellation);
+ await _backend.CloseDesktopAsync(token);
}, cancellation);
shutdownConfirmed = true;
closedThisRun = true;
cancellation.ThrowIfCancellationRequested();
- if (await _backend.CurrentAccountAsync(cancellation) != plan.SourceAccountKey)
- throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
if (plan.CreditProtectionPause)
{
+ if (await InStageAsync(SwitchStage.Discovering, _backend.CurrentAccountAsync, cancellation) != plan.SourceAccountKey)
+ throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
plan.AccountApplied = true;
Checkpoint(plan, SwitchPhase.CreditPaused);
return false;
}
if (!plan.RestartOnly)
{
- Checkpoint(plan, SwitchPhase.Applying);
- await RetryStepAsync(plan, async () =>
- {
- var account = await _backend.CurrentAccountAsync(cancellation);
- if (account == plan.TargetAccountKey) return;
- if (account != plan.SourceAccountKey)
- throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
- await _backend.ApplyAccountAsync(plan.TargetAccountKey, plan.SourceAccountKey, cancellation);
- }, cancellation);
+ Checkpoint(plan, SwitchPhase.Applying);
+ await RetryStepAsync(plan, SwitchStage.Applying, async token =>
+ {
+ var account = await _backend.CurrentAccountAsync(token);
+ if (account == plan.TargetAccountKey) return;
+ if (account != plan.SourceAccountKey)
+ throw new InvalidOperationException("로그인 계정이 변경돼 전환을 중단했습니다.");
+ await _backend.ApplyAccountAsync(plan.TargetAccountKey, plan.SourceAccountKey, token);
+ }, cancellation);
}
plan.AccountApplied = true; Checkpoint(plan, SwitchPhase.Launching);
}
@@ -240,61 +309,74 @@ await RetryStepAsync(plan, async () =>
if (!closedThisRun)
{
plan.DesktopRestartRequired = true; Checkpoint(plan, SwitchPhase.Closing);
- await _backend.CloseDesktopAsync(cancellation);
+ await InStageAsync(SwitchStage.Closing, async token =>
+ {
+ if (await _backend.CurrentAccountAsync(token) != plan.SourceAccountKey)
+ throw new InvalidOperationException(Loc.T("restart.login_changed"));
+ await _backend.CloseDesktopAsync(token);
+ }, cancellation);
shutdownConfirmed = true;
}
cancellation.ThrowIfCancellationRequested();
- if (await _backend.CurrentAccountAsync(cancellation) != plan.SourceAccountKey)
- throw new InvalidOperationException(Loc.T("restart.login_changed"));
Checkpoint(plan, SwitchPhase.Applying);
- await _applyModelProfile!(modelProfile, cancellation);
+ await InStageAsync(SwitchStage.ModelProfile, async token =>
+ {
+ if (await _backend.CurrentAccountAsync(token) != plan.SourceAccountKey)
+ throw new InvalidOperationException(Loc.T("restart.login_changed"));
+ await _applyModelProfile!(modelProfile, token);
+ }, cancellation);
plan.ModelProfileApplied = true; Checkpoint(plan, SwitchPhase.Launching);
}
- while (true)
+ await RetryStepAsync(plan, SwitchStage.Launching, async token =>
{
- try
+ if (await _backend.CurrentAccountAsync(token) != plan.TargetAccountKey)
+ throw new InvalidOperationException("선택한 계정과 현재 로그인이 달라 채팅 재개를 중단했습니다.");
+ plan.DesktopRestartRequired = true;
+ Checkpoint(plan, SwitchPhase.Launching); launchAttempted = true;
+ await _backend.LaunchDesktopAsync(token);
+ }, cancellation);
+ plan.DesktopRestartRequired = false;
+ Checkpoint(plan, SwitchPhase.Resuming);
+ var remaining = plan.Chats.Where(chat => !IsResumed(chat)).ToList();
+ while (remaining.Count != 0)
+ {
+ await RetryStepAsync(plan, SwitchStage.Connecting, _backend.WaitForDesktopConnectionAsync, cancellation);
+ var retry = new List();
+ foreach (var chat in remaining)
{
cancellation.ThrowIfCancellationRequested();
- if (await _backend.CurrentAccountAsync(cancellation) != plan.TargetAccountKey)
- throw new InvalidOperationException("선택한 계정과 현재 로그인이 달라 채팅 재개를 중단했습니다.");
- plan.DesktopRestartRequired = true;
- Checkpoint(plan, SwitchPhase.Launching); launchAttempted = true;
- await _backend.LaunchDesktopAsync(cancellation);
- plan.DesktopRestartRequired = false;
- Checkpoint(plan, SwitchPhase.Resuming);
- var retryable = false;
- foreach (var chat in plan.Chats.Where(chat => chat.ResumeState is not (ChatResumeState.Resumed or ChatResumeState.AlreadyRunning or ChatResumeState.Completed)))
+ var verifiedAccount = false;
+ try
{
- cancellation.ThrowIfCancellationRequested();
- if (await _backend.CurrentAccountAsync(cancellation) != plan.TargetAccountKey)
- throw new InvalidOperationException("로그인 계정이 변경돼 채팅 재개를 중단했습니다.");
- try
+ chat.Error = null;
+ chat.ResumeState = await InStageAsync(SwitchStage.Resuming, async token =>
{
- chat.Error = null;
- chat.ResumeState = await _backend.ResumeAsync(chat, () => { chat.ResumeState = ChatResumeState.Sending; Checkpoint(plan, SwitchPhase.Resuming); }, cancellation);
- retryable |= chat.ResumeState is ChatResumeState.Pending or ChatResumeState.Sending or ChatResumeState.Unconfirmed;
- }
- catch (OperationCanceledException) when (cancellation.IsCancellationRequested) { throw; }
- catch (Exception error)
- {
- chat.ResumeState = chat.ResumeState is ChatResumeState.Sending or ChatResumeState.Unconfirmed ? ChatResumeState.Unconfirmed : ChatResumeState.Failed;
- chat.Error = _describeError(error);
- retryable |= IsRetryable(error);
- }
- Checkpoint(plan, SwitchPhase.Resuming);
+ if (await _backend.CurrentAccountAsync(token) != plan.TargetAccountKey)
+ throw new InvalidOperationException("로그인 계정이 변경돼 채팅 재개를 중단했습니다.");
+ verifiedAccount = true;
+ return await _backend.ResumeAsync(chat, () =>
+ {
+ token.ThrowIfCancellationRequested();
+ chat.ResumeState = ChatResumeState.Sending; Checkpoint(plan, SwitchPhase.Resuming);
+ }, token);
+ }, cancellation, plan.Chats.Count(IsResumed), plan.Chats.Count);
+ if (chat.ResumeState is ChatResumeState.Pending or ChatResumeState.Sending or ChatResumeState.Unconfirmed) retry.Add(chat);
}
- var complete = plan.Chats.All(chat => chat.ResumeState is ChatResumeState.Resumed or ChatResumeState.AlreadyRunning or ChatResumeState.Completed);
- if (complete) { Checkpoint(plan, SwitchPhase.Finished); _save(null); return true; }
- if (!retryable || plan.AutomaticRecoveryAttempts >= MaximumRecoveryAttempts) return false;
- }
- catch (Exception error) when (!cancellation.IsCancellationRequested && IsRetryable(error) && plan.AutomaticRecoveryAttempts < MaximumRecoveryAttempts)
- {
- plan.Error = _describeError(error);
+ catch (OperationCanceledException) when (cancellation.IsCancellationRequested) { throw; }
+ catch (Exception error) when (verifiedAccount)
+ {
+ chat.ResumeState = chat.ResumeState is ChatResumeState.Sending or ChatResumeState.Unconfirmed ? ChatResumeState.Unconfirmed : ChatResumeState.Failed;
+ chat.Error = _describeError(error);
+ if (IsRetryable(error)) retry.Add(chat);
+ }
+ Checkpoint(plan, SwitchPhase.Resuming);
}
- // Keep the caller's switching state until both retries are spent. Persist the
- // reservation before waiting so a utility restart cannot reset the retry budget.
+ if (retry.Count == 0 || plan.AutomaticRecoveryAttempts >= MaximumRecoveryAttempts) break;
await ReserveRetryAsync(plan, cancellation);
+ remaining = retry;
}
+ if (!plan.Chats.All(IsResumed)) return false;
+ Checkpoint(plan, SwitchPhase.Finished); _save(null); return true;
}
catch (Exception error)
{
@@ -303,30 +385,33 @@ await RetryStepAsync(plan, async () =>
plan.AutomaticRecoveryAttempts = Math.Max(MaximumRecoveryAttempts, plan.AutomaticRecoveryAttempts);
// Reopen after cancellation or a failed apply, but do not add a fourth launch after
// exhausting the retries. Never overwrite credentials or repeat Continue here.
- if (!plan.CreditProtectionPause && plan.DesktopRestartRequired && shutdownConfirmed && (!launchAttempted || cancellation.IsCancellationRequested))
+ if (!plan.CreditProtectionPause && plan.DesktopRestartRequired && shutdownConfirmed && !launchAttempted)
{
- using var recovery = new CancellationTokenSource(TimeSpan.FromSeconds(35));
try
{
- var current = await _backend.CurrentAccountAsync(recovery.Token);
- if ((current == plan.SourceAccountKey || current == plan.TargetAccountKey) &&
- (!plan.PreventDepletedSourceRelaunch || current == plan.TargetAccountKey))
+ await InStageAsync(SwitchStage.Reopening, async token =>
{
- await _backend.LaunchDesktopAsync(recovery.Token);
- plan.DesktopRestartRequired = false;
- }
+ var current = await _backend.CurrentAccountAsync(token);
+ if ((current == plan.SourceAccountKey || current == plan.TargetAccountKey) &&
+ (!plan.PreventDepletedSourceRelaunch || current == plan.TargetAccountKey))
+ {
+ await _backend.LaunchDesktopAsync(token);
+ plan.DesktopRestartRequired = false;
+ }
+ }, CancellationToken.None);
}
catch (Exception restartError) { plan.Error += "\n" + Loc.F("switch.restart_failed", _describeError(restartError)); }
}
_save(plan); _changed(plan); throw;
}
}
- private async Task RetryStepAsync(AccountSwitchPlan plan, Func action, CancellationToken cancellation)
+ private async Task RetryStepAsync(AccountSwitchPlan plan, SwitchStage stage, Func action,
+ CancellationToken cancellation, int completed = 0, int total = 0)
{
while (true)
{
cancellation.ThrowIfCancellationRequested();
- try { await action(); return; }
+ try { await InStageAsync(stage, action, cancellation, completed, total); return; }
catch (Exception error) when (!cancellation.IsCancellationRequested && IsRetryable(error) && plan.AutomaticRecoveryAttempts < MaximumRecoveryAttempts)
{ plan.Error = _describeError(error); }
await ReserveRetryAsync(plan, cancellation);
@@ -336,10 +421,46 @@ private Task ReserveRetryAsync(AccountSwitchPlan plan, CancellationToken cancell
{
plan.AutomaticRecoveryAttempts++;
_save(plan); _changed(plan);
- return Task.Delay(TimeSpan.FromSeconds(1), cancellation);
+ var delay = TimeSpan.FromSeconds(1);
+ _progress?.Invoke(new(SwitchStage.Retrying, delay, plan.AutomaticRecoveryAttempts, MaximumRecoveryAttempts));
+ return Task.Delay(delay, cancellation);
}
- private static bool IsRetryable(Exception error) => error is IOException or TimeoutException ||
- error is System.ComponentModel.Win32Exception { NativeErrorCode: 2 or 3 or 32 or 33 or 170 };
+ private static bool IsResumed(SwitchChat chat) =>
+ chat.ResumeState is ChatResumeState.Resumed or ChatResumeState.AlreadyRunning or ChatResumeState.Completed;
+
+ private Task InStageAsync(SwitchStage stage, Func action, CancellationToken cancellation, int completed = 0, int total = 0) =>
+ InStageAsync(stage, async token => { await action(token); return true; }, cancellation, completed, total);
+
+ private async Task InStageAsync(SwitchStage stage, Func> action, CancellationToken cancellation, int completed = 0, int total = 0)
+ {
+ cancellation.ThrowIfCancellationRequested();
+ var progress = new SwitchProgress(stage, _budget(stage), completed, total);
+ using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
+ deadline.CancelAfter(progress.Budget);
+ _progress?.Invoke(progress);
+ try { return await action(deadline.Token); }
+ catch (OperationCanceledException error) when (deadline.IsCancellationRequested && !cancellation.IsCancellationRequested)
+ { throw new SwitchDeadlineException(progress, error); }
+ }
+
+ private static TimeSpan DefaultBudget(SwitchStage stage) => TimeSpan.FromSeconds(stage switch
+ {
+ SwitchStage.Discovering => 45,
+ SwitchStage.Closing => 45,
+ SwitchStage.Launching => 40,
+ SwitchStage.Connecting => 30,
+ SwitchStage.Resuming => 90,
+ SwitchStage.Reopening => 35,
+ SwitchStage.ModelProfile => 180,
+ _ => 60
+ });
+
+ private static bool IsRetryable(Exception error) => error switch
+ {
+ SwitchDeadlineException deadline => deadline.Stage is SwitchStage.BackingUp or SwitchStage.Connecting or SwitchStage.Resuming,
+ IOException or TimeoutException or System.ComponentModel.Win32Exception { NativeErrorCode: 2 or 3 or 32 or 33 or 170 } => true,
+ _ => false
+ };
private void Checkpoint(AccountSwitchPlan plan, SwitchPhase phase)
{ plan.Phase = phase; plan.Error = null; _save(plan); _changed(plan); }
}
diff --git a/src/core/Models.cs b/src/core/Models.cs
index fe745ebc..c1791d80 100644
--- a/src/core/Models.cs
+++ b/src/core/Models.cs
@@ -22,6 +22,8 @@ internal sealed class AccountProfile
[JsonIgnore] public DateTimeOffset? SubscriptionLastChecked { get; set; }
[JsonIgnore] public string? SubscriptionError { get; set; }
public bool RequiresApply { get; set; }
+ public bool HasAccountWindow { get; set; }
+ public bool WindowLoginPending { get; set; }
public UsageSnapshot? Usage { get; set; }
public List History { get; set; } = new();
public List CreditHistory { get; set; } = new();
@@ -151,7 +153,7 @@ public static AccountProfile Parse(string json)
var key = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(accountId + "\n" + subject))).ToLowerInvariant();
return new AccountProfile { Key = key, Email = email, AccountId = accountId, Plan = plan, AuthJson = json };
}
- private static JsonDocument DecodeClaims(string jwt)
+ internal static JsonDocument DecodeClaims(string jwt)
{
var parts = jwt.Split('.');
if (parts.Length != 3) throw new InvalidOperationException("로그인 토큰의 형식이 올바르지 않습니다.");
diff --git a/src/core/RefreshCoordinator.cs b/src/core/RefreshCoordinator.cs
index b3b951b7..3d675419 100644
--- a/src/core/RefreshCoordinator.cs
+++ b/src/core/RefreshCoordinator.cs
@@ -65,15 +65,15 @@ private async Task ExecuteAsync(Entry entry, Entry? previous)
else if (failure != null) entry.Completion.TrySetException(failure);
else entry.Completion.TrySetResult(true);
}
- public async Task CancelAndDrainAsync(IEnumerable? keys = null)
+ public async Task CancelAndDrainAsync(IEnumerable? keys = null, CancellationToken cancellation = default)
{
Entry[] entries;
lock (_state) entries = _running.Values.Where(e => keys == null || keys.Contains(e.Key)).ToArray();
foreach (var entry in entries) entry.Cancel();
foreach (var entry in entries)
{
- try { await entry.Completion.Task.ConfigureAwait(false); }
- catch (OperationCanceledException) { }
+ try { await entry.Completion.Task.WaitAsync(cancellation).ConfigureAwait(false); }
+ catch (OperationCanceledException) when (!cancellation.IsCancellationRequested) { }
}
}
}
diff --git a/src/desktop/DeskWindow.cs b/src/desktop/DeskWindow.cs
index 4981ab0f..32b28e91 100644
--- a/src/desktop/DeskWindow.cs
+++ b/src/desktop/DeskWindow.cs
@@ -278,12 +278,13 @@ private void RenderAccounts()
{
var profile = profiles[i]; var pending = _service?.Vault.Data.ActivePendingSwitch;
var resume = pending?.TargetAccountKey == profile.Key;
+ 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) ToolTip.SetTip(button, pending?.Error);
- button.IsEnabled = _ready && _switch == null && _login == null && !_stampingTitles && (!profile.IsCurrent || profile.RequiresApply || resume);
+ 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);
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);
@@ -333,11 +334,16 @@ 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;
- var creditPending = _service!.Vault.Data.ActivePendingSwitch;
- if (modelProfile != null && creditPending != null) { _statusMessage = Loc.T("남은 채팅 재개 작업을 먼저 처리해 주세요."); _status.Text = _statusMessage; return; }
- restart |= creditPending?.RestartOnly == true;
- if (restart && creditPending != null && !creditPending.RestartOnly) { _statusMessage = Loc.T("남은 채팅 재개 작업을 먼저 처리해 주세요."); _status.Text = _statusMessage; return; }
- creditPause |= creditPending is { CreditProtectionPause: true, Phase: not SwitchPhase.CreditPaused } && creditPending.TargetAccountKey == profile.Key && !AccountAutomation.CanUse(_service, profile, DateTimeOffset.UtcNow);
+ var pending = _service!.Vault.Data.ActivePendingSwitch;
+ var manual = !automatic && !creditPause && !restart && modelProfile == null;
+ if (!SwitchRecovery.AllowsAccount(pending, profile.Key, _service.CurrentKey, manual) ||
+ pending != null && (modelProfile != null || restart && !pending.RestartOnly))
+ { _statusMessage = Loc.T("switch.recover_pending"); _status.Text = _statusMessage; return; }
+ var replacedSource = !automatic && !creditPause && SwitchRecovery.CanReplaceEmptyRestart(pending, _service.CurrentKey)
+ ? pending!.SourceAccountKey : null;
+ restart |= pending is { RestartOnly: true } && pending.TargetAccountKey == profile.Key;
+ if (replacedSource != null) pending = null;
+ creditPause |= pending is { CreditProtectionPause: true, Phase: not SwitchPhase.CreditPaused } && pending.TargetAccountKey == profile.Key && !AccountAutomation.CanUse(_service, profile, DateTimeOffset.UtcNow);
if (!creditPause && !AccountAutomation.CanUse(_service, profile, DateTimeOffset.UtcNow)) { _statusMessage = Loc.T("credits.resume_blocked"); _status.Text = _statusMessage; return; }
_switch = CancellationTokenSource.CreateLinkedTokenSource(_stop.Token); _switchTarget = profile.Key; _phase = SwitchPhase.BackingUp; RenderAccounts();
try
@@ -348,11 +354,10 @@ await RunAsync(async _ =>
await using var backend = new DesktopSwitchBackend(_service, _sessions, profile.Key, restartOnly: restart);
var coordinator = new AccountSwitchCoordinator(backend,
plan => { lock (_service.Vault.SyncRoot) { _service.Vault.Data.PendingSwitch = plan; _service.Vault.Save(); } },
- plan => OnUi(() => { _phase = plan.Phase; RenderAccounts(); }), UserErrors.Describe, _service.ApplyModelProfileAsync, _service.ValidateModelProfileAsync);
- var pending = _service.Vault.Data.ActivePendingSwitch;
- if (pending != null && !pending.CreditProtectionPause && pending.TargetAccountKey != profile.Key) throw new InvalidOperationException(Loc.T("남은 채팅 재개 작업을 먼저 처리해 주세요."));
+ plan => OnUi(() => { _phase = plan.Phase; RenderAccounts(); }), UserErrors.Describe, _service.ApplyModelProfileAsync, _service.ValidateModelProfileAsync,
+ progress => OnUi(() => { _status.Text = progress.Label; ToolTip.SetTip(_status, progress.Label); }));
var plan = pending ?? (restart ? await coordinator.PrepareRestartAsync(profile.Key, DateTimeOffset.UtcNow, _switch.Token, modelProfile) :
- await coordinator.PrepareAsync(profile.Key, DateTimeOffset.UtcNow, _switch.Token, creditPause));
+ await coordinator.PrepareAsync(profile.Key, DateTimeOffset.UtcNow, _switch.Token, creditPause, replacedSource));
if (plan.CreditProtectionPause)
{
if (!creditPause) await coordinator.RetargetCreditPauseAsync(plan, profile.Key, _switch.Token);
@@ -364,7 +369,9 @@ await RunAsync(async _ =>
if (!automatic) plan.AutomaticRecoveryAttempts = 0;
lock (_service.Vault.SyncRoot) { _service.Vault.Data.PendingSwitch = plan; _service.Vault.Save(); }
if (await coordinator.RunAsync(plan, _switch.Token))
- { if (plan.RestartOnly) _statusMessage = Loc.T("restart.done"); }
+ _statusMessage = Loc.T(plan.RestartOnly
+ ? plan.Chats.Count == 0 ? "restart.opened" : "restart.done"
+ : plan.Chats.Count == 0 ? "switch.opened" : "계정을 전환하고 채팅을 재개했습니다.");
else
_statusMessage = plan.CreditProtectionPause && plan.Phase == SwitchPhase.CreditPaused ? Loc.T("credits.paused") : automatic ? Loc.T("auto.paused") : Loc.F("계정 전환 완료. 재개 확인이 필요한 채팅 {0}개",
plan.Chats.Count(chat => chat.ResumeState is ChatResumeState.Unconfirmed or ChatResumeState.Failed or ChatResumeState.Pending or ChatResumeState.Sending));
diff --git a/src/macos/Info.plist b/src/macos/Info.plist
index 27a0fc5c..fce3f934 100644
--- a/src/macos/Info.plist
+++ b/src/macos/Info.plist
@@ -7,8 +7,8 @@
CFBundleExecutableCodexSwitch
CFBundlePackageTypeAPPL
CFBundleInfoDictionaryVersion6.0
- CFBundleShortVersionString1.45.9
- CFBundleVersion1.45.9
+ CFBundleShortVersionString1.45.10
+ CFBundleVersion1.45.10
CFBundleIconFileapp-icon.icns
LSMinimumSystemVersion15.0
LSApplicationCategoryTypepublic.app-category.utilities
diff --git a/src/platforms/client/CodexSwitch.DesktopClient.csproj b/src/platforms/client/CodexSwitch.DesktopClient.csproj
index 979891a0..dd7587f8 100644
--- a/src/platforms/client/CodexSwitch.DesktopClient.csproj
+++ b/src/platforms/client/CodexSwitch.DesktopClient.csproj
@@ -4,6 +4,7 @@
CodexAccountDeskenabledisablenone
+
diff --git a/src/platforms/client/DesktopShutdown.cs b/src/platforms/client/DesktopShutdown.cs
index bcc93aba..a3a64475 100644
--- a/src/platforms/client/DesktopShutdown.cs
+++ b/src/platforms/client/DesktopShutdown.cs
@@ -48,6 +48,7 @@ public static Task CloseAsync(string executable, CancellationToken cancellation)
if (OperatingSystem.IsWindows()) return CloseWindowsAsync(executable, cancellation);
throw new PlatformNotSupportedException("Codex normal shutdown requires a supported platform provider.");
}
+ [System.Runtime.Versioning.SupportedOSPlatform("windows")]
private static Task CloseWindowsAsync(string executable, CancellationToken cancellation) => Task.Run(async () =>
{
cancellation.ThrowIfCancellationRequested();
@@ -66,6 +67,8 @@ private static Task CloseWindowsAsync(string executable, CancellationToken cance
}
}
if (processes.Count == 0) return;
+ if (RuntimeLocator.IsWindowsDesktopExecutable(executable) && WindowsAccountWindows.HasManagedWindow(executable))
+ throw new InvalidOperationException("switch.window_shutdown");
var parents = ReadParents(); var ids = new HashSet(processes.ConvertAll(process => process.Id));
processes.RemoveAll(process => parents.TryGetValue(process.Id, out var parent) && ids.Contains(parent));
if (processes.Count == 0) throw new IOException("Codex의 기본 프로세스를 확인하지 못했습니다.");
@@ -83,13 +86,22 @@ private static Task CloseWindowsAsync(string executable, CancellationToken cance
Started = new() { dwLowDateTime = (int)selfStart, dwHighDateTime = (int)(selfStart >> 32) } };
Check(RmAddFilter(session, null, ref selfIdentity, null, 2)); // RmNoShutdown
using var cancel = cancellation.Register(() => RmCancelCurrentTask(session));
- var result = RmShutdown(session, 0, IntPtr.Zero);
cancellation.ThrowIfCancellationRequested();
- if (result != 0) throw new IOException("Codex를 정상 종료하지 못했습니다. Codex 메뉴에서 종료한 뒤 다시 전환해 주세요.", new Win32Exception((int)result));
+ var result = RmShutdown(session, 0, IntPtr.Zero);
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation); timeout.CancelAfter(TimeSpan.FromSeconds(30));
- try { while (RuntimeLocator.IsDesktopRunning(executable)) await Task.Delay(100, timeout.Token); }
+ try
+ {
+ while (RuntimeLocator.IsDesktopRunning(executable))
+ {
+ timeout.Token.ThrowIfCancellationRequested();
+ if (result != 0)
+ throw new InvalidOperationException("Codex를 정상 종료하지 못했습니다. Codex 메뉴에서 종료한 뒤 다시 전환해 주세요.", new Win32Exception((int)result));
+ await Task.Delay(100, timeout.Token);
+ }
+ }
catch (OperationCanceledException) when (!cancellation.IsCancellationRequested)
- { throw new IOException("Codex가 아직 실행 중입니다. Codex 메뉴에서 완전히 종료해 주세요."); }
+ { throw new InvalidOperationException("Codex가 아직 실행 중입니다. Codex 메뉴에서 완전히 종료해 주세요."); }
+ catch (IOException error) { throw new InvalidOperationException(error.Message, error); }
}
finally { RmEndSession(session); }
}, cancellation);
diff --git a/src/platforms/client/WindowsAccountWindows.cs b/src/platforms/client/WindowsAccountWindows.cs
new file mode 100644
index 00000000..7b28b07d
--- /dev/null
+++ b/src/platforms/client/WindowsAccountWindows.cs
@@ -0,0 +1,248 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Management;
+using System.Runtime.InteropServices;
+using System.Runtime.Versioning;
+using System.Threading;
+using System.Threading.Tasks;
+
+namespace CodexAccountDesk;
+
+[SupportedOSPlatform("windows")]
+internal static class WindowsAccountWindows
+{
+ private const string Marker = "--codex-switch-account-window";
+ private const string ProfileArgument = "--user-data-dir=";
+ private sealed record Root(int Pid, long Created, string? Directory, bool Managed);
+
+ [DllImport("shell32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
+ private static extern IntPtr CommandLineToArgvW(string command, out int count);
+ [DllImport("kernel32.dll")] private static extern IntPtr LocalFree(IntPtr pointer);
+ [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr window);
+ [DllImport("user32.dll")] private static extern bool ShowWindowAsync(IntPtr window, int command);
+ [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr window);
+ [DllImport("user32.dll")] private static extern bool AllowSetForegroundWindow(int pid);
+ [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow();
+ [DllImport("user32.dll")] private static extern IntPtr GetAncestor(IntPtr window, uint flags);
+ [DllImport("user32.dll")] private static extern bool FlashWindow(IntPtr window, bool invert);
+ [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window, out int pid);
+
+ private static string[] Arguments(string line)
+ {
+ var argv = CommandLineToArgvW(line, out var count);
+ if (argv == IntPtr.Zero) throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
+ try
+ {
+ var args = new string[count];
+ for (var i = 0; i < count; i++) args[i] = Marshal.PtrToStringUni(Marshal.ReadIntPtr(argv, i * IntPtr.Size))!;
+ return args;
+ }
+ finally { LocalFree(argv); }
+ }
+
+ private static List Roots(string executable, bool requireComplete = false)
+ {
+ using var self = Process.GetCurrentProcess();
+ var name = Path.GetFileName(executable);
+ if (!name.Equals("ChatGPT.exe", StringComparison.OrdinalIgnoreCase) && !name.Equals("Codex.exe", StringComparison.OrdinalIgnoreCase))
+ throw new InvalidOperationException("Unexpected Codex desktop executable.");
+ using var query = new ManagementObjectSearcher("SELECT ProcessId,ParentProcessId,ExecutablePath,CommandLine,CreationDate FROM Win32_Process " +
+ $"WHERE (Name='ChatGPT.exe' OR Name='Codex.exe') AND SessionId={self.SessionId}");
+ query.Options.Timeout = TimeSpan.FromSeconds(4);
+ using var rows = query.Get();
+ var processes = new Dictionary();
+ foreach (ManagementObject row in rows)
+ {
+ using (row)
+ {
+ if (row["ExecutablePath"] is string path && !string.Equals(path, executable, StringComparison.OrdinalIgnoreCase) &&
+ !RuntimeLocator.IsWindowsDesktopExecutable(path)) continue;
+ processes[(int)(uint)row["ProcessId"]] = ((int)(uint)row["ParentProcessId"], row["CommandLine"] as string,
+ ManagementDateTimeConverter.ToDateTime((string)row["CreationDate"]).ToUniversalTime());
+ }
+ }
+ var roots = new List();
+ foreach (var (pid, item) in processes)
+ {
+ if (processes.TryGetValue(item.Parent, out var parent) && parent.Created <= item.Created) continue;
+ if (string.IsNullOrWhiteSpace(item.Command) && !requireComplete) continue;
+ WindowsProcessImage? candidate;
+ try { candidate = WindowsProcessImage.Read(pid); }
+ catch (System.ComponentModel.Win32Exception error) when (error.NativeErrorCode == 5 && !requireComplete &&
+ (item.Command == null || !Arguments(item.Command).Contains(Marker, StringComparer.Ordinal))) { continue; }
+ if (candidate is not { } image) continue;
+ if (!image.MatchesPath(executable) && !RuntimeLocator.IsWindowsDesktopExecutable(image.Path)) continue;
+ // WMI reports microseconds, GetProcessTimes reports 100 ns ticks.
+ if (DateTime.FromFileTimeUtc(image.CreationTime).Ticks / 10 != item.Created.Ticks / 10) continue;
+ if (string.IsNullOrEmpty(item.Command)) throw new InvalidOperationException("Codex window ownership is unavailable.");
+ var args = Arguments(item.Command);
+ if (args.Any(arg => arg.StartsWith("--type=", StringComparison.Ordinal))) continue;
+ var dirs = args.Where(arg => arg.StartsWith(ProfileArgument, StringComparison.OrdinalIgnoreCase)).ToArray();
+ if (dirs.Length > 1) throw new InvalidOperationException("Ambiguous Codex desktop profile.");
+ var dir = dirs.Length == 0 ? null : Path.GetFullPath(dirs[0].Substring(ProfileArgument.Length));
+ roots.Add(new(pid, image.CreationTime, dir, args.Contains(Marker, StringComparer.Ordinal)));
+ }
+ return roots;
+ }
+
+ private static IntPtr Window(Root root)
+ {
+ try
+ {
+ using var process = Process.GetProcessById(root.Pid);
+ var window = process.MainWindowHandle;
+ if (window == IntPtr.Zero || GetWindowThreadProcessId(window, out var owner) == 0 || owner != root.Pid) return IntPtr.Zero;
+ return WindowsProcessImage.Read(root.Pid)?.CreationTime == root.Created ? window : IntPtr.Zero;
+ }
+ catch (ArgumentException) { return IntPtr.Zero; } // PID exited between enumeration and window lookup.
+ }
+
+ internal static bool HasManagedWindow(string executable) => Roots(executable, true).Any(root => root.Managed);
+ internal static Dictionary Inventory(string executable)
+ {
+ var result = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ 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;
+ }
+ return result;
+ }
+ internal static bool UsesProfile(string executable, string profile) => Roots(executable, true).Any(root =>
+ string.Equals(root.Directory, profile, StringComparison.OrdinalIgnoreCase));
+
+ [DllImport("kernel32.dll", SetLastError = true)]
+ private static extern bool GetNamedPipeServerProcessId(Microsoft.Win32.SafeHandles.SafePipeHandle pipe, out uint processId);
+
+ internal static void VerifyBackend(Microsoft.Win32.SafeHandles.SafePipeHandle pipe, string executable, int rootPid)
+ {
+ if (!GetNamedPipeServerProcessId(pipe, out var peer) || WindowsProcessImage.Read((int)peer) is not { } image ||
+ !image.MatchesPath(Path.GetFullPath(executable))) throw new InvalidOperationException("switch.window_peer");
+ if (!DescendsFrom((int)peer, rootPid)) throw new InvalidOperationException("switch.window_parent");
+ }
+
+ private static bool DescendsFrom(int child, int parent)
+ {
+ var seen = new HashSet();
+ for (var pid = child; pid > 0 && seen.Count < 24 && seen.Add(pid);)
+ {
+ using var item = new ManagementObject("Win32_Process.Handle='" + pid + "'");
+ item.Get();
+ var created = ManagementDateTimeConverter.ToDateTime((string)item["CreationDate"]).ToUniversalTime();
+ pid = (int)(uint)item["ParentProcessId"];
+ if (WindowsProcessImage.Read(pid) is not { } ancestor || DateTime.FromFileTimeUtc(ancestor.CreationTime) > created.AddMilliseconds(1))
+ return false;
+ if (pid == parent) return true;
+ }
+ return false;
+ }
+
+ internal static Task OpenAsync(string executable, string? profile, string home, string backend, Action prepare,
+ Func verify, CancellationToken cancellation) =>
+ Task.Run(async () =>
+ {
+ using var deadline = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
+ deadline.CancelAfter(TimeSpan.FromSeconds(40));
+ var requested = false;
+ var observed = false;
+ var recoveredExit = false;
+ var waiting = Stopwatch.StartNew();
+ void Launch()
+ {
+ if (profile == null) { RuntimeLocator.LaunchDesktop(executable); return; }
+ var image = executable;
+ var package = Path.GetDirectoryName(Path.GetDirectoryName(executable));
+ if (package != null && Path.GetFileName(package).StartsWith("OpenAI.Codex_", StringComparison.OrdinalIgnoreCase) &&
+ Path.GetFileName(package).EndsWith("_2p2nqsd0c76g0", StringComparison.OrdinalIgnoreCase))
+ {
+ image = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
+ "Microsoft", "WindowsApps", "OpenAI.Codex_2p2nqsd0c76g0", "chatgpt-desktop.exe");
+ if (!File.Exists(image)) throw new FileNotFoundException("switch.window_alias");
+ }
+ var start = new ProcessStartInfo(image) { UseShellExecute = false, WorkingDirectory = Path.GetDirectoryName(executable)! };
+ start.ArgumentList.Add(ProfileArgument + profile);
+ start.ArgumentList.Add(Marker);
+ start.Environment["CODEX_ELECTRON_USER_DATA_PATH"] = profile;
+ start.Environment["CODEX_HOME"] = home;
+ start.Environment["CODEX_SWITCH_WINDOW_HOME"] = home;
+ start.Environment["CODEX_CLI_PATH"] = backend;
+ start.Environment["CODEX_SWITCH_BACKEND_CONFIG"] = Path.Combine(home, "window-backend.json");
+ start.Environment["CODEX_ELECTRON_START_IN_BACKGROUND"] = "0";
+ if (!File.Exists(backend)) throw new FileNotFoundException("Codex desktop runtime is missing.");
+ using var child = Process.Start(start) ?? throw new IOException("Codex did not start.");
+ }
+ try
+ {
+ while (true)
+ {
+ deadline.Token.ThrowIfCancellationRequested();
+ var roots = Roots(executable);
+ var matches = roots.Where(root => root.Managed == (profile != null) &&
+ string.Equals(root.Directory, profile, StringComparison.OrdinalIgnoreCase)).ToArray();
+ if (profile == null && matches.Length == 0 && roots.Any(root => !root.Managed))
+ throw new InvalidOperationException("switch.window_identity");
+ if (profile != null && roots.Any(root => !root.Managed && string.Equals(root.Directory, profile, StringComparison.OrdinalIgnoreCase)))
+ throw new InvalidOperationException("switch.window_identity");
+ if (matches.Length > 1) throw new InvalidOperationException("Multiple Codex windows claim this profile.");
+ if (matches.Length == 1)
+ {
+ observed = true;
+ var root = matches[0];
+ var window = Window(root);
+ if (window != IntPtr.Zero)
+ {
+ try { await verify(root.Pid, deadline.Token); }
+ catch (TimeoutException) { await Task.Delay(200, deadline.Token); continue; }
+ catch (IOException error) when ((error.HResult & 0xffff) is 32 or 33 or 109)
+ { await Task.Delay(200, deadline.Token); continue; }
+ if (Window(root) != window) continue;
+ AllowSetForegroundWindow(root.Pid);
+ if (IsIconic(window)) ShowWindowAsync(window, 9);
+ SetForegroundWindow(window);
+ for (var i = 0; i < 30; i++)
+ {
+ var front = GetForegroundWindow();
+ GetWindowThreadProcessId(GetAncestor(front, 3), out var foreground);
+ if (foreground == root.Pid) return;
+ if (i == 9 && !requested && Window(root) == window)
+ {
+ Launch(); requested = true;
+ }
+ await Task.Delay(50, deadline.Token);
+ }
+ if (Window(root) == window) FlashWindow(window, true);
+ throw new InvalidOperationException("switch.window_focus");
+ }
+ if (!requested && waiting.Elapsed > TimeSpan.FromSeconds(3))
+ {
+ try { await verify(root.Pid, deadline.Token); }
+ catch (TimeoutException) { await Task.Delay(200, deadline.Token); continue; }
+ AllowSetForegroundWindow(root.Pid);
+ Launch(); requested = true;
+ }
+ }
+ else if (!requested)
+ {
+ deadline.Token.ThrowIfCancellationRequested();
+ try { prepare(); }
+ catch (IOException error) when ((error.HResult & 0xffff) is 32 or 33)
+ { await Task.Delay(200, deadline.Token); continue; }
+ Launch();
+ requested = true; observed = false;
+ }
+ else if (observed)
+ {
+ if (recoveredExit) throw new IOException("switch.window_lost");
+ recoveredExit = true; requested = false; observed = false;
+ }
+ await Task.Delay(450, deadline.Token);
+ }
+ }
+ catch (OperationCanceledException) when (!cancellation.IsCancellationRequested)
+ { throw new TimeoutException("switch.window_wait"); }
+ }, cancellation);
+}
diff --git a/src/platforms/protocol/DesktopSessionMonitor.cs b/src/platforms/protocol/DesktopSessionMonitor.cs
index 04a4f730..73008298 100644
--- a/src/platforms/protocol/DesktopSessionMonitor.cs
+++ b/src/platforms/protocol/DesktopSessionMonitor.cs
@@ -41,9 +41,10 @@ public void RestartDiscovery()
_ledger.Reset(); Publish(_ledger.Read());
lock (_connectionSync) _connection?.Cancel();
}
- public async Task WaitForDiscoveryAsync(CancellationToken cancellation)
+ public async Task WaitForDiscoveryAsync(CancellationToken cancellation, TimeSpan? discoveryLimit = null)
{
- using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation); timeout.CancelAfter(TimeSpan.FromSeconds(25));
+ using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellation);
+ if (discoveryLimit is { } limit) timeout.CancelAfter(limit);
try { while (!Current.Available) await Task.Delay(150, timeout.Token); }
catch (OperationCanceledException) when (!cancellation.IsCancellationRequested) { throw new TimeoutException("진행 중인 채팅 상태를 확인하지 못했습니다."); }
}
diff --git a/src/platforms/resources/FolderChanges.cs b/src/platforms/resources/FolderChanges.cs
index 1e959083..51e191fa 100644
--- a/src/platforms/resources/FolderChanges.cs
+++ b/src/platforms/resources/FolderChanges.cs
@@ -5,17 +5,21 @@
namespace CodexAccountDesk;
+internal enum FolderChange { Entries, ItemChanged, RootMetadata, Reset }
+
internal sealed class FolderChanges : IDisposable
{
- private readonly Action _changed;
+ private readonly Action _changed;
private readonly Func _ignore;
private readonly List _watchers = new();
private volatile bool _retry = true;
+ private volatile bool _watchingFolder;
private int _identityChanged;
internal bool TakeIdentityChange() => Interlocked.Exchange(ref _identityChanged, 0) != 0;
internal string Path { get; }
internal bool Available => !_retry;
- internal FolderChanges(string path, Action changed, Func? ignore = null) { Path = path; _changed = changed; _ignore = ignore ?? (_ => false); }
+ internal FolderChanges(string path, Action changed, Func ignore)
+ { Path = path; _changed = changed; _ignore = ignore; }
internal bool Connect()
{
if (!_retry || !OperatingSystem.IsWindows()) return false;
@@ -28,46 +32,55 @@ internal bool Connect()
if (!ancestor.Exists || (ancestor.Attributes & FileAttributes.ReparsePoint) != 0) candidate = ancestor.Parent;
if (candidate == null) { _retry = true; return false; }
var recursive = DriveMonitor.RootComparer.Equals(candidate.FullName, Path);
- Add(candidate.FullName, recursive);
- if (recursive && candidate.Parent != null) Add(candidate.Parent.FullName, false);
+ _watchingFolder = recursive;
+ const NotifyFilters rootChanges = NotifyFilters.DirectoryName | NotifyFilters.Attributes | NotifyFilters.Security;
+ if (recursive)
+ {
+ Add(candidate.FullName, true, NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size | NotifyFilters.LastWrite);
+ Add(candidate.FullName, true, NotifyFilters.Attributes | NotifyFilters.Security, attributesOnly: true);
+ if (candidate.Parent != null) Add(candidate.Parent.FullName, false, rootChanges);
+ }
+ else Add(candidate.FullName, false, rootChanges);
return true;
}
catch (IOException) { _retry = true; Dispose(); return false; }
catch (UnauthorizedAccessException) { _retry = true; Dispose(); return false; }
catch (ArgumentException) { _retry = true; Dispose(); return false; }
}
- private void Add(string scope, bool recursive)
+ private void Add(string scope, bool recursive, NotifyFilters filters, bool attributesOnly = false)
{
var watcher = new FileSystemWatcher(scope)
{
IncludeSubdirectories = recursive,
- NotifyFilter = recursive
- ? NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.Attributes | NotifyFilters.Security
- : NotifyFilters.DirectoryName | NotifyFilters.Attributes | NotifyFilters.Security,
+ NotifyFilter = filters,
InternalBufferSize = 65536,
};
- watcher.Changed += (_, e) => Notify(e.FullPath, recursive);
+ watcher.Changed += (_, e) => Notify(e.FullPath, recursive, changed: true, attributesOnly: attributesOnly);
watcher.Created += (_, e) => Notify(e.FullPath, recursive);
watcher.Deleted += (_, e) => Notify(e.FullPath, recursive);
watcher.Renamed += (_, e) => { Notify(e.OldFullPath, recursive); Notify(e.FullPath, recursive); };
- watcher.Error += (_, _) => { _retry = true; _changed(Path, true); };
+ watcher.Error += (_, _) => { _retry = true; _changed(Path, FolderChange.Reset); };
_watchers.Add(watcher); watcher.EnableRaisingEvents = true;
}
- private void Notify(string path, bool recursive)
+ private void Notify(string path, bool recursive, bool changed = false, bool attributesOnly = false)
{
if (_ignore(path)) return;
if (!recursive)
{
var prefix = System.IO.Path.TrimEndingDirectorySeparator(path) + System.IO.Path.DirectorySeparatorChar;
if (DriveMonitor.RootComparer.Equals(path, Path) || Path.StartsWith(prefix, StringComparison.OrdinalIgnoreCase))
- { _retry = true; Interlocked.Exchange(ref _identityChanged, 1); _changed(Path, true); }
+ {
+ if (changed && _watchingFolder) _changed(Path, FolderChange.RootMetadata);
+ else { _retry = true; Interlocked.Exchange(ref _identityChanged, 1); _changed(Path, FolderChange.Reset); }
+ }
return;
}
- var directory = System.IO.Path.GetDirectoryName(path);
- _changed(directory ?? Path, false);
+ if (changed && !attributesOnly) _changed(path, FolderChange.ItemChanged);
+ else _changed(System.IO.Path.GetDirectoryName(path) ?? Path, FolderChange.Entries);
}
public void Dispose()
{
+ _watchingFolder = false;
foreach (var watcher in _watchers) watcher.Dispose();
_watchers.Clear();
}
diff --git a/src/platforms/resources/FolderMonitor.cs b/src/platforms/resources/FolderMonitor.cs
index 29e642d2..77c55d26 100644
--- a/src/platforms/resources/FolderMonitor.cs
+++ b/src/platforms/resources/FolderMonitor.cs
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
+using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text.Json;
@@ -20,15 +21,22 @@ internal sealed class FolderMonitor : IAsyncDisposable
private Dictionary _current = new(DriveMonitor.RootComparer);
private readonly Dictionary _status = new(DriveMonitor.RootComparer);
private readonly HashSet _dirty = new(DriveMonitor.RootComparer), _reset = new(DriveMonitor.RootComparer), _rebuild = new(DriveMonitor.RootComparer);
+ private readonly HashSet _refresh = new(DriveMonitor.RootComparer);
+ private readonly HashSet _checkRoots = new(DriveMonitor.RootComparer);
+ private readonly HashSet _changedItems = new(DriveMonitor.RootComparer);
private readonly FolderScanBudget _budget = new();
private readonly string? _indexDirectory;
+ private readonly Func _probeJournal;
private FolderUsage.Cache _cache;
private Task? _run;
+ private long _journalProbes;
private int _version;
private bool _active = true, _needsMeasurement = true;
private string? _measuringRoot;
- internal FolderMonitor(string? indexDirectory = null) { _indexDirectory = indexDirectory; _cache = new(_budget); }
+ internal FolderMonitor(string? indexDirectory = null, Func? probeJournal = null)
+ { _indexDirectory = indexDirectory; _probeJournal = probeJournal ?? WindowsFolderJournal.Probe; _cache = new(_budget); }
internal (long Roots, long Directories) QueryCounts { get { var cache = Volatile.Read(ref _cache); return (cache.RootReads, cache.DirectoryReads); } }
+ internal long JournalProbes => Interlocked.Read(ref _journalProbes);
internal bool IsMeasuring { get { lock (_sync) return _scan != null; } }
internal bool IsMeasuringRoot(string root) { lock (_sync) return _active && DriveMonitor.RootComparer.Equals(root, _measuringRoot); }
internal FolderIndexStatus? IndexStatus(string root) { lock (_sync) return _status.GetValueOrDefault(root); }
@@ -38,14 +46,20 @@ public void Configure(DrivePreference[] preferences)
{
lock (_sync)
{
- _scan?.Cancel(); _configuration = preferences; _version++; _dirty.Clear(); _reset.Clear(); _needsMeasurement = true;
- _current = preferences.ToDictionary(p => p.Root, p => (p.Folders ?? Array.Empty()).Select(f => new FolderReading(f.Path, f.Color, null, FolderState.Scanning)).ToArray(), DriveMonitor.RootComparer);
+ _scan?.Cancel(); _configuration = preferences; _version++; _dirty.Clear(); _reset.Clear(); _refresh.Clear(); _rebuild.Clear(); _checkRoots.Clear(); _changedItems.Clear(); _needsMeasurement = true;
+ var previous = _current;
+ _current = preferences.ToDictionary(p => p.Root, p => (p.Folders ?? Array.Empty()).Select(folder =>
+ {
+ var saved = previous.GetValueOrDefault(p.Root)?.FirstOrDefault(row => DriveMonitor.RootComparer.Equals(row.Path, folder.Path));
+ return saved?.Bytes != null ? saved with { Path = folder.Path, Color = folder.Color, State = FolderState.Scanning }
+ : new FolderReading(folder.Path, folder.Color, null, FolderState.Scanning);
+ }).ToArray(), DriveMonitor.RootComparer);
Signal();
}
}
internal void RefreshIndex(string root, bool rebuild)
{
- lock (_sync) { if (rebuild) _rebuild.Add(root); _needsMeasurement = true; Signal(); }
+ lock (_sync) { (rebuild ? _rebuild : _refresh).Add(root); Signal(); }
}
public void Start() { _run ??= Task.Run(RunAsync); }
public void SetActive(bool active)
@@ -57,17 +71,27 @@ public void SetActive(bool active)
}
}
private void Signal() { if (_changed.CurrentCount == 0) _changed.Release(); }
- private void Invalidate(int version, string path, bool reset)
+ private void Invalidate(int version, string path, FolderChange change)
{
lock (_sync)
{
if (version != _version || _stop.IsCancellationRequested) return;
- (reset ? _reset : _dirty).Add(path); if (_active) Signal();
+ var pending = change switch
+ {
+ FolderChange.ItemChanged => _changedItems,
+ FolderChange.RootMetadata => _checkRoots,
+ FolderChange.Reset => _reset,
+ _ => _dirty
+ };
+ pending.Add(path); if (_active) Signal();
}
}
private async Task RunAsync()
{
var watches = new List(); FolderIndexStore? store = null;
+ var journal = new Dictionary(DriveMonitor.RootComparer);
+ var lastCheckpoint = Stopwatch.GetTimestamp();
+ var loadManaged = true;
var cache = _cache; var cachedVersion = -1; var retry = false; var indexFaulted = false;
try
{
@@ -87,7 +111,7 @@ private async Task RunAsync()
}
if (cachedVersion != version)
{
- foreach (var watch in watches) watch.Dispose(); watches.Clear(); cache.Flush();
+ foreach (var watch in watches) watch.Dispose(); watches.Clear(); cache.Flush(); journal.Clear();
if (_indexDirectory != null && preferences.Any(p => p.Folders?.Length > 0)) store ??= new(_indexDirectory);
if (store != null)
{
@@ -100,75 +124,92 @@ private async Task RunAsync()
Changed?.Invoke();
}
cache = new(_budget, store) { DirectoriesPerSlice = store == null ? int.MaxValue : 8 };
- cache.Configure(preferences); cache.RefreshManaged(_stop.Token); Volatile.Write(ref _cache, cache); cachedVersion = version;
+ cache.Configure(preferences); Volatile.Write(ref _cache, cache); cachedVersion = version; loadManaged = true;
foreach (var folder in preferences.SelectMany(p => p.Folders ?? Array.Empty()))
- watches.Add(new(folder.Path, (path, full) => Invalidate(version, path, full), cache.Owns));
+ watches.Add(new(folder.Path, (path, change) => Invalidate(version, path, change), cache.Owns));
lock (_sync)
if (version == _version)
_current = preferences.ToDictionary(p => p.Root, p => cache.Saved(p.Root).Select(r => store != null && r.Bytes.HasValue ? r with { State = FolderState.Cached } : r).ToArray(), DriveMonitor.RootComparer);
Changed?.Invoke();
}
if (!active) { await _changed.WaitAsync(_stop.Token); continue; }
- string[] dirty, reset, rebuild; bool pending; CancellationTokenSource scan;
+ string[] dirty, reset, rebuild, refresh, checkRoots, changedItems; bool pending; CancellationTokenSource scan;
lock (_sync)
{
if (!_active || version != _version) continue;
_changed.Wait(0); pending = _needsMeasurement; _needsMeasurement = false;
- dirty = _dirty.ToArray(); reset = _reset.ToArray(); rebuild = _rebuild.ToArray(); _dirty.Clear(); _reset.Clear(); _rebuild.Clear();
+ dirty = _dirty.ToArray(); reset = _reset.ToArray(); rebuild = _rebuild.ToArray(); refresh = _refresh.ToArray();
+ checkRoots = _checkRoots.ToArray(); _checkRoots.Clear();
+ changedItems = _changedItems.ToArray(); _changedItems.Clear();
+ _dirty.Clear(); _reset.Clear(); _rebuild.Clear(); _refresh.Clear();
_scan = scan = CancellationTokenSource.CreateLinkedTokenSource(_stop.Token);
}
var continueWork = false;
+ var appliedChanges = false;
try
{
- var journal = new Dictionary(DriveMonitor.RootComparer);
- void Synchronize()
+ var recheck = reset.Select(path => Path.GetPathRoot(path)!).Concat(rebuild).Concat(refresh).ToHashSet(DriveMonitor.RootComparer);
+ var changedDirectories = dirty.ToHashSet(DriveMonitor.RootComparer);
+ // Windows can emit Changed for directory metadata during enumeration. Only structural
+ // directory events and changes to non-directory entries invalidate a listing.
+ foreach (var item in changedItems)
+ if (!cache.KnownDirectory(item) && Path.GetDirectoryName(item) is string directory) changedDirectories.Add(directory);
+ var changed = changedDirectories.Select(path => Path.GetPathRoot(path)!).ToHashSet(DriveMonitor.RootComparer);
+ var affected = changed.Concat(recheck).Concat(checkRoots.Select(path => Path.GetPathRoot(path)!)).ToHashSet(DriveMonitor.RootComparer);
+ foreach (var watch in watches)
{
- if (store == null) return;
+ scan.Token.ThrowIfCancellationRequested();
+ if (!watch.Available && (loadManaged || pending || retry || reset.Contains(watch.Path, DriveMonitor.RootComparer)
+ || refresh.Contains(Path.GetPathRoot(watch.Path)!, DriveMonitor.RootComparer))) _budget.Query(watch.Connect, scan.Token);
+ }
+ if (loadManaged) { cache.RefreshManaged(scan.Token); loadManaged = false; }
+ // Establish the watchers before reading the cursor so work arriving after it remains observable.
+ if (store != null)
foreach (var drive in preferences.Where(p => p.Folders?.Length > 0))
{
- var status = _budget.Query(() => WindowsFolderJournal.Probe(drive.Root), scan.Token); journal[drive.Root] = status;
+ if (journal.TryGetValue(drive.Root, out var known) && !recheck.Contains(drive.Root) &&
+ !(known.Access == FolderIndexAccess.Ready && changed.Contains(drive.Root)) &&
+ !(retry && known.Access == FolderIndexAccess.Unavailable)) continue;
+ var status = _budget.Query(() =>
+ {
+ Interlocked.Increment(ref _journalProbes);
+ return _probeJournal(drive.Root);
+ }, scan.Token);
var progress = cache.Progress(drive.Root);
lock (_sync) if (version == _version) _status[drive.Root] = new(status.Access, progress.Directories, progress.Files,
status.Error > 0 ? status.Error.ToString(System.Globalization.CultureInfo.InvariantCulture) : null);
- }
- Changed?.Invoke();
- foreach (var drive in preferences.Where(p => p.Folders?.Length > 0))
- {
- var status = journal[drive.Root];
- if (status.Access != FolderIndexAccess.Ready) continue;
- if (cache.Cursors.TryGetValue(drive.Root, out var saved) && WindowsFolderJournal.Covers(status, saved))
- cache.SaveCursor(drive.Root, WindowsFolderJournal.Replay(drive.Root, status, saved, _budget, change => cache.Invalidate(drive.Root, change), scan.Token));
- else
+ Changed?.Invoke();
+ if (status.Access == FolderIndexAccess.Ready)
{
- foreach (var folder in drive.Folders!) if (cache.HasSavedIndex(folder.Path)) cache.Reset(folder.Path);
- cache.SaveCursor(drive.Root, new(status.JournalId, status.NextUsn));
+ if (cache.Cursors.TryGetValue(drive.Root, out var saved) && WindowsFolderJournal.Covers(status, saved))
+ cache.SaveCursor(drive.Root, WindowsFolderJournal.Replay(drive.Root, status, saved, _budget, change => cache.Invalidate(drive.Root, change), scan.Token));
+ else
+ {
+ foreach (var folder in drive.Folders!) if (cache.HasSavedIndex(folder.Path)) cache.Reset(folder.Path);
+ cache.SaveCursor(drive.Root, new(status.JournalId, status.NextUsn));
+ }
}
+ journal[drive.Root] = status;
}
- }
- cache.Checkpoint = Synchronize;
- Synchronize();
- foreach (var watch in watches)
- {
- scan.Token.ThrowIfCancellationRequested();
- if (!watch.Available) _budget.Query(watch.Connect, scan.Token);
- }
- // The watcher covers changes while the journal checkpoint is being read.
- Synchronize();
- foreach (var path in dirty)
+ foreach (var path in changedDirectories)
if (store == null || !journal.TryGetValue(Path.GetPathRoot(path)!, out var source) || source.Access != FolderIndexAccess.Ready) cache.Invalidate(path);
foreach (var path in reset)
if (watches.Where(w => DriveMonitor.RootComparer.Equals(w.Path, path)).Any(w => w.TakeIdentityChange()) ||
store == null || !journal.TryGetValue(Path.GetPathRoot(path)!, out var source) || source.Access != FolderIndexAccess.Ready) cache.Reset(path);
foreach (var root in rebuild)
foreach (var folder in preferences.Where(p => DriveMonitor.RootComparer.Equals(p.Root, root)).SelectMany(p => p.Folders ?? Array.Empty())) cache.Reset(folder.Path);
+ foreach (var path in checkRoots) cache.CheckRootOnRead(path);
+ appliedChanges = true;
if (retry) cache.RetryPartial();
var allowed = preferences.Where(p => store == null || !journal.TryGetValue(p.Root, out var access) || access.Access == FolderIndexAccess.Ready ||
- access.Access == FolderIndexAccess.Unsupported && (rebuild.Contains(p.Root, DriveMonitor.RootComparer) || p.Folders?.All(f => !cache.HasSavedIndex(f.Path)) == true || dirty.Concat(reset).Any(d => DriveMonitor.RootComparer.Equals(Path.GetPathRoot(d), p.Root)))) .ToArray();
+ access.Access == FolderIndexAccess.Unsupported && (affected.Contains(p.Root) ||
+ p.Folders!.Any(f => !cache.HasSavedIndex(f.Path)) || cache.HasWorkFor(p.Folders!.Select(f => f.Path)))).ToArray();
+ var allowedRoots = allowed.Select(p => p.Root).ToHashSet(DriveMonitor.RootComparer);
var paths = allowed.SelectMany(p => p.Folders ?? Array.Empty()).Select(p => p.Path).ToArray();
- var measure = pending || dirty.Length > 0 || reset.Length > 0 || rebuild.Length > 0 || cache.HasWorkFor(paths) || retry && allowed.Any(p => cache.Saved(p.Root).Any(r => r.State == FolderState.Partial));
+ var measure = pending || affected.Count > 0 || cache.HasWorkFor(paths) || retry && allowed.Any(p => cache.Saved(p.Root).Any(r => r.State == FolderState.Partial));
if (measure && paths.Length > 0)
{
- var result = FolderUsage.Scan(allowed, scan.Token, measured: (root, reading) =>
+ FolderUsage.Scan(allowed, scan.Token, measured: (root, reading) =>
{
var progress = cache.Progress(root);
lock (_sync)
@@ -184,13 +225,12 @@ void Synchronize()
Changed?.Invoke();
});
cache.Configure(preferences);
- if (OperatingSystem.IsWindows())
- foreach (var root in result.Keys.ToArray())
- result[root] = result[root].Select(row => row.State == FolderState.Available && watches.Any(w => DriveMonitor.RootComparer.Equals(w.Path, row.Path) && !w.Available)
- ? row with { State = FolderState.Partial, Skipped = row.Skipped + 1 } : row).ToArray();
- lock (_sync) if (version == _version) foreach (var pair in result) _current[pair.Key] = pair.Value;
}
- cache.Flush(); cache.RefreshManaged(scan.Token);
+ continueWork = cache.HasWorkFor(paths) || allowed.Any(p => cache.Saved(p.Root).Any(r => r.State == FolderState.Scanning));
+ if (store?.HasChanges == true && (!continueWork || Stopwatch.GetElapsedTime(lastCheckpoint) >= TimeSpan.FromSeconds(1)))
+ {
+ cache.Flush(); cache.RefreshManaged(scan.Token); lastCheckpoint = Stopwatch.GetTimestamp();
+ }
lock (_sync)
{
if (version == _version)
@@ -199,8 +239,11 @@ void Synchronize()
var source = journal.GetValueOrDefault(preference.Root);
var saved = cache.Saved(preference.Root);
if (store != null && source?.Access != FolderIndexAccess.Ready)
- _current[preference.Root] = saved.Select(row => row with { State = row.Bytes.HasValue ? FolderState.Cached : FolderState.Unavailable }).ToArray();
- else if (measure) _current[preference.Root] = saved;
+ _current[preference.Root] = saved.Select(row => row.State == FolderState.Scanning && allowedRoots.Contains(preference.Root) ? row
+ : row with { State = row.Bytes.HasValue ? FolderState.Cached : row.State == FolderState.Scanning ? FolderState.Unavailable : row.State }).ToArray();
+ else if (measure) _current[preference.Root] = saved.Select(row =>
+ row.State == FolderState.Available && watches.Any(w => DriveMonitor.RootComparer.Equals(w.Path, row.Path) && !w.Available)
+ ? row with { State = FolderState.Partial, Skipped = row.Skipped + 1 } : row).ToArray();
if (store != null)
{
var progress = cache.Progress(preference.Root);
@@ -208,18 +251,28 @@ void Synchronize()
source?.Error is > 0 ? source.Error.ToString(System.Globalization.CultureInfo.InvariantCulture) : null);
}
}
- continueWork = cache.HasWorkFor(paths) || allowed.Any(p => cache.Saved(p.Root).Any(r => r.State == FolderState.Scanning));
}
Changed?.Invoke();
}
- catch (OperationCanceledException) when (scan.IsCancellationRequested) { lock (_sync) _needsMeasurement = true; cache.Flush(); }
+ catch (OperationCanceledException) when (scan.IsCancellationRequested)
+ {
+ lock (_sync)
+ {
+ _needsMeasurement = true;
+ if (!appliedChanges && version == _version)
+ {
+ _dirty.UnionWith(dirty); _reset.UnionWith(reset); _rebuild.UnionWith(rebuild); _refresh.UnionWith(refresh);
+ _checkRoots.UnionWith(checkRoots); _changedItems.UnionWith(changedItems);
+ }
+ }
+ cache.Flush();
+ }
finally
{
- cache.Checkpoint = null;
lock (_sync) { _measuringRoot = null; _scan = null; scan.Dispose(); }
Changed?.Invoke();
}
- var signaled = await _changed.WaitAsync(TimeSpan.FromSeconds(continueWork ? 1 : 60), _stop.Token);
+ var signaled = await _changed.WaitAsync(continueWork ? TimeSpan.FromMilliseconds(250) : TimeSpan.FromSeconds(60), _stop.Token);
retry = !signaled && !continueWork;
if (signaled) await Task.Delay(TimeSpan.FromSeconds(2), _stop.Token);
}
diff --git a/src/platforms/resources/FolderUsage.cs b/src/platforms/resources/FolderUsage.cs
index 2b86dc6b..c85f47ed 100644
--- a/src/platforms/resources/FolderUsage.cs
+++ b/src/platforms/resources/FolderUsage.cs
@@ -80,7 +80,7 @@ private static FolderReading Read(string root, FolderPreference folder, Cancella
if (!OperatingSystem.IsWindows()) return new(folder.Path, folder.Color, null, FolderState.Unsupported);
cancellation.ThrowIfCancellationRequested();
var work = cache.Pending(folder.Path);
- if (work == null)
+ if (work == null || cache.NeedsRootCheck(folder.Path))
{
cache.Begin(folder.Path);
uint volume;
@@ -92,10 +92,9 @@ private static FolderReading Read(string root, FolderPreference folder, Cancella
if ((cache.Query(() => File.GetAttributes(path), cancellation) & FileAttributes.ReparsePoint) != 0)
return Failed(FolderState.Unavailable);
}
- if ((cache.Query(() => File.GetAttributes(folder.Path), cancellation) & FileAttributes.Directory) == 0) return Failed(FolderState.Unavailable);
var info = cache.Query(() =>
{
- using var handle = CreateFileW(NativePath(folder.Path), 0x80, 7, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero);
+ using var handle = CreateFileW(NativePath(folder.Path), 0x81, 7, IntPtr.Zero, 3, 0x02200000, IntPtr.Zero);
if (handle.IsInvalid || !GetFileInformationByHandle(handle, out var value))
throw new IOException("Folder volume cannot be read.", new Win32Exception(Marshal.GetLastWin32Error()));
return value;
@@ -111,7 +110,7 @@ private static FolderReading Read(string root, FolderPreference folder, Cancella
catch (UnauthorizedAccessException) { return Failed(FolderState.Unavailable); }
cache.Trust(folder.Path);
if (cache.TryReuse(folder.Path, out var saved)) return saved with { Color = folder.Color };
- work = cache.Start(folder.Path, volume);
+ work = cache.Pending(folder.Path) ?? cache.Start(folder.Path, volume);
}
var processed = 0;
var slice = Stopwatch.StartNew();
diff --git a/src/platforms/resources/FolderUsageCache.cs b/src/platforms/resources/FolderUsageCache.cs
index 37ee681a..5114fef2 100644
--- a/src/platforms/resources/FolderUsageCache.cs
+++ b/src/platforms/resources/FolderUsageCache.cs
@@ -48,7 +48,6 @@ internal sealed class Work
private readonly Dictionary _readings = new(DriveMonitor.RootComparer);
internal readonly Dictionary Cursors = new(DriveMonitor.RootComparer);
private readonly Dictionary _persistedCursors = new(DriveMonitor.RootComparer);
- internal Action? Checkpoint;
internal int DirectoriesPerSlice { get; set; } = int.MaxValue;
internal long DirectoryReads { get; private set; }
internal long RootReads { get; private set; }
@@ -125,7 +124,7 @@ internal void BeginScan() { }
internal bool TryReuse(string folder, out FolderReading reading)
{
return _readings.TryGetValue(folder, out reading!) && reading.State != FolderState.Scanning && !_work.ContainsKey(folder) &&
- (_store == null || _trusted.Contains(folder)) && !_dirty.Concat(_reset).Any(path => DriveMonitor.RootComparer.Equals(path, folder) || Inside(folder, path) || Inside(path, folder));
+ _trusted.Contains(folder) && !_dirty.Concat(_reset).Any(path => DriveMonitor.RootComparer.Equals(path, folder) || Inside(folder, path) || Inside(path, folder));
}
internal void Begin(string folder) { RootReads++; }
internal Work? Pending(string folder) => _work.GetValueOrDefault(folder);
@@ -133,6 +132,8 @@ internal bool TryReuse(string folder, out FolderReading reading)
internal Work Start(string folder, uint volume) { var value = new Work(folder, volume); _work[folder] = value; return value; }
internal long Bytes(string folder) => _bytes.GetValueOrDefault(folder);
internal void Trust(string folder) => _trusted.Add(folder);
+ internal bool NeedsRootCheck(string folder) => !_trusted.Contains(folder);
+ internal void CheckRootOnRead(string folder) => _trusted.Remove(folder);
internal string[] UntrustedRoots => _roots.Keys.Where(p => !_trusted.Contains(p)).ToArray();
internal void Finish(string folder)
{
@@ -254,8 +255,10 @@ private void SetDirectory(string directory, FolderEntry[] entries)
directory = canonical;
if (_directories.TryGetValue(directory, out var old)) RemoveReferences(directory, old);
_directories[directory] = entries; _byFolder[folder].Add(directory);
+ var failed = false;
foreach (var entry in entries)
{
+ failed |= entry.Failed;
if ((entry.Attributes & (FileAttributes.Directory | FileAttributes.ReparsePoint)) == FileAttributes.Directory && entry.Id != 0)
{ _directoryIds[new(Path.GetPathRoot(directory)!.ToUpperInvariant(), entry.Volume, entry.Id)] = entry.Path; _knownDirectories.Add(entry.Path); }
if (!entry.Resolved || entry.Failed) continue;
@@ -266,7 +269,7 @@ private void SetDirectory(string directory, FolderEntry[] entries)
else if (!DriveMonitor.RootComparer.Equals(file.FirstDirectory, directory)) (file.OtherDirectories ??= new(DriveMonitor.RootComparer)).Add(directory);
}
if (_dirty.Remove(directory)) Delete(FolderIndexStore.DirtyKind, directory);
- _failed.Remove(directory);
+ if (failed) _failed.Add(directory); else _failed.Remove(directory);
if (!Owns(directory)) Put(FolderIndexStore.DirectoryKind, directory, entries);
if (old != null) Prune(old, directory);
}
@@ -306,14 +309,13 @@ internal IEnumerable Entries(DirectoryInfo directory, uint volume,
if (!children.TryGetValue(child.Path, out var id) || id == 0 || id != child.Id) Reset(child.Path, false);
}
SetDirectory(path, fresh);
- if (++_writes % 64 == 0) { Checkpoint?.Invoke(); Flush(); }
+ if (++_writes % 64 == 0) Flush();
return fresh;
}
internal void FailDirectory(string path) { foreach (var child in _directories.Keys.Where(p => DriveMonitor.RootComparer.Equals(path, p) || Inside(path, p)).ToArray()) RemoveDirectory(child); _dirty.Remove(path); _failed.Add(path); }
internal void RetryPartial()
{
foreach (var directory in _failed.ToArray()) Invalidate(directory);
- foreach (var pair in _directories) if (pair.Value.Any(e => e.Failed)) Invalidate(pair.Key);
foreach (var row in _readings.Values.Where(r => r.State == FolderState.Partial))
foreach (var path in _directoryIds.Values.Where(p => (DriveMonitor.RootComparer.Equals(p, row.Path) || Inside(row.Path, p)) && !_directories.ContainsKey(p)).ToArray()) Invalidate(path);
}
diff --git a/src/windows/AccountAutomationUiDiagnostics.cs b/src/windows/AccountAutomationUiDiagnostics.cs
index a443ef24..e55aae2b 100644
--- a/src/windows/AccountAutomationUiDiagnostics.cs
+++ b/src/windows/AccountAutomationUiDiagnostics.cs
@@ -118,21 +118,26 @@ void ActivateWarning(DependencyObject element)
vault.Data.Drives.Clear();
var service = new AccountService(vault, System.IO.Path.Combine(directory, "absent-restart-completion-home"));
var window = new MainWindow(service, new Program.Options { UiEvidenceDirectory = directory, CodexHome = service.CodexHome, DataDirectory = vault.DirectoryPath });
- var plan = new AccountSwitchPlan { Phase = SwitchPhase.Finished, AccountApplied = true, RestartOnly = true,
- Chats = new() { new() { ResumeState = ChatResumeState.AlreadyRunning } } };
var flags = BindingFlags.Instance | BindingFlags.NonPublic;
var originalLanguage = Loc.Language;
try
{
- foreach (var language in Loc.Languages)
+ foreach (var hasChat in new[] { true, false })
{
- window.ChangeLanguage(language.Code, false);
+ var plan = new AccountSwitchPlan { Phase = SwitchPhase.Finished, AccountApplied = true, RestartOnly = true };
+ if (hasChat) plan.Chats.Add(new() { ResumeState = ChatResumeState.AlreadyRunning });
+ vault.Data.PendingSwitch = plan;
typeof(MainWindow).GetMethod("SwitchChanged", flags)!.Invoke(window, new object[] { plan });
- var status = (TextBlock)typeof(MainWindow).GetField("_status", flags)!.GetValue(window)!;
- assert(status.Text == Loc.T("restart.done") && status.Visibility == Visibility.Visible,
- "Completed restart lost its translated status: " + language.Code);
- assert(plan.Error == null && SwitchRecovery.Active(plan) == null,
- "Rendering completion created a recovery failure: " + language.Code);
+ foreach (var language in Loc.Languages)
+ {
+ window.ChangeLanguage(language.Code, false);
+ var status = (TextBlock)typeof(MainWindow).GetField("_switchText", flags)!.GetValue(window)!;
+ var panel = (Border)typeof(MainWindow).GetField("_switchPanel", flags)!.GetValue(window)!;
+ assert(status.Text == Loc.T(hasChat ? "restart.done" : "restart.opened") && panel.Visibility == Visibility.Visible,
+ "Completed restart lost its translated status: " + language.Code);
+ assert(plan.Error == null && vault.Data.ActivePendingSwitch == null,
+ "Rendering completion created a recovery failure: " + language.Code);
+ }
}
}
finally { window.Close(); Loc.SetLanguage(originalLanguage); }
diff --git a/src/windows/AccountCardHeader.cs b/src/windows/AccountCardHeader.cs
index 8f21d554..63a4a2d3 100644
--- a/src/windows/AccountCardHeader.cs
+++ b/src/windows/AccountCardHeader.cs
@@ -8,10 +8,12 @@ internal sealed class AccountCardHeader : Grid
{
public StackPanel Actions { get; }
private readonly TextBlock _name, _metadata;
+ private readonly bool _showCompactStatus;
private readonly Dictionary
diff --git a/tests/windows-handoff/Program.cs b/tests/windows-handoff/Program.cs
index 15f13837..f84f16bf 100644
--- a/tests/windows-handoff/Program.cs
+++ b/tests/windows-handoff/Program.cs
@@ -14,6 +14,8 @@ internal static class Program
private static async Task Main(string[] args)
{
if (!OperatingSystem.IsWindows()) throw new PlatformNotSupportedException("Native Windows handoff checks require Windows");
+ if (args.Length == 2 && args[0] == "--account-windows")
+ return await AccountWindowContracts.RunAsync(args[1]);
var executable = Path.GetFullPath(args.Single());
if (Path.GetFileName(executable) != "HandoffFixture.exe" || !File.Exists(executable) || RuntimeLocator.IsDesktopRunning(executable))
throw new InvalidOperationException("A fresh disposable fixture executable is required");
@@ -65,16 +67,17 @@ private static async Task Main(string[] args)
var backend = new Backend(executable, fixture); var coordinator = new AccountSwitchCoordinator(backend, _ => { }, _ => { }, UserErrors.Describe);
var plan = await coordinator.PrepareAsync("target", DateTimeOffset.UtcNow, CancellationToken.None);
watch.Restart(); var timedOut = false;
- try { await coordinator.RunAsync(plan, CancellationToken.None); } catch (IOException) { timedOut = true; }
+ try { await coordinator.RunAsync(plan, CancellationToken.None); } catch (InvalidOperationException) { timedOut = true; }
Assert(timedOut && watch.Elapsed >= TimeSpan.FromSeconds(29) && watch.Elapsed < TimeSpan.FromSeconds(40) &&
- !fixture.Child.HasExited && !plan.AccountApplied && !backend.Calls.Contains("launch"), "Deadline, no-force shutdown or apply/launch boundary failed");
+ !fixture.Child.HasExited && !plan.AccountApplied && !backend.Calls.Contains("launch") &&
+ backend.Calls.Count(call => call == "close") == 1, "Deadline, no-force shutdown or apply/launch boundary failed");
passed.Add("30-second deadline stops handoff without force-killing a slow child or applying credentials");
}
using (var fixture = await StartAsync(executable, directory, 0, true))
{
var denied = false;
try { await DesktopShutdown.CloseAsync(executable, CancellationToken.None); }
- catch (IOException error) when (error.InnerException is System.ComponentModel.Win32Exception native && native.NativeErrorCode == 351) { denied = true; }
+ catch (InvalidOperationException error) when (error.InnerException is System.ComponentModel.Win32Exception native && native.NativeErrorCode == 351) { denied = true; }
Assert(denied && !fixture.Parent.HasExited, "Unsupported native shutdown was hidden or force-killed");
passed.Add("Restart Manager unsupported headless shutdown is preserved and does not force-close the process");
}
diff --git a/tests/windows-startup/Program.cs b/tests/windows-startup/Program.cs
index 3bf673f7..32489fbf 100644
--- a/tests/windows-startup/Program.cs
+++ b/tests/windows-startup/Program.cs
@@ -144,7 +144,7 @@ public static int Main(string[] args)
{
window.Show(); await window.Dispatcher.InvokeAsync(() => {}, DispatcherPriority.Loaded);
Func initialize = token => Call(window, "EnsureInitializedAsync", token);
- await Call(window, "RunAsync", "Codex 계정 확인 중…", initialize);
+ await Call(window, "RunAsync", "Codex 계정 확인 중…", initialize, Type.Missing);
Check(label + ": real initialization failed while the configured client path is absent", !(bool)Field(window,"_ready") && ((Task)Field(window,"_initialization")).IsFaulted);
Check(label + ": account addition stays disabled before successful initialization", !((Button)Field(window,"_add")).IsEnabled);
await Task.Delay(200); Capture(window, Path.Combine(output, label + "-unavailable.png"));