From 1e886faa41934cb2eb576f67a72de392e9424a6f Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 5 Nov 2026 15:49:44 +0000 Subject: [PATCH] Complete the Codex host initialization handshake once --- docs/chat-backends.md | 3 +- .../codex-pending-interactions-restart.md | 6 +++ internal/codex/hosted_test.go | 9 +++- internal/codexhost/host.go | 5 +++ internal/codexhost/host_test.go | 45 ++++++++++++++++--- internal/codexhost/process_test.go | 3 ++ 6 files changed, 62 insertions(+), 9 deletions(-) diff --git a/docs/chat-backends.md b/docs/chat-backends.md index 912354e1..0ddb2008 100644 --- a/docs/chat-backends.md +++ b/docs/chat-backends.md @@ -82,7 +82,8 @@ changes Codex settings. Helpers are scoped by database path and upstream socket, with mode-0600 Unix sockets and singleton locks under the mode-0700 directory `/pipelines/codex-hosts//`. -On reconnect the helper returns its cached initialization handshake and replays +The helper completes upstream initialize -> initialized exactly once before +accepting clients. On reconnect it returns the cached initialization result and replays only unanswered server requests, preserving exact callback IDs and parameters. Responses and `serverRequest/resolved` remove pending entries. Old/new client RPC IDs are remapped so a delayed response for an old Pipelines process cannot answer diff --git a/docs/notes/codex-pending-interactions-restart.md b/docs/notes/codex-pending-interactions-restart.md index 53c90e93..bf462993 100644 --- a/docs/notes/codex-pending-interactions-restart.md +++ b/docs/notes/codex-pending-interactions-restart.md @@ -47,3 +47,9 @@ The initial deployment cannot rescue callbacks already owned by the old direct connection; pending interactions must settle before that first replacement. A helper crash, upstream App Server restart, or expiry breaks callback identity and remains an explicit limitation. No disk reconstruction is claimed. + +Handshake follow-up: the bridge now sends the upstream `initialized` notification +once after a successful initialize response and before declaring readiness. +Downstream initialized notifications remain suppressed on every attach. A real +socket fixture verifies initialize -> initialized ordering and exactly one of +each across client replacement, and the adapter integration checks both counts. diff --git a/internal/codex/hosted_test.go b/internal/codex/hosted_test.go index 849c0851..05e4388d 100644 --- a/internal/codex/hosted_test.go +++ b/internal/codex/hosted_test.go @@ -39,6 +39,7 @@ func TestHostedDetachRetainsAnswerableInteractions(t *testing.T) { var mu sync.Mutex var upstream *websocket.Conn var initialized atomic.Int32 + var handshakeCompleted atomic.Int32 responses := make(chan rpcMessage, 8) readyUpstream := make(chan struct{}) server := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -63,6 +64,10 @@ func TestHostedDetachRetainsAnswerableInteractions(t *testing.T) { if msg.Method == "initialize" { initialized.Add(1) } + if msg.Method == "initialized" { + handshakeCompleted.Add(1) + continue + } mu.Lock() err = wsjson.Write(ctx, conn, map[string]any{"id": msg.ID, "result": map[string]any{}}) mu.Unlock() @@ -161,8 +166,8 @@ func TestHostedDetachRetainsAnswerableInteractions(t *testing.T) { if !seen["7"] || !seen["8"] { t.Fatalf("callback identities changed: %+v", seen) } - if initialized.Load() != 1 { - t.Fatalf("upstream initialized %d times", initialized.Load()) + if initialized.Load() != 1 || handshakeCompleted.Load() != 1 { + t.Fatalf("upstream handshake counts: initialize=%d initialized=%d", initialized.Load(), handshakeCompleted.Load()) } if err := after.Answer(ctx, protocol.ChatAnswerRequest{SessionID: "thread-a", FormID: "question", Answers: map[string]any{"q": "no"}}); err == nil { t.Fatal("question was answered twice") diff --git a/internal/codexhost/host.go b/internal/codexhost/host.go index e38e66ec..f2b031b2 100644 --- a/internal/codexhost/host.go +++ b/internal/codexhost/host.go @@ -117,6 +117,11 @@ func Serve(ctx context.Context, options Options) error { if failure := h.initialize["error"]; len(failure) > 0 && string(failure) != "null" { return errors.New("Codex App Server refused initialization") } + // Complete the upstream handshake once before accepting Pipelines clients. + // Reattached clients only initialize their downstream connection. + if err := h.write(upstream, message{"method": json.RawMessage(`"initialized"`)}); err != nil { + return fmt.Errorf("complete Codex App Server initialization: %w", err) + } server := &http.Server{Handler: http.HandlerFunc(h.accept), ReadHeaderTimeout: 5 * time.Second} defer server.Close() go func() { <-child.Done(); _ = server.Close() }() diff --git a/internal/codexhost/host_test.go b/internal/codexhost/host_test.go index 661b4328..daf89895 100644 --- a/internal/codexhost/host_test.go +++ b/internal/codexhost/host_test.go @@ -15,11 +15,12 @@ import ( ) type fakeServer struct { - ctx context.Context - conn *websocket.Conn - mu sync.Mutex - received chan message - ready chan struct{} + ctx context.Context + conn *websocket.Conn + mu sync.Mutex + received chan message + handshakes chan string + ready chan struct{} } func testHost(t *testing.T) (*fakeServer, string, context.CancelFunc, <-chan error) { @@ -31,7 +32,7 @@ func testHost(t *testing.T) (*fakeServer, string, context.CancelFunc, <-chan err t.Cleanup(func() { os.RemoveAll(dir) }) ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) - fake := &fakeServer{ctx: ctx, received: make(chan message, 64), ready: make(chan struct{})} + fake := &fakeServer{ctx: ctx, received: make(chan message, 64), handshakes: make(chan string, 8), ready: make(chan struct{})} listener, err := net.Listen("unix", filepath.Join(dir, "upstream.sock")) if err != nil { t.Fatal(err) @@ -58,7 +59,10 @@ func testHost(t *testing.T) (*fakeServer, string, context.CancelFunc, <-chan err var method string _ = json.Unmarshal(msg["method"], &method) if method == "initialize" { + fake.handshakes <- method fake.send(t, message{"id": msg["id"], "result": json.RawMessage(`{"userAgent":"fixture"}`)}) + } else if method == "initialized" { + fake.handshakes <- method } else { select { case fake.received <- msg: @@ -239,3 +243,32 @@ func TestResolvedNotificationClearsOnlyMatchingThread(t *testing.T) { t.Fatalf("resolved callback replayed: %s", got) } } + +func TestBridgeCompletesUpstreamHandshakeExactlyOnce(t *testing.T) { + fake, socket, _, _ := testHost(t) + first := attach(t, socket) + writeClient(t, first, `{"method":"initialized"}`) + writeClient(t, first, `{"method":"initialized"}`) + first.CloseNow() + second := attach(t, socket) + writeClient(t, second, `{"method":"initialized"}`) + writeClient(t, second, `{"id":2,"method":"barrier"}`) + if got := fake.next(t); method(got) != "barrier" { + t.Fatalf("unexpected upstream call: %s", got) + } + for _, want := range []string{"initialize", "initialized"} { + select { + case got := <-fake.handshakes: + if got != want { + t.Fatalf("handshake order: got %s, want %s", got, want) + } + case <-time.After(time.Second): + t.Fatalf("missing upstream %s", want) + } + } + select { + case got := <-fake.handshakes: + t.Fatalf("upstream handshake repeated after downstream reconnect: %s", got) + default: + } +} diff --git a/internal/codexhost/process_test.go b/internal/codexhost/process_test.go index e9647bb8..d0a792ac 100644 --- a/internal/codexhost/process_test.go +++ b/internal/codexhost/process_test.go @@ -54,6 +54,9 @@ func TestEnsureSpawnsReusableDetachedHost(t *testing.T) { if wsjson.Read(ctx, conn, &msg) != nil { return } + if method(msg) == "initialized" { + continue + } if err := wsjson.Write(ctx, conn, message{"id": msg["id"], "result": json.RawMessage(`{}`)}); err != nil { return }