From e228ea8ebddc395d5c1ddbd88b43086ca0c23288 Mon Sep 17 00:00:00 2001 From: ayattara Date: Wed, 26 Aug 2026 16:18:38 +0000 Subject: [PATCH] fix(settings): preserve profile capability events --- .../agent/settings/handlers/handlers.go | 24 ++++-- .../handlers/profile_crud_handlers_test.go | 32 +++++++ apps/web/lib/types/backend.ts | 2 + apps/web/lib/ws/handlers/agents.test.ts | 15 ++++ apps/web/lib/ws/handlers/agents.ts | 85 +++++++++++++------ 5 files changed, 124 insertions(+), 34 deletions(-) diff --git a/apps/backend/internal/agent/settings/handlers/handlers.go b/apps/backend/internal/agent/settings/handlers/handlers.go index 193eff4cc1..f91a20d436 100644 --- a/apps/backend/internal/agent/settings/handlers/handlers.go +++ b/apps/backend/internal/agent/settings/handlers/handlers.go @@ -621,7 +621,7 @@ func (h *Handlers) httpCreateProfile(c *gin.Context) { c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create profile"}) return } - h.broadcastProfileEvent(ws.ActionAgentProfileCreated, resp) + h.broadcastProfileEvent(c.Request.Context(), ws.ActionAgentProfileCreated, resp) c.JSON(http.StatusOK, resp) } @@ -704,7 +704,7 @@ func (h *Handlers) httpUpdateProfile(c *gin.Context) { c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to update profile"}) return } - h.broadcastProfileEvent(ws.ActionAgentProfileUpdated, resp) + h.broadcastProfileEvent(c.Request.Context(), ws.ActionAgentProfileUpdated, resp) c.JSON(http.StatusOK, resp) } @@ -734,7 +734,7 @@ func (h *Handlers) httpDuplicateProfile(c *gin.Context) { c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to duplicate profile"}) return } - h.broadcastProfileEvent(ws.ActionAgentProfileCreated, resp) + h.broadcastProfileEvent(c.Request.Context(), ws.ActionAgentProfileCreated, resp) c.JSON(http.StatusOK, resp) } @@ -746,12 +746,24 @@ func (h *Handlers) httpDuplicateProfile(c *gin.Context) { // filterGlobalProfiles, and the WS path must not contradict that. When the // hub does not support workspace routing (test fakes), the office event is // dropped fail-closed. -func (h *Handlers) broadcastProfileEvent(action string, profile *dto.AgentProfileDTO) { +func (h *Handlers) broadcastProfileEvent(ctx context.Context, action string, profile *dto.AgentProfileDTO) { if h.hub == nil { return } + // Profile events can arrive before settings-agent hydration. Include the + // capability needed by sessionless pickers so they need not guess. + inferenceCapable := false + if action != ws.ActionAgentProfileDeleted { + agent, err := h.controller.GetAgent(ctx, profile.AgentID) + if err != nil { + h.logger.Warn("failed to load agent capability for profile event", zap.Error(err)) + } else { + inferenceCapable = agent.InferenceCapable + } + } notification, _ := ws.NewNotification(action, gin.H{ - "profile": profile, + "profile": profile, + "inference_capable": inferenceCapable, }) if profile.WorkspaceID != "" { if workspaceHub, ok := h.hub.(interface { @@ -789,7 +801,7 @@ func (h *Handlers) httpDeleteProfile(c *gin.Context) { c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete profile"}) return } - h.broadcastProfileEvent(ws.ActionAgentProfileDeleted, profile) + h.broadcastProfileEvent(c.Request.Context(), ws.ActionAgentProfileDeleted, profile) c.JSON(http.StatusOK, gin.H{"success": true}) } diff --git a/apps/backend/internal/agent/settings/handlers/profile_crud_handlers_test.go b/apps/backend/internal/agent/settings/handlers/profile_crud_handlers_test.go index 38065cdd42..3d4b77a03e 100644 --- a/apps/backend/internal/agent/settings/handlers/profile_crud_handlers_test.go +++ b/apps/backend/internal/agent/settings/handlers/profile_crud_handlers_test.go @@ -8,6 +8,7 @@ import ( "reflect" "testing" + "github.com/kandev/kandev/internal/agent/agents" "github.com/kandev/kandev/internal/agent/settings/controller" "github.com/kandev/kandev/internal/agent/settings/dto" ws "github.com/kandev/kandev/pkg/websocket" @@ -97,6 +98,37 @@ func TestCreateProfileEndpoint(t *testing.T) { } }) + t.Run("broadcast includes the owning agent's inference capability", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedAgent(repo, "agent-1", "profile-agent", false) + hub := &duplicateHub{} + router, _, reg := newSettingsHarness(t, repo, hub) + inferenceAgent := agents.NewMockAgentWithID("profile-agent", "profile-agent", "Profile Agent") + inferenceAgent.SetEnabled(true) + if err := reg.Register(inferenceAgent); err != nil { + t.Fatalf("register inference agent: %v", err) + } + + response := doSettingsRequest(router, http.MethodPost, "/api/v1/agents/agent-1/profiles", + `{"name":"Fast","model":"model-x"}`) + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + payloads := hub.payloads(ws.ActionAgentProfileCreated) + if len(payloads) != 1 { + t.Fatalf("recorded %d profile-created broadcasts, want 1", len(payloads)) + } + var envelope struct { + InferenceCapable bool `json:"inference_capable"` + } + if err := json.Unmarshal(payloads[0], &envelope); err != nil { + t.Fatalf("decode profile-created payload: %v", err) + } + if !envelope.InferenceCapable { + t.Fatal("profile-created capability = false, want true for mock-agent") + } + }) + t.Run("rejections keep their specific message and write nothing", func(t *testing.T) { cases := []struct { name string diff --git a/apps/web/lib/types/backend.ts b/apps/web/lib/types/backend.ts index 991547dcb8..594f59114c 100644 --- a/apps/web/lib/types/backend.ts +++ b/apps/web/lib/types/backend.ts @@ -317,6 +317,8 @@ export type AgentProfileDeletedPayload = { export type AgentProfileChangedPayload = { profile: AgentProfilePayload; + /** Sessionless-inference capability for profile events received before agent hydration. */ + inference_capable?: boolean; }; export type UserSettingsUpdatedPayload = Omit< diff --git a/apps/web/lib/ws/handlers/agents.test.ts b/apps/web/lib/ws/handlers/agents.test.ts index b081d3ecc1..48b3b57095 100644 --- a/apps/web/lib/ws/handlers/agents.test.ts +++ b/apps/web/lib/ws/handlers/agents.test.ts @@ -188,6 +188,21 @@ describe("agent profile events", () => { expect(stored?.model).toBe("new-model"); }); + it("preserves event capability before the owning settings agent is hydrated", () => { + const store = makeStore(); + const handlers = handlersFor(store); + + handlers[PROFILE_CREATED]( + message(PROFILE_CREATED, { + profile: profilePayload(), + inference_capable: true, + }), + ); + + expect(store.getState().settingsAgents.items).toHaveLength(0); + expect(store.getState().agentProfiles.items[0]?.inference_capable).toBe(true); + }); + it("does not resurrect a deleted profile from a delayed create event", () => { const store = makeStore(); const handlers = handlersFor(store); diff --git a/apps/web/lib/ws/handlers/agents.ts b/apps/web/lib/ws/handlers/agents.ts index faffce87a4..3888124136 100644 --- a/apps/web/lib/ws/handlers/agents.ts +++ b/apps/web/lib/ws/handlers/agents.ts @@ -1,6 +1,7 @@ import type { StoreApi } from "zustand"; import type { AppState } from "@/lib/state/store"; import type { WsHandlers } from "@/lib/ws/handlers/types"; +import type { BackendMessageMap } from "@/lib/types/backend"; import { compareTimestamps, isStaleAvailableAgentsSnapshot, @@ -21,6 +22,26 @@ function getAgentId(raw: unknown): string { return typeof value === "string" ? value : ""; } +function getInferenceCapable(raw: unknown): boolean | undefined { + const value = (raw as { inference_capable?: unknown } | undefined)?.inference_capable; + return typeof value === "boolean" ? value : undefined; +} + +function profileEventAgent( + state: AppState, + agentID: string, + inferenceCapable: boolean | undefined, +) { + const agent = state.settingsAgents.items.find((item) => item.id === agentID); + return { + id: agentID, + name: agent?.name ?? "", + capability_status: agent?.capability_status, + capability_error: agent?.capability_error, + inference_capable: agent?.inference_capable ?? inferenceCapable, + }; +} + /** * Office-scoped profiles are owned by the office channels, never the kanban * settings surface (the HTTP agent list hides them via filterGlobalProfiles). @@ -88,20 +109,14 @@ function handleProfileCreated( state: AppState, profile: unknown, eventTimestamp: string | undefined, + inferenceCapable: boolean | undefined, ): Partial { const normalized = normalizeAgentProfile(profile); if (isOfficeScoped(normalized)) return {}; if (isStaleProfileEvent(state, normalized, eventTimestamp)) return {}; deletionTombstones.delete(normalized.id); // a genuinely newer create wins const agentId = getAgentId(profile); - const agent = state.settingsAgents.items.find((a) => a.id === agentId); - const agentStub = { - id: agentId, - name: agent?.name ?? "", - capability_status: agent?.capability_status, - capability_error: agent?.capability_error, - inference_capable: agent?.inference_capable, - }; + const agentStub = profileEventAgent(state, agentId, inferenceCapable); const nextProfiles = [ ...state.agentProfiles.items.filter((p) => p.id !== normalized.id), toAgentProfileOption(agentStub, normalized), @@ -131,19 +146,13 @@ function handleProfileUpdated( state: AppState, profile: unknown, eventTimestamp: string | undefined, + inferenceCapable: boolean | undefined, ): Partial { const normalized = normalizeAgentProfile(profile); if (isOfficeScoped(normalized)) return {}; if (isStaleProfileEvent(state, normalized, eventTimestamp)) return {}; const agentId = getAgentId(profile); - const agent = state.settingsAgents.items.find((a) => a.id === agentId); - const agentStub = { - id: agentId, - name: agent?.name ?? "", - capability_status: agent?.capability_status, - capability_error: agent?.capability_error, - inference_capable: agent?.inference_capable, - }; + const agentStub = profileEventAgent(state, agentId, inferenceCapable); const nextProfiles = state.agentProfiles.items.map((p) => p.id === normalized.id ? toAgentProfileOption(agentStub, normalized) : p, ); @@ -196,6 +205,36 @@ function handleProfileDeleted( }; } +function applyProfileCreatedEvent( + store: StoreApi, + message: BackendMessageMap["agent.profile.created"], +) { + store.setState((state) => ({ + ...state, + ...handleProfileCreated( + state, + message.payload.profile, + message.timestamp, + getInferenceCapable(message.payload), + ), + })); +} + +function applyProfileUpdatedEvent( + store: StoreApi, + message: BackendMessageMap["agent.profile.updated"], +) { + store.setState((state) => ({ + ...state, + ...handleProfileUpdated( + state, + message.payload.profile, + message.timestamp, + getInferenceCapable(message.payload), + ), + })); +} + export function registerAgentsHandlers(store: StoreApi): WsHandlers { return { "agent.available.updated": (message) => { @@ -281,18 +320,8 @@ export function registerAgentsHandlers(store: StoreApi): WsHandlers { }; }); }, - "agent.profile.created": (message) => { - store.setState((state) => ({ - ...state, - ...handleProfileCreated(state, message.payload.profile, message.timestamp), - })); - }, - "agent.profile.updated": (message) => { - store.setState((state) => ({ - ...state, - ...handleProfileUpdated(state, message.payload.profile, message.timestamp), - })); - }, + "agent.profile.created": (message) => applyProfileCreatedEvent(store, message), + "agent.profile.updated": (message) => applyProfileUpdatedEvent(store, message), "agent.profile.deleted": (message) => { store.setState((state) => ({ ...state,