Skip to content

Commit 665cc48

Browse files
luvs01lidge-jun
andauthored
fix(link): restore owned integrations before native signal exit (#8036)
* fix(link): restore local routing when child stops * fix(client): restore owned Link routing before listener release * test(cli): align stop contracts with owned routing cleanup * test(client): preserve failure exit in signal cleanup contract * docs(link): document pending disconnect stop refusal Add an incomplete disconnect receipt (client_disconnect_pending) to the existing stop restoration refusal conditions in all eight lifecycle guides. Keep the recovery-evidence guidance and the runtime behavior unchanged. * fix(link): preserve handled-signal exit wiring * fix(link): allow catalog sync before signal restoration * fix(link): fence sync commits during signal shutdown * fix(link): keep runtime publication through its record builder * fix(link): retry transient stop-fence contention explicitly * docs(link): define the configuration mutation lock on first use * docs(link): keep operator recovery steps in the CLI lifecycle guide The structure note now states only the runtime behavior; starting and resyncing a Link Child after a signal stop is documented with the other stop steps in the public lifecycle reference. * test(link): use the canonical Codex home in sync-stop fixtures Sync records the canonical catalog path while the fixture created its native backup under the /var alias on macOS, so restoration fell back to an empty catalog; clean up held children with SIGKILL so a failed assertion is reported instead of hanging. Also correct the offline-sync wording: an offline sync does reapply routing. --------- Co-authored-by: JUN <[email protected]>
1 parent 491beb6 commit 665cc48

28 files changed

Lines changed: 958 additions & 36 deletions

‎docs-site/src/content/docs/fr/reference/cli/lifecycle.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,8 @@ ocx start --socks5-off
3232

3333
### `ocx stop`
3434

35+
Un Link Child non supervisé restaure Codex natif et Grok avant de libérer son listener lors d’un signal, en revérifiant la connexion à chaque écriture. Service/Desktop, sibling, transfert de redémarrage et reçu stop du parent préservent les intégrations. L’arrêt refuse le redémarrage avec `409 runtime_stopping`. Une terminaison forcée peut éviter le signal ; la restauration par `ocx stop` reste nécessaire.
36+
3537
Arrête le proxy actif à partir de son PID, supprime le fichier de PID et rétablit le fonctionnement natif de Codex. Si un service d’arrière-plan géré est installé, `ocx stop` l’arrête d’abord afin qu’il ne puisse pas relancer le proxy. Le bouton **Stop** du tableau de bord Web exécute la même opération (`POST /api/stop`) sur tous les backends, sauf le Planificateur de tâches Windows : le wrapper peut y relancer le proxy après la fin de la tâche, donc le tableau de bord refuse avec `respawnable_service`, ne modifie rien et vous demande d'exécuter `ocx stop`.
3638

3739
Sur un client hub connecté, `ocx stop`, y compris via l’API, conserve le routage Codex, le catalogue et la configuration Grok appartenant à la connexion ; `ocx start` les dessert de nouveau. L’arrêt explicite d’un Remote Link Child rétablit au contraire, si la restauration partagée réussit, le routage natif de Codex, le catalogue et les métadonnées de reprise sauvegardées, et supprime la configuration Grok gérée. La connexion Home enregistrée reste conservée ; `ocx disconnect` la supprime.

‎docs-site/src/content/docs/ja/reference/cli/lifecycle.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ ocx start --socks5-off
2828

2929
### `ocx stop`
3030

31+
監督プロセスのない Link Child は終了シグナル時、各書き込みで接続を再確認し、リスナーを閉じる前に Codex と管理対象 Grok を復元します。サービス・Desktop、sibling、再起動の引き継ぎ、親 stop 記録がある場合は設定を保持します。終了中の再起動は `409 runtime_stopping` です。強制終了はシグナル処理を省略する場合があり、親 `ocx stop` の復元も必要です。
32+
3133
実行中のプロキシを (PID によって) 停止し、PID ファイルを削除します。スタンドアロンの所有者ではネイティブ Codex を復元します。マネージド バックグラウンド サービスがインストールされている場合、`ocx stop` はそれを最初に停止するため、プロキシを再起動できません。Web ダッシュボードの **停止** ボタンは同じ処理 (`POST /api/stop`) を実行しますが、Windows タスク スケジューラだけは例外です。タスク終了後もラッパーがプロキシを再起動しうるため、ダッシュボードは `respawnable_service` で拒否し、何も変更せずに `ocx stop` の実行を促します。
3234

3335
接続済みの hub クライアントでは、`ocx stop`(成功した API 停止を含む)は接続が所有する Codex のルーティング、モデルカタログ、Grok 設定を保持します。`ocx start` はルーティングを再注入せず、その設定で再び処理します。Codex を自身のアカウントへ戻すには `ocx disconnect`、既にネイティブルーティングへ戻した後の再適用には `ocx sync --restart-codex` を使います。

‎docs-site/src/content/docs/ko/reference/cli/lifecycle.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -44,6 +44,8 @@ ocx start --socks5-off
4444

4545
### `ocx stop`
4646

47+
감독 프로세스 없이 실행되는 Link Child는 종료 신호 처리 시 각 쓰기 직전에 연결을 재확인하고 리스너를 닫기 전에 Codex 기본 설정과 관리 Grok 설정을 복원합니다. 서비스·Desktop 감독, sibling, 재시작·재활용 인계, 부모 stop 영수증이 있으면 설정을 보존합니다. 종료 중 재시작 요청은 `409 runtime_stopping`입니다. 강제 종료는 신호 처리를 건너뛸 수 있어 부모 `ocx stop`의 복원도 필요합니다.
48+
4749
실행 중인 프록시를 PID 기준으로 중지하고 PID 파일을 삭제합니다. 독립 실행 소유자라면 기본 Codex를 복원합니다. 관리형
4850
백그라운드 서비스가 설치되어 있으면 `ocx stop`이 먼저 그 서비스를 중지하므로 프록시가 다시
4951
올라올 수 없습니다. 웹 대시보드의 **Stop** 버튼도 같은 동작(`POST /api/stop`)을 하지만, Windows 작업 스케줄러는 예외입니다. 작업이 끝나도 래퍼가 프록시를 다시 띄울 수 있어서, 대시보드는 `respawnable_service`로 거절하고 아무것도 바꾸지 않은 채 `ocx stop` 실행을 안내합니다.

‎docs-site/src/content/docs/reference/cli/lifecycle.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,8 @@ ocx start --socks5-off
8282

8383
### `ocx stop [--json]`
8484

85+
An unsupervised Link Child handling a shutdown signal restores native Codex and managed Grok before releasing its listener, rechecking the served connection before each write. Service/Desktop supervision, sibling ownership, restart/recycle handoff and pending parent stop receipts preserve integrations. Shutdown rejects bound restart with `409 runtime_stopping`. Forced termination can bypass signal handlers; parent `ocx stop` restoration remains necessary. To route Codex through Home again after such a stop, start the Child (`ocx start`, or `ocx service start` for an installed service) and then run `ocx sync --restart-codex`. Starting alone does not reapply routing. A sync run while the Child is stopped still reapplies routing, which points Codex at a listener that is not running, so start the Child first.
86+
8587
Stop the running proxy (by PID), remove the PID file, and restore native Codex for standalone owners. If a managed
8688
background service is installed, `ocx stop` also stops it first so it cannot respawn the proxy.
8789
On a connected hub client, `ocx stop` leaves Codex routing, its

‎docs-site/src/content/docs/ru/reference/cli/lifecycle.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ ocx start --socks5-off
5050

5151
### `ocx stop`
5252

53+
Link Child без супервизора при сигнале восстанавливает нативный Codex и управляемый Grok до закрытия listener, проверяя подключение перед каждой записью. Сервис/Desktop, sibling, передача перезапуска и квитанция stop родителя сохраняют настройки. Во время завершения перезапуск возвращает `409 runtime_stopping`. Принудительное завершение может обойти сигнал; восстановление родителем `ocx stop` остаётся необходимым.
54+
5355
Остановить работающий прокси (по PID) и удалить PID-file; для автономного владельца также восстановить native Codex. Если
5456
установлена managed background service, `ocx stop` сначала останавливает и её, чтобы она не
5557
перезапустила прокси обратно. Кнопка **Stop** в веб-дашборде выполняет то же действие (`POST /api/stop`) на всех бэкендах, кроме планировщика заданий Windows: там обёртка может перезапустить прокси после завершения задачи, поэтому дашборд отказывает с `respawnable_service`, ничего не меняет и просит выполнить `ocx stop`.

‎docs-site/src/content/docs/tr/reference/cli/lifecycle.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,8 @@ ocx start --socks5-off
5050

5151
### `ocx stop`
5252

53+
Gözetimsiz Link Child kapanma sinyalinde her yazmadan önce bağlantıyı doğrular ve dinleyiciyi bırakmadan önce yerel Codex ile yönetilen Grok ayarlarını geri yükler. Servis/Desktop, sibling, yeniden başlatma devri ve üst stop makbuzu ayarları korur. Kapanma sırasında yeniden başlatma `409 runtime_stopping` döndürür. Zorla sonlandırma sinyali atlayabilir; üst `ocx stop` geri yüklemesi yine gereklidir.
54+
5355
Çalışan proxy'yi (PID'ye göre) durdurun, PID dosyasını kaldırın ve yerel Codex'i
5456
geri yükleyin. Yönetilen bir arka plan servisi kuruluysa `ocx stop` proxy'yi
5557
yeniden oluşturamaması için önce onu da durdurur. Web kontrol panelinin **Durdur** düğmesi aynı eylemi (`POST /api/stop`) Windows Görev Zamanlayıcı dışındaki tüm arka uçlarda çalıştırır: orada görev bittikten sonra sarmalayıcı proxy'yi yeniden başlatabilir, bu yüzden panel `respawnable_service` ile reddeder, hiçbir şeyi değiştirmez ve `ocx stop` çalıştırmanızı ister.

‎docs-site/src/content/docs/zh-cn/reference/cli/lifecycle.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ ocx start --socks5-off
2828

2929
### `ocx stop`
3030

31+
无人监督的 Link Child 处理退出信号时,会在每次写入前核对连接,并在关闭监听器前恢复 Codex 原生配置及受管理的 Grok。服务/Desktop、sibling、重启交接和父进程 stop 收据会保留配置。退出中的重启请求返回 `409 runtime_stopping`。强制终止可能跳过信号处理,仍需父进程 `ocx stop` 的恢复路径。
32+
3133
停止正在运行的代理(按 PID),移除 PID 文件;独立运行的所有者还会恢复原生 Codex。如果安装了受管后台服务,`ocx stop` 还会先停止该服务,这样它就无法重新拉起代理。Web 仪表盘的 **Stop** 按钮在多数后端执行同样的操作(`POST /api/stop`),但 Windows 任务计划程序除外:任务结束后包装器仍可能重新拉起代理,只有运行在代理之外的 stop 才能在恢复客户端配置前确认这个重启窗口,因此仪表盘会以 `respawnable_service` 拒绝、不做任何更改,并提示改用 `ocx stop`。
3234

3335
对于已连接的 hub 客户端,`ocx stop`(包括成功的 API 停止)会保留连接所拥有的 Codex 路由、模型目录和 Grok 配置。`ocx start` 使用这些保留的配置恢复服务,不会重新注入路由。要让 Codex 回到自己的账户,请运行 `ocx disconnect`;若已恢复为原生路由,要重新应用连接路由,请运行 `ocx sync --restart-codex`。

‎docs-site/src/content/docs/zh-tw/reference/cli/lifecycle.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,8 @@ ocx start --socks5-off
2828

2929
### `ocx stop`
3030

31+
無人監督的 Link Child 處理結束訊號時,會在每次寫入前核對連線,並在關閉接聽器前還原 Codex 原生設定及受管理的 Grok。服務/Desktop、sibling、重新啟動交接和父程序 stop 收據會保留設定。結束中的重新啟動要求回傳 `409 runtime_stopping`。強制終止可能略過訊號處理,仍需父程序 `ocx stop` 的還原路徑。
32+
3133
停止執行中的代理(依 PID)、移除 PID 檔案,並還原原生 Codex。若已安裝受管背景服務,`ocx stop` 也會先停止它,使其無法重新生成代理。網頁儀表板的 **Stop** 按鈕在多數後端執行相同動作(`POST /api/stop`),但 Windows 工作排程器除外:工作結束後包裝程序仍可能重新啟動 Proxy,因此儀表板會以 `respawnable_service` 拒絕、不做任何變更,並請你改用 `ocx stop`。
3234

3335
對已連線的 hub 用戶端,`ocx stop`(包括成功的 API 停止)會保留連線擁有的 Codex 路由、目錄和 Grok 設定,`ocx start` 會再次提供服務。明確停止 Remote Link Child 時,若共用設定還原成功,則會還原原生 Codex 路由、目錄與已備份的續接歷程中繼資料,並移除受管理的 Grok 設定。已儲存的 Home 連線會保留,可用 `ocx disconnect` 移除。

‎scripts/test-layout/layout-clients.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,6 +152,7 @@
152152
"client-link-connect.test.ts": "clients",
153153
"client-link-relay.test.ts": "clients",
154154
"client-link-runtime.test.ts": "clients",
155+
"client-link-stop.test.ts": "clients",
155156
"link-routes.test.ts": "clients",
156157
"client-link-state.test.ts": "clients",
157158
"client-link-status.test.ts": "clients",

‎src/cli/index.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1139,7 +1139,9 @@ async function handleStopUnlocked(snapshot?: GuardedStopSnapshot) {
11391139
.filter(read => isPendingTeardownAbandoned(read, teardownOwnerStillRunning));
11401140
let teardownNonce: string | undefined;
11411141
// #7423: an update that restarts the proxy asks this stop to leave Codex routing for the replacement.
1142-
const handoverRequested = updateTeardownHandoverRequested(process.env, () => shouldSyncCodexOnStart(loadConfig())) && !stoppingSibling && !connectedClientSkip;
1142+
// Client start never discharges a standalone update-handover receipt or reapplies routing.
1143+
const handoverRequested = updateTeardownHandoverRequested(process.env, () => shouldSyncCodexOnStart(loadConfig()))
1144+
&& !stoppingSibling && readClientConnectionState().kind !== "connected";
11431145
let deferralHonoredByProxy = false;
11441146
const claimTeardown = (endpoint: { hostname: string; port: number }, endpointSource: "exact" | "guessed") => {
11451147
if (teardownNonce || stoppingSibling) return;

0 commit comments

Comments
 (0)