Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion cli/serve/desktop.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,9 @@ func (desktopServeCmd) Run(parent context.Context, run *command.Context, args []
return err
}
}
if err := ensureServeBootstrapState(ctx, configPath, false); err != nil {
// Bootstrap only local state before the renderer can connect. The serving
// manager still detects providers after the listeners are ready.
if err := ensureServeBootstrapState(ctx, configPath, true); err != nil {
return err
}
cfg, err := loadConfig(configPath)
Expand Down
5 changes: 4 additions & 1 deletion cli/serve/serve.go
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,10 @@ func startServerWithConfigPath(ctx context.Context, run *command.Context, cfg co
}
restoreAuthDetect := applyNoAuthDetectEnv(serveOpts.NoAuthDetect)
defer restoreAuthDetect()
_ = EnsureCLIProxy(ctx)
// The desktop can serve local state before any provider needs CLIProxy.
if serveOpts.Distribution != "electron" {
_ = EnsureCLIProxy(ctx)
}
defer func() {
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
Expand Down
27 changes: 27 additions & 0 deletions cli/serve/serve_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1135,6 +1135,33 @@ func TestServeForegroundReportsListeningBeforeStartingAgents(t *testing.T) {
}
}

func TestServeForegroundDesktopDoesNotWarmCLIProxyBeforeListening(t *testing.T) {
restore := stubServeDependencies(t)
defer restore()

EnsureCLIProxy = func(context.Context) error {
t.Error("desktop startup should leave CLIProxy initialization to its callers")
return nil
}
listening := false
RunServer = func(opts server.Options) error {
opts.OnListening()
return nil
}
err := serveForegroundWithConfigPath(t.Context(), testContext(), config.Config{
Server: config.ServerConfig{ListenAddr: "127.0.0.1:18080"},
}, "", "", serveOptions{
Distribution: "electron",
OnListening: func() { listening = true },
})
if err != nil {
t.Fatal(err)
}
if !listening {
t.Fatal("desktop listener was not reported ready")
}
}

func TestServeForegroundRestoresConfiguredAgentsDuringManagerStartup(t *testing.T) {
restore := stubServeDependencies(t)
defer restore()
Expand Down
44 changes: 33 additions & 11 deletions internal/agentengine/agents/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@ const (
)

const agentListRuntimeProbeConcurrency = 4
const configuredHostAgentStartupConcurrency = 4

const stopRunningSandboxAgentsConcurrency = 4

Expand Down Expand Up @@ -2067,30 +2068,51 @@ func (s *Controller) StartConfiguredAgents(ctx context.Context) (startErr error)
slog.InfoContext(ctx, "configured worker startup finished", "candidates", len(agents),
"success", startErr == nil, "total_ms", time.Since(started).Milliseconds())
}()
startErrors := make([]error, len(agents))
startAgent := func(index int, live Agent) {
if _, err := s.Start(ctx, live.ID); err != nil {
startErrors[index] = fmt.Errorf("%s: %w", live.Name, err)
}
}
var hostStarts sync.WaitGroup
hostSlots := make(chan struct{}, configuredHostAgentStartupConcurrency)
runningGateways := make([]Agent, 0, len(agents))
for _, a := range agents {
if err := ctx.Err(); err != nil {
return err
for index, a := range agents {
if ctx.Err() != nil {
break
}
live := s.hydrateAgentStatus(ctx, a)
if isHostRuntimeKind(live.RuntimeKind) {
if !shouldRestoreConfiguredHostRuntime(live) {
if isHostRuntimeKind(a.RuntimeKind) {
select {
case hostSlots <- struct{}{}:
case <-ctx.Done():
continue
}
} else if isRuntimeRunning(live) {
runningGateways = append(runningGateways, live)
hostStarts.Go(func() {
defer func() { <-hostSlots }()
live := s.hydrateAgentStatus(ctx, a)
if shouldRestoreConfiguredHostRuntime(live) {
startAgent(index, live)
}
})
continue
}
if _, err := s.Start(ctx, live.ID); err != nil {
startErr = errors.Join(startErr, fmt.Errorf("%s: %w", live.Name, err))
live := s.hydrateAgentStatus(ctx, a)
if isRuntimeRunning(live) {
runningGateways = append(runningGateways, live)
continue
}
startAgent(index, live)
}
hostStarts.Wait()
if err := ctx.Err(); err != nil {
return err
}
// Readiness observations are intentionally not persisted. Prime the running
// gateway workers after a process restart so an already-dead gateway does
// not look healthy until a user opens its detail endpoint. Each probe has a
// deadline while the startup marker keeps the roster fresh.
s.primeUnknownGatewayRuntimeAvailability(ctx, runningGateways)
return startErr
return errors.Join(startErrors...)
}

// StopRunningSandboxAgents stops every registered sandbox agent whose runtime
Expand Down
67 changes: 67 additions & 0 deletions internal/agentengine/agents/controller_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7636,6 +7636,73 @@ func TestStartConfiguredAgentsRestoresRunningCodexWorker(t *testing.T) {
}
}

func TestStartConfiguredAgentsRestoresHealthyWorkerWhileAnotherStarts(t *testing.T) {
t.Setenv("HOME", t.TempDir())
slowStarted := make(chan struct{})
releaseSlow := make(chan struct{})
fastStarted := make(chan struct{})
rt := fakeAgentRuntime{
kind: RuntimeKindCodex,
start: func(ctx context.Context, h agentruntime.Handle) (agentruntime.State, error) {
if h.RuntimeID == runtimeIDForAgentID("agent-slow") {
close(slowStarted)
select {
case <-releaseSlow:
case <-ctx.Done():
return agentruntime.StateStopped, ctx.Err()
}
} else if h.RuntimeID == runtimeIDForAgentID("agent-fast") {
close(fastStarted)
} else {
return agentruntime.StateStopped, fmt.Errorf("unexpected runtime %s", h.RuntimeID)
}
return agentruntime.StateRunning, nil
},
info: func(_ context.Context, h agentruntime.Handle) (agentruntime.Info, error) {
return agentruntime.Info{HandleID: h.HandleID, State: agentruntime.StateRunning}, nil
},
}
svc, err := NewController(testModelConfig(), config.ServerConfig{}, "", "", WithRuntime(rt))
if err != nil {
t.Fatal(err)
}
for index, name := range []string{"slow", "fast"} {
id := "agent-" + name
svc.agents[id] = Agent{
ID: id, Name: name, Role: RoleWorker,
RuntimeKind: RuntimeKindCodex, RuntimeID: runtimeIDForAgentID(id), BoxID: "sess-" + name,
Status: string(agentruntime.StateRunning), CreatedAt: time.Unix(int64(index), 0),
AgentProfile: AgentProfile{Name: name, Provider: ProviderCodex, ModelID: "gpt-5.5", ProfileComplete: true},
ProfileComplete: true,
}
}

ctx, cancel := context.WithTimeout(t.Context(), 3*time.Second)
defer cancel()
done := make(chan error, 1)
go func() { done <- svc.StartConfiguredAgents(ctx) }()
select {
case <-slowStarted:
case err := <-done:
t.Fatalf("worker restoration returned before starting the first worker: %v", err)
case <-ctx.Done():
<-done
t.Fatal("the first worker did not begin restoring")
}
select {
case <-fastStarted:
case err := <-done:
t.Fatalf("worker restoration returned before starting the healthy worker: %v", err)
case <-ctx.Done():
<-done
t.Fatal("the healthy worker waited for the slow worker")
}
close(releaseSlow)
if err := <-done; err != nil {
t.Fatal(err)
}
}

func TestStartConfiguredAgentsRestoresDesiredRunningDSHWorker(t *testing.T) {
t.Setenv("HOME", t.TempDir())
startCalls := 0
Expand Down
14 changes: 10 additions & 4 deletions internal/cliproxy/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ const (
noBrowserEnv = "CSGCLAW_CLIPROXY_NO_BROWSER"
disableKeychainEnv = "CSGCLAW_CLIPROXY_DISABLE_KEYCHAIN"

authProviderClaude = "claude"
authProviderClaude = "claude"
automaticKeychainImportTimeout = 3 * time.Second
)

type AuthStatus struct {
Expand Down Expand Up @@ -202,9 +203,11 @@ func importExistingAuth(ctx context.Context, authDir string) {
if !autoAuthImportEnabled() {
return
}
for _, provider := range []string{ProviderCodex, authProviderClaude} {
_, _ = importExternalAuth(ctx, authDir, provider)
}
_, _ = importExternalAuth(ctx, authDir, ProviderCodex)
// Opportunistic startup import must yield if Keychain is waiting for access.
probeCtx, cancel := context.WithTimeout(ctx, automaticKeychainImportTimeout)
defer cancel()
_, _ = importExternalAuth(probeCtx, authDir, authProviderClaude)
}

func importExternalAuth(ctx context.Context, authDir, provider string) (authImportResult, error) {
Expand Down Expand Up @@ -252,6 +255,9 @@ func importClaudeKeychainAuth(ctx context.Context, authDir string) (authImportRe
return authImportResult{message: "Claude Keychain probing is disabled. Run csgclaw model auth login claude-code."}, nil
}
for _, candidate := range claudeKeychainCandidates {
if err := ctx.Err(); err != nil {
return authImportResult{}, err
}
raw, err := claudeKeychainReader(ctx, candidate.service, candidate.account)
if err != nil || len(strings.TrimSpace(string(raw))) == 0 {
continue
Expand Down
23 changes: 23 additions & 0 deletions internal/cliproxy/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -539,6 +539,29 @@ func TestImportExistingAuthRefreshesClaudeKeychainWhenExisting(t *testing.T) {
}
}

func TestAutomaticKeychainImportUsesOneDeadline(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("CODEX_HOME", t.TempDir())
t.Setenv(autoLoginEnv, "true")
t.Setenv(disableKeychainEnv, "false")
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
calls := 0
defer stubKeychain(t, func(probeCtx context.Context, _, _ string) ([]byte, error) {
calls++
if _, ok := probeCtx.Deadline(); !ok {
t.Error("automatic Keychain import has no deadline")
}
cancel()
return nil, probeCtx.Err()
})()

importExistingAuth(ctx, t.TempDir())
if calls != 1 {
t.Fatalf("Keychain probes after cancellation = %d, want 1 total", calls)
}
}

func testJWT(t *testing.T, claims string) string {
t.Helper()
return "e30." + base64.RawURLEncoding.EncodeToString([]byte(claims)) + ".sig"
Expand Down
Loading