feat: add agent profile duplicate (#2550)

This commit is contained in:
Clément Fiere
2026-08-12 12:19:12 +02:00
committed by GitHub
parent b4a84f8212
commit 7e207c6fd1
40 changed files with 4094 additions and 194 deletions
@@ -75,6 +75,11 @@ func (m *MockRepository) CreateAgentProfile(ctx context.Context, profile *models
return nil
}
// DuplicateAgentProfile implements the settings store interface for the resolver test fakes.
func (m *MockRepository) DuplicateAgentProfile(ctx context.Context, input store.DuplicateAgentProfileInput) error {
return nil
}
func (m *MockRepository) UpdateAgentProfile(ctx context.Context, profile *models.AgentProfile) error {
if m.updateAgentProfileFn != nil {
return m.updateAgentProfileFn(ctx, profile)
@@ -2,6 +2,8 @@ package controller
import (
"context"
"database/sql"
"errors"
"fmt"
"regexp"
"sort"
@@ -14,6 +16,7 @@ import (
"github.com/kandev/kandev/internal/agent/settings/dto"
"github.com/kandev/kandev/internal/agent/settings/models"
"github.com/kandev/kandev/internal/agent/settings/profileconfig"
"github.com/kandev/kandev/internal/agent/settings/store"
"github.com/kandev/kandev/internal/secrets"
)
@@ -254,6 +257,212 @@ func (c *Controller) UpdateProfile(ctx context.Context, req UpdateProfileRequest
return &result, nil
}
type DuplicateProfileRequest struct {
ID string
}
// DuplicateProfile creates an independent copy of an existing profile. The
// copy keeps every configuration field (model, mode, config options, CLI
// flags, env vars, launcher prefix, auto-approve flags, enabled state, MCP
// config) under a fresh row named "<source> Copy", so a user can start a
// variant from a working profile without re-entering it. Runtime state is
// intentionally not copied: the copy starts idle with no pause reason,
// last-run timestamp, or consecutive-failure count. No in-use checks apply —
// a brand-new row cannot be referenced by sessions, watchers, automations,
// or routing tiers yet.
//
// The copy is committed in one repository transaction (row + MCP config), so
// a failure leaves no partial profile and a disabled source never becomes
// briefly selectable.
//
// The source profile and MCP row are read up front, then the repository
// re-verifies those revisions inside the transaction; a concurrent writer
// between the reads and the insert aborts with a retryable error, so the
// copy always reflects one consistent snapshot of the source.
func (c *Controller) DuplicateProfile(ctx context.Context, req DuplicateProfileRequest) (*dto.AgentProfileDTO, error) {
source, err := c.repo.GetAgentProfile(ctx, req.ID)
if err != nil {
if isProfileNotFoundErr(err) {
return nil, ErrAgentProfileNotFound
}
return nil, err
}
// Office-scoped profiles are owned by the workspace-scoped office API
// surface and hidden from this instance-level settings surface (the UI
// filters them via filterGlobalProfiles). Refuse to duplicate them here so
// the endpoint cannot read or clone another workspace's configuration;
// 404 keeps the existence of office profiles hidden.
if source.WorkspaceID != "" {
return nil, ErrAgentProfileNotFound
}
for attempt := 0; ; attempt++ {
// A source without an MCP row leaves the copy without one: the
// default-config semantics and boot EnsureDefaultMcpConfig cover
// MCP-supporting agents.
var sourceMcp *models.AgentProfileMcpConfig
sourceMcp, err = c.repo.GetAgentProfileMcpConfig(ctx, source.ID)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
return nil, err
}
if errors.Is(err, sql.ErrNoRows) {
sourceMcp = nil
}
clone := duplicateClone(source)
var mcpCopy *models.AgentProfileMcpConfig
if sourceMcp != nil {
mcpCopy = &models.AgentProfileMcpConfig{
Enabled: sourceMcp.Enabled,
Servers: cloneStringInterfaceMap(sourceMcp.Servers),
Meta: cloneStringInterfaceMap(sourceMcp.Meta),
}
}
err = c.repo.DuplicateAgentProfile(ctx, store.DuplicateAgentProfileInput{
Source: source,
SourceMcp: sourceMcp,
Profile: clone,
McpConfig: mcpCopy,
})
if err == nil {
result := toProfileDTO(clone)
return &result, nil
}
// A source deleted between the snapshot read and the transaction is a
// deterministic 404, not a retryable race: the copy has nothing to
// reflect, so surface it immediately instead of re-reading the source
// up to maxDuplicateRetries times.
if errors.Is(err, store.ErrSourceProfileNotFound) {
return nil, ErrAgentProfileNotFound
}
if !isRetryableDuplicateErr(err) || attempt >= maxDuplicateRetries {
return nil, err
}
source, err = c.repo.GetAgentProfile(ctx, req.ID)
if err != nil {
if isProfileNotFoundErr(err) {
return nil, ErrAgentProfileNotFound
}
return nil, err
}
}
}
// maxDuplicateRetries bounds the number of re-attempts after a concurrent
// source change. One retry covers the common single-writer race; the cap
// prevents a hot loop under sustained concurrent edits.
const maxDuplicateRetries = 2
// isRetryableDuplicateErr reports whether a duplicate attempt failed because
// the source changed concurrently (revision mismatch or a WAL snapshot-isolation
// busy error on the write) rather than deterministically. A deleted source is
// intentionally absent: DuplicateProfile maps ErrSourceProfileNotFound to 404
// before consulting this set.
func isRetryableDuplicateErr(err error) bool {
return errors.Is(err, store.ErrProfileChanged) ||
strings.Contains(err.Error(), "database is locked") ||
strings.Contains(err.Error(), "database table is locked")
}
// duplicateClone builds the copy row from the source profile. Runtime state
// is intentionally not copied: the copy starts idle with no pause reason,
// last-run timestamp, or consecutive-failure count.
func duplicateClone(source *models.AgentProfile) *models.AgentProfile {
return &models.AgentProfile{
AgentID: source.AgentID,
Name: strings.TrimSpace(source.Name) + " Copy",
AgentDisplayName: source.AgentDisplayName,
Model: source.Model,
FallbackModel: strings.TrimSpace(source.FallbackModel),
AutoFallback: source.AutoFallback,
Mode: source.Mode,
ConfigOptions: profileconfig.SanitizeConfigOptions(cloneStringMap(source.ConfigOptions)),
AllowIndexing: source.AllowIndexing,
AutoApprove: source.AutoApprove,
CLIPassthrough: source.CLIPassthrough,
CLIFlags: cloneCLIFlags(source.CLIFlags),
EnvVars: cloneEnvVars(source.EnvVars),
CommandPrefix: source.CommandPrefix,
UserModified: true,
Enabled: source.Enabled,
WorkspaceID: source.WorkspaceID,
Role: source.Role,
Icon: source.Icon,
ReportsTo: source.ReportsTo,
SkillIDs: source.SkillIDs,
DesiredSkills: source.DesiredSkills,
MaxConcurrentSessions: source.MaxConcurrentSessions,
CooldownSec: source.CooldownSec,
SkipIdleRuns: source.SkipIdleRuns,
FailureThreshold: cloneIntPtr(source.FailureThreshold),
ExecutorPreference: source.ExecutorPreference,
BudgetMonthlyCents: source.BudgetMonthlyCents,
Settings: source.Settings,
Permissions: source.Permissions,
DangerouslySkipPermissions: source.DangerouslySkipPermissions,
CustomPrompt: source.CustomPrompt,
}
}
// isProfileNotFoundErr reports whether err means "no live profile row with
// that ID". The sqlite store surfaces it as sql.ErrNoRows from GetAgentProfile
// and as an "agent profile not found" message from the update/delete paths;
// fakes and future stores may use either shape.
func isProfileNotFoundErr(err error) bool {
return errors.Is(err, sql.ErrNoRows) || strings.Contains(err.Error(), "agent profile not found")
}
// cloneCLIFlags returns a copy of the profile's CLI flag list so the
// duplicated profile never shares slice memory with the source.
func cloneCLIFlags(in []models.CLIFlag) []models.CLIFlag {
out := make([]models.CLIFlag, len(in))
copy(out, in)
return out
}
// cloneEnvVars returns a copy of the profile's env-var list (secret
// references included) so the duplicated profile never shares slice memory
// with the source.
func cloneEnvVars(in []models.ProfileEnvVar) []models.ProfileEnvVar {
out := make([]models.ProfileEnvVar, len(in))
copy(out, in)
return out
}
// cloneStringMap returns a shallow copy of a string map, preserving nil so a
// source with no config options stays nil on the copy.
func cloneStringMap(in map[string]string) map[string]string {
if in == nil {
return nil
}
out := make(map[string]string, len(in))
for k, v := range in {
out[k] = v
}
return out
}
// cloneStringInterfaceMap returns a shallow copy of a string-keyed interface
// map (used for MCP servers/meta), preserving nil.
func cloneStringInterfaceMap(in map[string]interface{}) map[string]interface{} {
if in == nil {
return nil
}
out := make(map[string]interface{}, len(in))
for k, v := range in {
out[k] = v
}
return out
}
// cloneIntPtr returns a copy of an int pointer so the duplicated profile never
// aliases the source's field, preserving nil.
func cloneIntPtr(in *int) *int {
if in == nil {
return nil
}
v := *in
return &v
}
func (c *Controller) validateGlobalSecretRefs(ctx context.Context, envVars []dto.ProfileEnvVarDTO) error {
if c.secretStore == nil {
return nil
@@ -0,0 +1,369 @@
package controller
import (
"context"
"errors"
"testing"
"time"
"github.com/kandev/kandev/internal/agent/settings/models"
"github.com/kandev/kandev/internal/agent/settings/store"
)
// sourceProfile returns a fully-populated kanban-flavour profile so every
// copy assertion has a concrete value to compare against.
func sourceProfile() *models.AgentProfile {
failureThreshold := 4
lastRun := time.Date(2026, 8, 1, 12, 0, 0, 0, time.UTC)
return &models.AgentProfile{
ID: "source-1",
AgentID: "agent-1",
Name: "Default",
AgentDisplayName: "Claude Code",
Model: "claude-sonnet",
FallbackModel: "claude-haiku",
AutoFallback: true,
Mode: "plan",
ConfigOptions: map[string]string{"effort": "high"},
AllowIndexing: true,
AutoApprove: true,
CLIPassthrough: true,
CLIFlags: []models.CLIFlag{
{Description: "Allow all tools", Flag: "--allow-all-tools", Enabled: true},
{Description: "Custom", Flag: "--my-flag value", Enabled: false},
},
EnvVars: []models.ProfileEnvVar{
{Key: "FOO", Value: "bar"},
{Key: "TOKEN", SecretID: "sec-1"},
},
CommandPrefix: "greywall --",
UserModified: true,
Enabled: true,
// Office enrichment configuration — must be copied. WorkspaceID stays
// empty (kanban): the settings duplicate endpoint rejects office-scoped
// sources, so the copy assertions cover the enrichment fields on a
// kanban-scoped profile.
WorkspaceID: "",
Role: "worker",
Icon: "🤖",
ReportsTo: "profile-other",
SkillIDs: `["s1","s2"]`,
DesiredSkills: `["ds1"]`,
MaxConcurrentSessions: 2,
CooldownSec: 60,
SkipIdleRuns: true,
FailureThreshold: &failureThreshold,
ExecutorPreference: "exec-local",
BudgetMonthlyCents: 12500,
Settings: `{"office_theme":"dark"}`,
Permissions: `{"spawn_subagents":true}`,
// Deprecated legacy columns — still copied for fidelity so an old row's
// values survive duplication.
DangerouslySkipPermissions: true,
CustomPrompt: "legacy prompt",
// Runtime state — must NOT be copied.
Status: "working",
PauseReason: "auto-paused",
LastRunFinishedAt: &lastRun,
ConsecutiveFailures: 3,
}
}
// duplicateSetup wires a controller to a fake store pre-seeded with the source profile.
func duplicateSetup(source *models.AgentProfile) (*Controller, *fakeStore) {
ctrl := newTestController(nil)
st := newFakeStore()
st.agents[source.AgentID] = &models.Agent{ID: source.AgentID, Name: "test-agent"}
st.profiles[source.AgentID] = []*models.AgentProfile{source}
ctrl.repo = st
return ctrl, st
}
// TestDuplicateProfile_CopiesFullConfiguration verifies every configuration field (office enrichment and deprecated legacy columns included) survives duplication while runtime state is reset.
func TestDuplicateProfile_CopiesFullConfiguration(t *testing.T) {
source := sourceProfile()
ctrl, st := duplicateSetup(source)
result, err := ctrl.DuplicateProfile(context.Background(), DuplicateProfileRequest{ID: source.ID})
if err != nil {
t.Fatalf("DuplicateProfile: %v", err)
}
if result.ID == source.ID || result.ID == "" {
t.Fatalf("copy ID = %q, want a fresh non-empty ID", result.ID)
}
if result.Name != "Default Copy" {
t.Errorf("copy name = %q, want %q", result.Name, "Default Copy")
}
if result.AgentID != source.AgentID {
t.Errorf("copy agent_id = %q, want %q", result.AgentID, source.AgentID)
}
if result.AgentDisplayName != source.AgentDisplayName {
t.Errorf("copy display name = %q, want %q", result.AgentDisplayName, source.AgentDisplayName)
}
if result.Model != source.Model || result.FallbackModel != source.FallbackModel || !result.AutoFallback {
t.Errorf("copy model fields = (%q, %q, %v), want (%q, %q, true)",
result.Model, result.FallbackModel, result.AutoFallback, source.Model, source.FallbackModel)
}
if result.Mode != source.Mode {
t.Errorf("copy mode = %q, want %q", result.Mode, source.Mode)
}
if len(result.ConfigOptions) != 1 || result.ConfigOptions["effort"] != "high" {
t.Errorf("copy config options = %+v, want effort=high", result.ConfigOptions)
}
if !result.AllowIndexing || !result.AutoApprove || !result.CLIPassthrough {
t.Errorf("copy boolean config not preserved: allow_indexing=%v auto_approve=%v cli_passthrough=%v",
result.AllowIndexing, result.AutoApprove, result.CLIPassthrough)
}
if !result.UserModified {
t.Error("copy user_modified = false, want true")
}
if !result.Enabled {
t.Error("copy enabled = false, want true (source enabled)")
}
if result.CommandPrefix != "greywall --" {
t.Errorf("copy command prefix = %q, want %q", result.CommandPrefix, "greywall --")
}
if len(result.CLIFlags) != 2 ||
result.CLIFlags[0].Flag != "--allow-all-tools" || !result.CLIFlags[0].Enabled ||
result.CLIFlags[1].Flag != "--my-flag value" || result.CLIFlags[1].Enabled {
t.Errorf("copy cli flags = %+v, want both source entries with their enabled states", result.CLIFlags)
}
if len(result.EnvVars) != 2 ||
result.EnvVars[0].Key != "FOO" || result.EnvVars[0].Value != "bar" || result.EnvVars[0].SecretID != "" ||
result.EnvVars[1].Key != "TOKEN" || result.EnvVars[1].SecretID != "sec-1" {
t.Errorf("copy env vars = %+v, want both source entries incl. secret ref", result.EnvVars)
}
if len(st.created) != 1 {
t.Fatalf("stored copies = %d, want 1", len(st.created))
}
stored := st.created[0]
if stored.ID != result.ID {
t.Errorf("stored copy ID = %q, response ID = %q", stored.ID, result.ID)
}
// Office enrichment configuration copied; runtime state reset.
if stored.WorkspaceID != "" || stored.Role != "worker" || stored.Icon != "🤖" ||
stored.ReportsTo != "profile-other" || stored.SkillIDs != `["s1","s2"]` ||
stored.DesiredSkills != `["ds1"]` || stored.MaxConcurrentSessions != 2 ||
stored.CooldownSec != 60 || !stored.SkipIdleRuns ||
stored.FailureThreshold == nil || *stored.FailureThreshold != 4 ||
stored.ExecutorPreference != "exec-local" || stored.BudgetMonthlyCents != 12500 ||
stored.Settings != `{"office_theme":"dark"}` || stored.Permissions != `{"spawn_subagents":true}` {
t.Errorf("stored office enrichment not copied: %+v", stored)
}
if !stored.DangerouslySkipPermissions || stored.CustomPrompt != "legacy prompt" {
t.Errorf("deprecated legacy columns not copied: dangerously_skip_permissions=%v custom_prompt=%q",
stored.DangerouslySkipPermissions, stored.CustomPrompt)
}
if stored.Status != "" || stored.PauseReason != "" || stored.LastRunFinishedAt != nil || stored.ConsecutiveFailures != 0 {
t.Errorf("runtime state must not be copied: status=%q pause=%q last_run=%v failures=%d",
stored.Status, stored.PauseReason, stored.LastRunFinishedAt, stored.ConsecutiveFailures)
}
if stored.MigratedFrom != "" {
t.Errorf("legacy field must not be copied: migrated_from=%q", stored.MigratedFrom)
}
}
// TestDuplicateProfile_CopiesDisabledState verifies a disabled source produces a disabled copy.
func TestDuplicateProfile_CopiesDisabledState(t *testing.T) {
source := sourceProfile()
source.Enabled = false
ctrl, st := duplicateSetup(source)
result, err := ctrl.DuplicateProfile(context.Background(), DuplicateProfileRequest{ID: source.ID})
if err != nil {
t.Fatalf("DuplicateProfile: %v", err)
}
if result.Enabled {
t.Error("copy enabled = true, want false (source disabled)")
}
if len(st.created) != 1 || st.created[0].Enabled {
t.Errorf("stored copy enabled = %v, want false", st.created[0].Enabled)
}
// The disabled state must be part of the single atomic duplicate write:
// no follow-up enabled flip is allowed (a flip would create a window where
// the copy is selectable and would need a second write).
if len(st.updated) != 0 {
t.Errorf("duplicate issued %d follow-up updates, want 0 (atomic write)", len(st.updated))
}
// The response timestamps must be the ones actually stored (no stale
// insert timestamp after a separate write).
stored := st.created[0]
if !result.CreatedAt.Equal(stored.CreatedAt) || !result.UpdatedAt.Equal(stored.UpdatedAt) {
t.Errorf("response timestamps (%v/%v) differ from stored (%v/%v)",
result.CreatedAt, result.UpdatedAt, stored.CreatedAt, stored.UpdatedAt)
}
}
// TestDuplicateProfile_StoreFailureLeavesNoCopy verifies a failed transaction leaves no copy behind.
func TestDuplicateProfile_StoreFailureLeavesNoCopy(t *testing.T) {
source := sourceProfile()
ctrl, st := duplicateSetup(source)
wantErr := errors.New("boom")
st.duplicateProfErr = wantErr
_, err := ctrl.DuplicateProfile(context.Background(), DuplicateProfileRequest{ID: source.ID})
if !errors.Is(err, wantErr) {
t.Fatalf("err = %v, want %v", err, wantErr)
}
if len(st.created) != 0 || len(st.mcpConfigs) != 0 {
t.Errorf("partial copy persisted despite store error: created=%d mcp=%d",
len(st.created), len(st.mcpConfigs))
}
}
// TestDuplicateProfile_CopiesMcpConfig verifies the MCP config (enabled, servers, meta) is copied under the new profile ID.
func TestDuplicateProfile_CopiesMcpConfig(t *testing.T) {
source := sourceProfile()
ctrl, st := duplicateSetup(source)
st.mcpConfigs[source.ID] = &models.AgentProfileMcpConfig{
ProfileID: source.ID,
Enabled: true,
Servers: map[string]interface{}{
"github": map[string]interface{}{"url": "https://api.github.com", "enabled": true},
},
Meta: map[string]interface{}{"source": "user"},
}
result, err := ctrl.DuplicateProfile(context.Background(), DuplicateProfileRequest{ID: source.ID})
if err != nil {
t.Fatalf("DuplicateProfile: %v", err)
}
copied, ok := st.mcpConfigs[result.ID]
if !ok {
t.Fatalf("no mcp config row for copy %q", result.ID)
}
if !copied.Enabled {
t.Error("copied mcp config enabled = false, want true")
}
servers, ok := copied.Servers["github"].(map[string]interface{})
if !ok || servers["url"] != "https://api.github.com" || servers["enabled"] != true {
t.Errorf("copied mcp servers = %+v, want github entry preserved", copied.Servers)
}
if copied.Meta["source"] != "user" {
t.Errorf("copied mcp meta = %+v, want source=user", copied.Meta)
}
// The source row must be untouched.
if _, ok := st.mcpConfigs[source.ID]; !ok {
t.Error("source mcp config row disappeared")
}
}
// TestDuplicateProfile_NoMcpConfigLeavesCopyWithoutRow verifies a source without an MCP row leaves the copy without one.
func TestDuplicateProfile_NoMcpConfigLeavesCopyWithoutRow(t *testing.T) {
source := sourceProfile()
ctrl, st := duplicateSetup(source)
if _, err := ctrl.DuplicateProfile(context.Background(), DuplicateProfileRequest{ID: source.ID}); err != nil {
t.Fatalf("DuplicateProfile: %v", err)
}
if len(st.mcpConfigs) != 0 {
t.Errorf("copy created an mcp config row when the source had none: %+v", st.mcpConfigs)
}
}
// TestDuplicateProfile_NotFound verifies an unknown source ID maps to ErrAgentProfileNotFound.
func TestDuplicateProfile_NotFound(t *testing.T) {
ctrl, _ := duplicateSetup(sourceProfile())
_, err := ctrl.DuplicateProfile(context.Background(), DuplicateProfileRequest{ID: "missing"})
if !errors.Is(err, ErrAgentProfileNotFound) {
t.Fatalf("err = %v, want ErrAgentProfileNotFound", err)
}
}
// TestDuplicateProfile_RejectsOfficeScopedSource verifies the settings
// duplicate endpoint refuses office-scoped profiles: they are owned by the
// workspace-scoped office surface and hidden from this instance-level API, so
// duplication must fail closed (as 404, not 403, to keep their existence
// hidden) without creating a copy.
func TestDuplicateProfile_RejectsOfficeScopedSource(t *testing.T) {
source := sourceProfile()
source.WorkspaceID = "ws-1"
ctrl, st := duplicateSetup(source)
_, err := ctrl.DuplicateProfile(context.Background(), DuplicateProfileRequest{ID: source.ID})
if !errors.Is(err, ErrAgentProfileNotFound) {
t.Fatalf("err = %v, want ErrAgentProfileNotFound for an office-scoped source", err)
}
if len(st.created) != 0 {
t.Errorf("office-scoped source created %d copies, want 0", len(st.created))
}
}
// TestDuplicateProfile_NameSuffixFromEmptySourceName pins the copy name when the source name is empty.
func TestDuplicateProfile_NameSuffixFromEmptySourceName(t *testing.T) {
source := sourceProfile()
source.Name = ""
ctrl, st := duplicateSetup(source)
result, err := ctrl.DuplicateProfile(context.Background(), DuplicateProfileRequest{ID: source.ID})
if err != nil {
t.Fatalf("DuplicateProfile: %v", err)
}
if result.Name != " Copy" {
t.Errorf("copy name = %q, want %q", result.Name, " Copy")
}
_ = st
}
// TestDuplicateProfile_RetriesOnConcurrentChange verifies the controller
// re-reads the source and retries when the repository aborts the first
// attempt with ErrProfileChanged (a concurrent writer), ending with exactly
// one copy — and that the retried copy reflects the NEW source state (proving
// the fresh GetAgentProfile happened).
func TestDuplicateProfile_RetriesOnConcurrentChange(t *testing.T) {
source := sourceProfile()
ctrl, st := duplicateSetup(source)
st.duplicateChangedOnce = true
result, err := ctrl.DuplicateProfile(context.Background(), DuplicateProfileRequest{ID: source.ID})
if err != nil {
t.Fatalf("DuplicateProfile after retry: %v", err)
}
if result.ID == source.ID || result.ID == "" {
t.Fatalf("copy ID = %q, want a fresh ID", result.ID)
}
if result.Name != "Changed Name Copy" {
t.Errorf("copy name = %q, want %q (copy must be built from the re-read source)", result.Name, "Changed Name Copy")
}
if len(st.created) != 1 {
t.Fatalf("stored copies = %d, want exactly 1 after retry", len(st.created))
}
}
// TestDuplicateProfile_ExhaustsRetriesOnPersistentChange verifies the
// controller gives up (and creates nothing) when every attempt aborts with
// ErrProfileChanged.
func TestDuplicateProfile_ExhaustsRetriesOnPersistentChange(t *testing.T) {
source := sourceProfile()
ctrl, st := duplicateSetup(source)
st.duplicateProfErr = store.ErrProfileChanged
_, err := ctrl.DuplicateProfile(context.Background(), DuplicateProfileRequest{ID: source.ID})
if !errors.Is(err, store.ErrProfileChanged) {
t.Fatalf("err = %v, want ErrProfileChanged", err)
}
if len(st.created) != 0 {
t.Errorf("copy created despite persistent source changes: %d rows", len(st.created))
}
}
// TestDuplicateProfile_SourceDeletedMidFlightMapsToNotFound verifies a source
// deleted during the duplicate retries surfaces as ErrAgentProfileNotFound
// (HTTP 404) instead of the raw store error (HTTP 500).
func TestDuplicateProfile_SourceDeletedMidFlightMapsToNotFound(t *testing.T) {
source := sourceProfile()
ctrl, st := duplicateSetup(source)
st.duplicateProfErr = store.ErrSourceProfileNotFound
_, err := ctrl.DuplicateProfile(context.Background(), DuplicateProfileRequest{ID: source.ID})
if !errors.Is(err, ErrAgentProfileNotFound) {
t.Fatalf("err = %v, want ErrAgentProfileNotFound", err)
}
if len(st.created) != 0 {
t.Errorf("copy created despite deleted source: %d rows", len(st.created))
}
}
@@ -17,6 +17,7 @@ import (
"github.com/kandev/kandev/internal/agent/hostutility"
"github.com/kandev/kandev/internal/agent/registry"
"github.com/kandev/kandev/internal/agent/settings/models"
"github.com/kandev/kandev/internal/agent/settings/store"
"github.com/kandev/kandev/internal/agent/usage"
"github.com/kandev/kandev/internal/agentctl/acpcompat"
"github.com/kandev/kandev/internal/common/logger"
@@ -34,26 +35,30 @@ func (f *fakeCapReader) Get(agentType string) (hostutility.AgentCapabilities, bo
// fakeStore implements just enough of store.Repository for the reconciler.
type fakeStore struct {
agents map[string]*models.Agent // keyed by DB ID
byName map[string]*models.Agent // keyed by Name
profiles map[string][]*models.AgentProfile // keyed by DB agent ID (live)
deleted map[string][]*models.AgentProfile // keyed by DB agent ID (soft-deleted)
created []*models.AgentProfile
updated []*models.AgentProfile
softDeleted []string
nextAgentID int
nextProfID int
getByNameErr error
listAgentsErr error
listProfErr map[string]error
agents map[string]*models.Agent // keyed by DB ID
byName map[string]*models.Agent // keyed by Name
profiles map[string][]*models.AgentProfile // keyed by DB agent ID (live)
deleted map[string][]*models.AgentProfile // keyed by DB agent ID (soft-deleted)
mcpConfigs map[string]*models.AgentProfileMcpConfig // keyed by profile ID
created []*models.AgentProfile
updated []*models.AgentProfile
softDeleted []string
nextAgentID int
nextProfID int
getByNameErr error
listAgentsErr error
listProfErr map[string]error
duplicateProfErr error
duplicateChangedOnce bool
}
func newFakeStore() *fakeStore {
return &fakeStore{
agents: map[string]*models.Agent{},
byName: map[string]*models.Agent{},
profiles: map[string][]*models.AgentProfile{},
deleted: map[string][]*models.AgentProfile{},
agents: map[string]*models.Agent{},
byName: map[string]*models.Agent{},
profiles: map[string][]*models.AgentProfile{},
deleted: map[string][]*models.AgentProfile{},
mcpConfigs: map[string]*models.AgentProfileMcpConfig{},
}
}
@@ -97,10 +102,17 @@ func (f *fakeStore) ListTUIAgents(context.Context) ([]*models.Agent, error) {
return nil, nil
}
func (f *fakeStore) GetAgentProfileMcpConfig(context.Context, string) (*models.AgentProfileMcpConfig, error) {
// GetAgentProfileMcpConfig implements the settings store interface for the reconciler test fakes.
func (f *fakeStore) GetAgentProfileMcpConfig(_ context.Context, profileID string) (*models.AgentProfileMcpConfig, error) {
if cfg, ok := f.mcpConfigs[profileID]; ok {
return cfg, nil
}
return nil, nil
}
func (f *fakeStore) UpsertAgentProfileMcpConfig(context.Context, *models.AgentProfileMcpConfig) error {
// UpsertAgentProfileMcpConfig implements the settings store interface for the reconciler test fakes.
func (f *fakeStore) UpsertAgentProfileMcpConfig(_ context.Context, config *models.AgentProfileMcpConfig) error {
f.mcpConfigs[config.ProfileID] = config
return nil
}
@@ -112,6 +124,50 @@ func (f *fakeStore) CreateAgentProfile(_ context.Context, p *models.AgentProfile
return nil
}
// DuplicateAgentProfile implements the settings store interface for the reconciler test fakes.
func (f *fakeStore) DuplicateAgentProfile(_ context.Context, input store.DuplicateAgentProfileInput) error {
if f.duplicateProfErr != nil {
return f.duplicateProfErr
}
if f.duplicateChangedOnce {
f.duplicateChangedOnce = false
// Simulate a concurrent writer: the stored source row changes between
// the controller's first read and its duplicate attempt, so a retry
// must re-read the source and copy the NEW state.
input.Source.Name = "Changed Name"
input.Source.UpdatedAt = input.Source.UpdatedAt.Add(time.Second)
return store.ErrProfileChanged
}
// Version check mirrors the sqlite store: the stored source rows must
// still match the revisions the copy was built from.
if f.profiles[input.Source.AgentID] != nil {
for _, p := range f.profiles[input.Source.AgentID] {
if p.ID == input.Source.ID && !p.UpdatedAt.Equal(input.Source.UpdatedAt) {
return store.ErrProfileChanged
}
}
}
if input.SourceMcp != nil {
mcp, ok := f.mcpConfigs[input.Source.ID]
if !ok || !mcp.UpdatedAt.Equal(input.SourceMcp.UpdatedAt) {
return store.ErrProfileChanged
}
}
p := input.Profile
f.nextProfID++
p.ID = "profile-" + strconv.Itoa(f.nextProfID)
now := time.Now().UTC()
p.CreatedAt = now
p.UpdatedAt = now
f.profiles[p.AgentID] = append(f.profiles[p.AgentID], p)
f.created = append(f.created, p)
if input.McpConfig != nil {
input.McpConfig.ProfileID = p.ID
f.mcpConfigs[p.ID] = input.McpConfig
}
return nil
}
func (f *fakeStore) UpdateAgentProfile(_ context.Context, p *models.AgentProfile) error {
f.updated = append(f.updated, p)
return nil
@@ -46,6 +46,16 @@ type AgentProfileDTO struct {
UpdatedAt time.Time `json:"updated_at"`
}
// GetWorkspaceID lets struct-shaped profile payloads (e.g. the MCP event-bus
// publisher wrapping *AgentProfileDTO under "profile") be routed by the
// gateway's extractWorkspaceID without a JSON round-trip.
func (p *AgentProfileDTO) GetWorkspaceID() string {
if p == nil {
return ""
}
return p.WorkspaceID
}
// CLIFlagDTO mirrors models.CLIFlag on the wire. Each entry is one user-facing
// CLI argument on a profile; at launch time the `flag` string is shell-split
// and only entries with `enabled:true` reach the agent subprocess argv.
@@ -75,6 +75,7 @@ func (h *Handlers) registerHTTP(router *gin.Engine) {
api.GET("/agent-update/jobs/:id", h.httpGetAgentUpdateJob)
api.PATCH("/agent-profiles/:id", h.interlock, h.httpUpdateProfile)
api.DELETE("/agent-profiles/:id", h.interlock, h.httpDeleteProfile)
api.POST("/agent-profiles/:id/duplicate", h.interlock, h.httpDuplicateProfile)
api.GET("/agent-profiles/:id/mcp-config", h.httpGetProfileMcpConfig)
api.POST("/agent-profiles/:id/mcp-config", h.interlock, h.httpUpdateProfileMcpConfig)
}
@@ -544,12 +545,7 @@ func (h *Handlers) httpCreateProfile(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create profile"})
return
}
if h.hub != nil {
notification, _ := ws.NewNotification(ws.ActionAgentProfileCreated, gin.H{
"profile": resp,
})
h.hub.Broadcast(notification)
}
h.broadcastProfileEvent(ws.ActionAgentProfileCreated, resp)
c.JSON(http.StatusOK, resp)
}
@@ -614,15 +610,62 @@ func (h *Handlers) httpUpdateProfile(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to update profile"})
return
}
if h.hub != nil {
notification, _ := ws.NewNotification(ws.ActionAgentProfileUpdated, gin.H{
"profile": resp,
})
h.hub.Broadcast(notification)
}
h.broadcastProfileEvent(ws.ActionAgentProfileUpdated, resp)
c.JSON(http.StatusOK, resp)
}
// httpDuplicateProfile copies a profile's full configuration into a new row
// named "<source> copy" and returns the new profile. No request body: the
// copy name is derived server-side. The existing agent.profile.created
// notification lets every open settings surface pick the copy up live.
func (h *Handlers) httpDuplicateProfile(c *gin.Context) {
profileID := c.Param("id")
if profileID == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "profile id is required"})
return
}
resp, err := h.controller.DuplicateProfile(c.Request.Context(), controller.DuplicateProfileRequest{
ID: profileID,
})
if err != nil {
if err == controller.ErrAgentProfileNotFound {
c.JSON(http.StatusNotFound, gin.H{"error": "agent profile not found"})
return
}
h.logger.Error("failed to duplicate profile", zap.Error(err))
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to duplicate profile"})
return
}
h.broadcastProfileEvent(ws.ActionAgentProfileCreated, resp)
c.JSON(http.StatusOK, resp)
}
// broadcastProfileEvent fans a profile create/update/delete event out.
// Kanban profiles (empty WorkspaceID) go to every settings client.
// Office-scoped profiles are routed through the workspace-scoped broadcaster
// so their configuration (env vars, servers, ...) never leaks across
// workspace/user boundaries — the HTTP agent list hides them via
// 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) {
if h.hub == nil {
return
}
notification, _ := ws.NewNotification(action, gin.H{
"profile": profile,
})
if profile.WorkspaceID != "" {
if workspaceHub, ok := h.hub.(interface {
BroadcastToWorkspaceOrDrop(string, *ws.Message)
}); ok {
workspaceHub.BroadcastToWorkspaceOrDrop(profile.WorkspaceID, notification)
}
return
}
h.hub.Broadcast(notification)
}
func (h *Handlers) httpDeleteProfile(c *gin.Context) {
force := c.Query("force") == "true"
profile, err := h.controller.DeleteProfile(c.Request.Context(), c.Param("id"), force)
@@ -647,12 +690,7 @@ func (h *Handlers) httpDeleteProfile(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to delete profile"})
return
}
if h.hub != nil {
notification, _ := ws.NewNotification(ws.ActionAgentProfileDeleted, gin.H{
"profile": profile,
})
h.hub.Broadcast(notification)
}
h.broadcastProfileEvent(ws.ActionAgentProfileDeleted, profile)
c.JSON(http.StatusOK, gin.H{"success": true})
}
@@ -52,6 +52,7 @@ func TestRegisterRoutesProtectsEveryStateChangingAgentSettingsRoute(t *testing.T
{method: http.MethodPost, path: "/api/v1/agent-update/agent-1"},
{method: http.MethodPatch, path: "/api/v1/agent-profiles/profile-1"},
{method: http.MethodDelete, path: "/api/v1/agent-profiles/profile-1"},
{method: http.MethodPost, path: "/api/v1/agent-profiles/profile-1/duplicate"},
{method: http.MethodPost, path: "/api/v1/agent-profiles/profile-1/mcp-config"},
}
@@ -0,0 +1,329 @@
package handlers
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/kandev/kandev/internal/agent/settings/controller"
"github.com/kandev/kandev/internal/agent/settings/dto"
"github.com/kandev/kandev/internal/agent/settings/models"
"github.com/kandev/kandev/internal/agent/settings/store"
"github.com/kandev/kandev/internal/common/httpmw"
"github.com/kandev/kandev/internal/common/logger"
ws "github.com/kandev/kandev/pkg/websocket"
)
// duplicateRepo is a minimal store.Repository stub: the duplicate path only
// reads one profile, inserts the copy, flips enabled, and reads/writes the
// MCP config row. Everything else is a no-op.
type duplicateRepo struct {
profiles map[string]*models.AgentProfile
created []*models.AgentProfile
}
// newDuplicateRepo returns a fake repository preloaded with one kanban profile (p-1) under agent-1.
func newDuplicateRepo() *duplicateRepo {
return &duplicateRepo{profiles: map[string]*models.AgentProfile{}}
}
// GetAgentProfile implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) GetAgentProfile(_ context.Context, id string) (*models.AgentProfile, error) {
if p, ok := r.profiles[id]; ok {
return p, nil
}
return nil, fmt.Errorf("agent profile not found: %s", id)
}
// GetAgentProfileIncludingDeleted implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) GetAgentProfileIncludingDeleted(ctx context.Context, id string) (*models.AgentProfile, error) {
return r.GetAgentProfile(ctx, id)
}
// CreateAgentProfile implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) CreateAgentProfile(_ context.Context, p *models.AgentProfile) error {
if p.ID == "" {
p.ID = "duplicate-" + p.Name
}
r.profiles[p.ID] = p
r.created = append(r.created, p)
return nil
}
// DuplicateAgentProfile implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) DuplicateAgentProfile(_ context.Context, input store.DuplicateAgentProfileInput) error {
// Version check: the stored source must match the caller's snapshot.
if src, ok := r.profiles[input.Source.ID]; ok && !src.UpdatedAt.Equal(input.Source.UpdatedAt) {
return store.ErrProfileChanged
}
p := input.Profile
if p.ID == "" {
p.ID = "duplicate-" + p.Name
}
now := time.Now().UTC()
p.CreatedAt = now
p.UpdatedAt = now
r.profiles[p.ID] = p
r.created = append(r.created, p)
if input.McpConfig != nil {
input.McpConfig.ProfileID = p.ID
}
return nil
}
// UpdateAgentProfileEnabled implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) UpdateAgentProfileEnabled(_ context.Context, id string, enabled bool) (time.Time, error) {
p, ok := r.profiles[id]
if !ok {
return time.Time{}, fmt.Errorf("agent profile not found: %s", id)
}
p.Enabled = enabled
p.UpdatedAt = time.Now().UTC()
return p.UpdatedAt, nil
}
// GetAgentProfileMcpConfig implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) GetAgentProfileMcpConfig(context.Context, string) (*models.AgentProfileMcpConfig, error) {
return nil, nil
}
// UpsertAgentProfileMcpConfig implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) UpsertAgentProfileMcpConfig(context.Context, *models.AgentProfileMcpConfig) error {
return nil
}
// CreateAgent implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) CreateAgent(context.Context, *models.Agent) error { return nil }
// GetAgent implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) GetAgent(context.Context, string) (*models.Agent, error) {
return nil, nil
}
// GetAgentByName implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) GetAgentByName(context.Context, string) (*models.Agent, error) {
return nil, nil
}
// UpdateAgent implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) UpdateAgent(context.Context, *models.Agent) error { return nil }
// DeleteAgent implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) DeleteAgent(context.Context, string) error { return nil }
// ListAgents implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) ListAgents(context.Context) ([]*models.Agent, error) {
return nil, nil
}
// ListTUIAgents implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) ListTUIAgents(context.Context) ([]*models.Agent, error) {
return nil, nil
}
// UpdateAgentProfile implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) UpdateAgentProfile(context.Context, *models.AgentProfile) error {
return nil
}
// DeleteAgentProfile implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) DeleteAgentProfile(context.Context, string) error { return nil }
// ListAgentProfiles implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) ListAgentProfiles(context.Context, string) ([]*models.AgentProfile, error) {
return nil, nil
}
// HasDeletedAgentProfiles implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) HasDeletedAgentProfiles(context.Context, string) (bool, error) {
return false, nil
}
// Close implements the settings store interface for the duplicate handler tests.
func (r *duplicateRepo) Close() error { return nil }
var _ store.Repository = (*duplicateRepo)(nil)
// duplicateHub captures every WS message so tests can assert the broadcast.
type duplicateHub struct {
mu sync.Mutex
msgs []*ws.Message
}
// Broadcast records a global notification so tests can assert (non-)delivery.
func (h *duplicateHub) Broadcast(msg *ws.Message) {
h.mu.Lock()
defer h.mu.Unlock()
h.msgs = append(h.msgs, msg)
}
// actions returns the global notifications recorded by Broadcast.
func (h *duplicateHub) actions() []string {
h.mu.Lock()
defer h.mu.Unlock()
out := make([]string, 0, len(h.msgs))
for _, m := range h.msgs {
out = append(out, m.Action)
}
return out
}
// workspaceDuplicateHub models the gateway hub: global Broadcast plus the
// workspace-scoped, fail-closed BroadcastToWorkspaceOrDrop.
type workspaceDuplicateHub struct {
mu sync.Mutex
global []*ws.Message
workspaceMsgs map[string][]*ws.Message
}
// Broadcast records a global notification so tests can assert (non-)delivery.
func (h *workspaceDuplicateHub) Broadcast(msg *ws.Message) {
h.mu.Lock()
defer h.mu.Unlock()
h.global = append(h.global, msg)
}
// BroadcastToWorkspaceOrDrop records a workspace-scoped notification so tests can assert (non-)delivery.
func (h *workspaceDuplicateHub) BroadcastToWorkspaceOrDrop(workspaceID string, msg *ws.Message) {
h.mu.Lock()
defer h.mu.Unlock()
h.workspaceMsgs[workspaceID] = append(h.workspaceMsgs[workspaceID], msg)
}
// newDuplicateRouter builds a gin router with the settings handlers wired to the given repo and hub.
func newDuplicateRouter(t *testing.T, repo store.Repository, hub Broadcaster) *gin.Engine {
t.Helper()
gin.SetMode(gin.TestMode)
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"})
if err != nil {
t.Fatalf("NewLogger: %v", err)
}
ctrl := controller.NewController(repo, nil, nil, nil, log)
router := gin.New()
NewHandlers(ctrl, hub, log, "test-interlock").registerHTTP(router)
return router
}
// TestDuplicateProfileEndpoint_CopiesAndBroadcasts verifies the HTTP endpoint copies a kanban profile and broadcasts agent.profile.created.
func TestDuplicateProfileEndpoint_CopiesAndBroadcasts(t *testing.T) {
repo := newDuplicateRepo()
repo.profiles["source-1"] = &models.AgentProfile{
ID: "source-1",
AgentID: "agent-1",
Name: "Default",
AgentDisplayName: "Claude Code",
Model: "claude-sonnet",
CLIFlags: []models.CLIFlag{{Description: "Tools", Flag: "--allow-all-tools", Enabled: true}},
Enabled: true,
}
hub := &duplicateHub{}
router := newDuplicateRouter(t, repo, hub)
req := httptest.NewRequest(http.MethodPost, "/api/v1/agent-profiles/source-1/duplicate", nil)
req.Header.Set(httpmw.InterimSettingsInterlockHeader, "test-interlock")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body: %s", rec.Code, rec.Body.String())
}
var created dto.AgentProfileDTO
if err := json.Unmarshal(rec.Body.Bytes(), &created); err != nil {
t.Fatalf("decode response: %v", err)
}
if created.ID == "source-1" || created.ID == "" {
t.Errorf("response profile ID = %q, want a fresh ID", created.ID)
}
if created.Name != "Default Copy" {
t.Errorf("response name = %q, want %q", created.Name, "Default Copy")
}
if created.Model != "claude-sonnet" {
t.Errorf("response model = %q, want claude-sonnet", created.Model)
}
if len(created.CLIFlags) != 1 || created.CLIFlags[0].Flag != "--allow-all-tools" {
t.Errorf("response cli flags = %+v, want the source entry", created.CLIFlags)
}
found := false
for _, action := range hub.actions() {
if action == ws.ActionAgentProfileCreated {
found = true
}
}
if !found {
t.Errorf("no %s broadcast, got %v", ws.ActionAgentProfileCreated, hub.actions())
}
if len(repo.created) != 1 {
t.Fatalf("stored copies = %d, want 1", len(repo.created))
}
}
// TestDuplicateProfileEndpoint_NotFound verifies an unknown source ID surfaces as HTTP 404.
func TestDuplicateProfileEndpoint_NotFound(t *testing.T) {
router := newDuplicateRouter(t, newDuplicateRepo(), nil)
req := httptest.NewRequest(http.MethodPost, "/api/v1/agent-profiles/missing/duplicate", nil)
req.Header.Set(httpmw.InterimSettingsInterlockHeader, "test-interlock")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404; body: %s", rec.Code, rec.Body.String())
}
if !strings.Contains(rec.Body.String(), "agent profile not found") {
t.Errorf("body = %q, want agent profile not found message", rec.Body.String())
}
}
// TestDuplicateProfileEndpoint_RejectsOfficeScopedSource verifies the
// settings duplicate endpoint refuses office-scoped profiles fail-closed:
// the source is owned by the workspace-scoped office surface, so the request
// surfaces as 404 (existence hidden) and no event is broadcast on any channel
// (workspace-aware or global).
func TestDuplicateProfileEndpoint_RejectsOfficeScopedSource(t *testing.T) {
repo := newDuplicateRepo()
repo.profiles["source-office"] = &models.AgentProfile{
ID: "source-office",
AgentID: "agent-1",
Name: "Office Agent",
WorkspaceID: "ws-1",
Enabled: true,
}
hub := &workspaceDuplicateHub{workspaceMsgs: map[string][]*ws.Message{}}
router := newDuplicateRouter(t, repo, hub)
req := httptest.NewRequest(http.MethodPost, "/api/v1/agent-profiles/source-office/duplicate", nil)
req.Header.Set(httpmw.InterimSettingsInterlockHeader, "test-interlock")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404; body: %s", rec.Code, rec.Body.String())
}
if len(hub.global) != 0 {
t.Errorf("office duplicate leaked to the global settings broadcast: %d messages", len(hub.global))
}
if len(hub.workspaceMsgs) != 0 {
t.Errorf("office duplicate broadcast workspace-scoped messages: %v", hub.workspaceMsgs)
}
}
// TestDuplicateProfileEndpoint_RequiresInterlock verifies the duplicate route is rejected without the interlock token.
func TestDuplicateProfileEndpoint_RequiresInterlock(t *testing.T) {
router := newDuplicateRouter(t, newDuplicateRepo(), nil)
req := httptest.NewRequest(http.MethodPost, "/api/v1/agent-profiles/source-1/duplicate", nil)
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
if rec.Code != http.StatusForbidden {
t.Fatalf("status = %d, want 403 without interlock token", rec.Code)
}
}
@@ -450,6 +450,14 @@ func (r *sqliteRepository) UpsertAgentProfileMcpConfig(ctx context.Context, conf
if config.ProfileID == "" {
return fmt.Errorf("profile ID is required")
}
return r.upsertAgentProfileMcpConfig(ctx, r.db, config)
}
// upsertAgentProfileMcpConfig inserts or replaces the MCP config row for a
// profile, running against the caller-supplied execer so the duplicate can
// commit it in the same transaction as the profile row. Defaults nil maps and
// fills timestamps on the passed config in place.
func (r *sqliteRepository) upsertAgentProfileMcpConfig(ctx context.Context, execer profileExecer, config *models.AgentProfileMcpConfig) error {
if config.Servers == nil {
config.Servers = map[string]interface{}{}
}
@@ -471,7 +479,7 @@ func (r *sqliteRepository) UpsertAgentProfileMcpConfig(ctx context.Context, conf
return fmt.Errorf("failed to serialize MCP meta: %w", err)
}
_, err = r.db.ExecContext(ctx, r.db.Rebind(`
_, err = execer.ExecContext(ctx, execer.Rebind(`
INSERT INTO agent_profile_mcp_configs (profile_id, enabled, servers_json, meta_json, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?)
ON CONFLICT(profile_id) DO UPDATE SET
@@ -490,6 +498,116 @@ func (r *sqliteRepository) CreateAgentProfile(ctx context.Context, profile *mode
now := time.Now().UTC()
profile.CreatedAt = now
profile.UpdatedAt = now
// New profiles are created enabled — the DB column default is 1 and
// nothing creates a profile pre-disabled. Setting the field here keeps
// callers' in-memory copy consistent with the row.
profile.Enabled = true
return r.insertAgentProfile(ctx, r.db, profile)
}
// DuplicateAgentProfile creates an independent copy of a profile in a single
// transaction: the row is inserted with the caller-provided Enabled state (a
// duplicate of a disabled profile must not become briefly selectable) and the
// MCP config row is upserted when non-nil. A failure rolls back and leaves no
// partial copy, so retrying after an error cannot create a duplicate row.
//
// The source rows are re-read inside the transaction and must still carry the
// revisions the copy was built from; otherwise ErrProfileChanged is returned
// and nothing is created. Combined with WAL snapshot isolation (a concurrent
// commit after this transaction's first read aborts its write with a busy
// error), the copy always reflects one consistent snapshot of the source.
func (r *sqliteRepository) DuplicateAgentProfile(ctx context.Context, input DuplicateAgentProfileInput) error {
if input.Profile.ID == "" {
input.Profile.ID = uuid.New().String()
}
tx, err := r.db.BeginTxx(ctx, nil)
if err != nil {
return err
}
defer func() { _ = tx.Rollback() }()
if err := r.verifySourceSnapshot(ctx, tx, input); err != nil {
return err
}
now := time.Now().UTC()
input.Profile.CreatedAt = now
input.Profile.UpdatedAt = now
if err := r.insertAgentProfile(ctx, tx, input.Profile); err != nil {
return err
}
if input.McpConfig != nil {
input.McpConfig.ProfileID = input.Profile.ID
if err := r.upsertAgentProfileMcpConfig(ctx, tx, input.McpConfig); err != nil {
return err
}
}
return tx.Commit()
}
// verifySourceSnapshot checks, inside the duplicate transaction, that the
// source rows still match the revisions the caller built the copy from. A
// mismatch means a concurrent writer changed the source between the caller's
// read and this transaction — duplicating anyway would produce a copy mixing
// two points in time.
func (r *sqliteRepository) verifySourceSnapshot(ctx context.Context, tx *sqlx.Tx, input DuplicateAgentProfileInput) error {
var sourceUpdated time.Time
err := tx.QueryRowContext(ctx, tx.Rebind(
`SELECT updated_at FROM agent_profiles WHERE id = ? AND deleted_at IS NULL`),
input.Source.ID).Scan(&sourceUpdated)
if errors.Is(err, sql.ErrNoRows) {
return ErrSourceProfileNotFound
}
if err != nil {
return err
}
if !sourceUpdated.Equal(input.Source.UpdatedAt) {
return ErrProfileChanged
}
if input.SourceMcp == nil {
// The caller's snapshot had no MCP row: verify one was not created in
// the meantime, otherwise the copy would silently drop it. Missing is
// the unchanged case; an existing row means the snapshot is stale.
var exists int
err = tx.QueryRowContext(ctx, tx.Rebind(
`SELECT 1 FROM agent_profile_mcp_configs WHERE profile_id = ?`),
input.Source.ID).Scan(&exists)
if err == nil {
return ErrProfileChanged
}
if !errors.Is(err, sql.ErrNoRows) {
return err
}
return nil
}
var mcpUpdated time.Time
err = tx.QueryRowContext(ctx, tx.Rebind(
`SELECT updated_at FROM agent_profile_mcp_configs WHERE profile_id = ?`),
input.Source.ID).Scan(&mcpUpdated)
if errors.Is(err, sql.ErrNoRows) {
return ErrProfileChanged
}
if err != nil {
return err
}
if !mcpUpdated.Equal(input.SourceMcp.UpdatedAt) {
return ErrProfileChanged
}
return nil
}
// profileExecer is the subset of *sqlx.DB / *sqlx.Tx the shared insert and
// upsert helpers need, so one code path serves both single-statement and
// transactional writes.
type profileExecer interface {
ExecContext(ctx context.Context, query string, args ...any) (sql.Result, error)
Rebind(query string) string
}
// insertAgentProfile writes the profile row through the caller-supplied
// execer, sharing one SQL statement between CreateAgentProfile and the
// transactional duplicate path. The profile's Enabled value is written as-is.
func (r *sqliteRepository) insertAgentProfile(ctx context.Context, execer profileExecer, profile *models.AgentProfile) error {
cliFlagsJSON, err := cliFlagsToJSON(profile.CLIFlags)
if err != nil {
return err
@@ -502,11 +620,7 @@ func (r *sqliteRepository) CreateAgentProfile(ctx context.Context, profile *mode
if err != nil {
return err
}
// New profiles are created enabled — the DB column default is 1 and
// nothing creates a profile pre-disabled. Setting the field here keeps
// callers' in-memory copy consistent with the row.
profile.Enabled = true
_, err = r.db.ExecContext(ctx, r.db.Rebind(`
_, err = execer.ExecContext(ctx, execer.Rebind(`
INSERT INTO agent_profiles (
id, agent_id, name, agent_display_name, model, mode, migrated_from,
auto_approve, dangerously_skip_permissions, allow_indexing, cli_passthrough,
@@ -0,0 +1,291 @@
package store
import (
"context"
"database/sql"
"errors"
"testing"
"github.com/kandev/kandev/internal/agent/settings/models"
)
// TestDuplicateAgentProfile_RoundTrip verifies the atomic copy path: the copy
// gets a fresh ID, keeps every configuration field, preserves the source's
// disabled state (the store must NOT force a duplicate enabled like
// CreateAgentProfile does), and copies the MCP config row in the same write.
func TestDuplicateAgentProfile_RoundTrip(t *testing.T) {
repo := newFreshRepo(t)
ctx := context.Background()
if err := repo.CreateAgent(ctx, &models.Agent{Name: "test-agent", SupportsMCP: true}); err != nil {
t.Fatalf("seed agent: %v", err)
}
agent, err := repo.GetAgentByName(ctx, "test-agent")
if err != nil {
t.Fatalf("get agent: %v", err)
}
source := &models.AgentProfile{
AgentID: agent.ID,
Name: "Default",
AgentDisplayName: "Test Agent",
Model: "model-1",
Mode: "plan",
AutoApprove: true,
CLIPassthrough: true,
CLIFlags: []models.CLIFlag{{Description: "Tools", Flag: "--allow-all-tools", Enabled: true}},
EnvVars: []models.ProfileEnvVar{{Key: "FOO", Value: "bar"}},
CommandPrefix: "greywall --",
UserModified: true,
}
if err := repo.CreateAgentProfile(ctx, source); err != nil {
t.Fatalf("create source: %v", err)
}
// CreateAgentProfile forces enabled=true; simulate a user-disabled source.
// The returned timestamp is the DB revision the duplicate input must carry.
disabledAt, err := repo.UpdateAgentProfileEnabled(ctx, source.ID, false)
if err != nil {
t.Fatalf("disable source: %v", err)
}
source.UpdatedAt = disabledAt
sourceMcp := &models.AgentProfileMcpConfig{
ProfileID: source.ID,
Enabled: true,
Servers: map[string]interface{}{"github": map[string]interface{}{"url": "https://api.github.com"}},
Meta: map[string]interface{}{"k": "v"},
}
if err := repo.UpsertAgentProfileMcpConfig(ctx, sourceMcp); err != nil {
t.Fatalf("seed source mcp: %v", err)
}
clone := &models.AgentProfile{
AgentID: source.AgentID,
Name: "Default Copy",
AgentDisplayName: source.AgentDisplayName,
Model: source.Model,
Mode: source.Mode,
AutoApprove: source.AutoApprove,
CLIPassthrough: source.CLIPassthrough,
CLIFlags: source.CLIFlags,
EnvVars: source.EnvVars,
CommandPrefix: source.CommandPrefix,
Enabled: false,
UserModified: true,
}
copiedMcp := &models.AgentProfileMcpConfig{
Enabled: sourceMcp.Enabled,
Servers: sourceMcp.Servers,
Meta: sourceMcp.Meta,
}
if err := repo.DuplicateAgentProfile(ctx, DuplicateAgentProfileInput{
Source: source,
SourceMcp: sourceMcp,
Profile: clone,
McpConfig: copiedMcp,
}); err != nil {
t.Fatalf("DuplicateAgentProfile: %v", err)
}
if clone.ID == source.ID || clone.ID == "" {
t.Fatalf("copy ID = %q, want a fresh ID", clone.ID)
}
got, err := repo.GetAgentProfile(ctx, clone.ID)
if err != nil {
t.Fatalf("get copy: %v", err)
}
// The duplicate must NOT be forced enabled like CreateAgentProfile: a
// disabled source produces a disabled copy in the same write.
if got.Enabled {
t.Error("duplicate enabled = true, want false (source disabled)")
}
if got.Name != "Default Copy" || got.Model != "model-1" || got.Mode != "plan" ||
!got.AutoApprove || !got.CLIPassthrough || got.CommandPrefix != "greywall --" ||
len(got.CLIFlags) != 1 || got.CLIFlags[0].Flag != "--allow-all-tools" ||
len(got.EnvVars) != 1 || got.EnvVars[0].Key != "FOO" {
t.Errorf("copy configuration not preserved: %+v", got)
}
if !got.CreatedAt.Equal(got.UpdatedAt) {
t.Errorf("copy timestamps differ: created=%v updated=%v", got.CreatedAt, got.UpdatedAt)
}
gotMcp, err := repo.GetAgentProfileMcpConfig(ctx, clone.ID)
if err != nil {
t.Fatalf("get copy mcp config: %v", err)
}
if gotMcp == nil || !gotMcp.Enabled {
t.Fatal("copy mcp config missing or disabled")
}
servers, ok := gotMcp.Servers["github"].(map[string]interface{})
if !ok || servers["url"] != "https://api.github.com" {
t.Errorf("copy mcp servers = %+v, want github entry preserved", gotMcp.Servers)
}
if gotMcp.Meta["k"] != "v" {
t.Errorf("copy mcp meta = %+v, want k=v", gotMcp.Meta)
}
// The source row must be untouched.
srcAgain, err := repo.GetAgentProfile(ctx, source.ID)
if err != nil || srcAgain == nil || srcAgain.Enabled {
t.Errorf("source row altered by duplicate: err=%v enabled=%v", err, srcAgain.Enabled)
}
}
// TestDuplicateAgentProfile_NoMcpConfig verifies the copy is created without
// an MCP row when none is passed.
func TestDuplicateAgentProfile_NoMcpConfig(t *testing.T) {
repo := newFreshRepo(t)
ctx := context.Background()
if err := repo.CreateAgent(ctx, &models.Agent{Name: "test-agent"}); err != nil {
t.Fatalf("seed agent: %v", err)
}
agent, err := repo.GetAgentByName(ctx, "test-agent")
if err != nil {
t.Fatalf("get agent: %v", err)
}
source := &models.AgentProfile{AgentID: agent.ID, Name: "Default"}
if err := repo.CreateAgentProfile(ctx, source); err != nil {
t.Fatalf("create source: %v", err)
}
clone := &models.AgentProfile{AgentID: agent.ID, Name: "Default Copy"}
if err := repo.DuplicateAgentProfile(ctx, DuplicateAgentProfileInput{
Source: source,
Profile: clone,
}); err != nil {
t.Fatalf("DuplicateAgentProfile: %v", err)
}
if _, err := repo.GetAgentProfileMcpConfig(ctx, clone.ID); err == nil {
t.Fatal("expected no MCP row for a copy without config")
}
}
// TestDuplicateAgentProfile_DetectsConcurrentChange verifies the transaction
// aborts with ErrProfileChanged when the source row moved on since the caller
// built the copy (here: a stale revision), and creates nothing.
func TestDuplicateAgentProfile_DetectsConcurrentChange(t *testing.T) {
repo := newFreshRepo(t)
ctx := context.Background()
if err := repo.CreateAgent(ctx, &models.Agent{Name: "test-agent"}); err != nil {
t.Fatalf("seed agent: %v", err)
}
agent, err := repo.GetAgentByName(ctx, "test-agent")
if err != nil {
t.Fatalf("get agent: %v", err)
}
source := &models.AgentProfile{AgentID: agent.ID, Name: "Default"}
if err := repo.CreateAgentProfile(ctx, source); err != nil {
t.Fatalf("create source: %v", err)
}
// A concurrent writer bumps the source after the caller's snapshot.
if _, err := repo.UpdateAgentProfileEnabled(ctx, source.ID, false); err != nil {
t.Fatalf("bump source: %v", err)
}
clone := &models.AgentProfile{AgentID: agent.ID, Name: "Default Copy"}
err = repo.DuplicateAgentProfile(ctx, DuplicateAgentProfileInput{
Source: source, // stale: UpdatedAt predates the bump above
Profile: clone,
})
if !errors.Is(err, ErrProfileChanged) {
t.Fatalf("err = %v, want ErrProfileChanged", err)
}
if _, err := repo.GetAgentProfile(ctx, clone.ID); !errors.Is(err, sql.ErrNoRows) {
t.Fatalf("copy row created despite stale source: err=%v", err)
}
}
// TestDuplicateAgentProfile_DetectsMcpRowCreatedMidFlight verifies the
// transaction aborts when the caller's snapshot had NO MCP row but one was
// created before the duplicate ran — otherwise the copy would silently drop
// the newly configured servers.
func TestDuplicateAgentProfile_DetectsMcpRowCreatedMidFlight(t *testing.T) {
repo := newFreshRepo(t)
ctx := context.Background()
if err := repo.CreateAgent(ctx, &models.Agent{Name: "test-agent"}); err != nil {
t.Fatalf("seed agent: %v", err)
}
agent, err := repo.GetAgentByName(ctx, "test-agent")
if err != nil {
t.Fatalf("get agent: %v", err)
}
source := &models.AgentProfile{AgentID: agent.ID, Name: "Default"}
if err := repo.CreateAgentProfile(ctx, source); err != nil {
t.Fatalf("create source: %v", err)
}
// The caller read "no MCP row", then a concurrent writer created one.
mcp := &models.AgentProfileMcpConfig{
ProfileID: source.ID,
Enabled: true,
Servers: map[string]interface{}{"github": "x"},
}
if err := repo.UpsertAgentProfileMcpConfig(ctx, mcp); err != nil {
t.Fatalf("create source mcp: %v", err)
}
clone := &models.AgentProfile{AgentID: agent.ID, Name: "Default Copy"}
err = repo.DuplicateAgentProfile(ctx, DuplicateAgentProfileInput{
Source: source, // SourceMcp nil: snapshot predates the MCP row
Profile: clone,
})
if !errors.Is(err, ErrProfileChanged) {
t.Fatalf("err = %v, want ErrProfileChanged (MCP row created mid-flight)", err)
}
if _, err := repo.GetAgentProfile(ctx, clone.ID); !errors.Is(err, sql.ErrNoRows) {
t.Fatalf("copy row created despite new MCP row: err=%v", err)
}
}
// TestDuplicateAgentProfile_RollsBackMcpFailure verifies the transaction
// rolls back the inserted profile row when the MCP upsert fails AFTER the
// insert. A regression that commits the profile before the MCP write would
// leave a partial, selectable copy on every failed duplicate.
func TestDuplicateAgentProfile_RollsBackMcpFailure(t *testing.T) {
repo := newFreshRepo(t)
ctx := context.Background()
if err := repo.CreateAgent(ctx, &models.Agent{Name: "test-agent"}); err != nil {
t.Fatalf("seed agent: %v", err)
}
agent, err := repo.GetAgentByName(ctx, "test-agent")
if err != nil {
t.Fatalf("get agent: %v", err)
}
source := &models.AgentProfile{AgentID: agent.ID, Name: "Default"}
if err := repo.CreateAgentProfile(ctx, source); err != nil {
t.Fatalf("create source: %v", err)
}
// The source has a valid MCP row so the snapshot verification passes and
// the failure below happens during the insert-time serialization.
sourceMcp := &models.AgentProfileMcpConfig{
ProfileID: source.ID,
Enabled: true,
Servers: map[string]interface{}{"ok": "v"},
}
if err := repo.UpsertAgentProfileMcpConfig(ctx, sourceMcp); err != nil {
t.Fatalf("seed source mcp: %v", err)
}
clone := &models.AgentProfile{AgentID: agent.ID, Name: "Default Copy"}
// A channel is not JSON-serializable: the MCP upsert fails during
// serialization, which happens AFTER the profile row was inserted inside
// the transaction.
badMcp := &models.AgentProfileMcpConfig{
Enabled: true,
Servers: map[string]interface{}{"bad": make(chan int)},
}
err = repo.DuplicateAgentProfile(ctx, DuplicateAgentProfileInput{
Source: source,
SourceMcp: sourceMcp,
Profile: clone,
McpConfig: badMcp,
})
if err == nil {
t.Fatal("expected MCP serialization error, got nil")
}
if _, err := repo.GetAgentProfile(ctx, clone.ID); !errors.Is(err, sql.ErrNoRows) {
t.Fatalf("copy row survived a failed duplicate (rollback missing): err=%v", err)
}
}
@@ -2,11 +2,34 @@ package store
import (
"context"
"errors"
"time"
"github.com/kandev/kandev/internal/agent/settings/models"
)
var (
// ErrProfileChanged is returned by DuplicateAgentProfile when a source
// row changed between the caller's read and the transactional insert, so
// the copy would not reflect a consistent snapshot. Callers retry on a
// fresh read.
ErrProfileChanged = errors.New("source profile changed during duplicate")
// ErrSourceProfileNotFound is returned by DuplicateAgentProfile when the
// source profile row no longer exists (deleted mid-flight).
ErrSourceProfileNotFound = errors.New("source profile not found")
)
// DuplicateAgentProfileInput carries everything the atomic duplicate needs:
// the copy rows the caller built (Profile, McpConfig) plus the source rows
// they were built from (Source, SourceMcp) so the transaction can verify the
// copy reflects one consistent snapshot.
type DuplicateAgentProfileInput struct {
Source *models.AgentProfile
SourceMcp *models.AgentProfileMcpConfig // nil when the source has no MCP row
Profile *models.AgentProfile
McpConfig *models.AgentProfileMcpConfig // nil when SourceMcp is nil
}
type Repository interface {
CreateAgent(ctx context.Context, agent *models.Agent) error
GetAgent(ctx context.Context, id string) (*models.Agent, error)
@@ -20,6 +43,13 @@ type Repository interface {
UpsertAgentProfileMcpConfig(ctx context.Context, config *models.AgentProfileMcpConfig) error
CreateAgentProfile(ctx context.Context, profile *models.AgentProfile) error
// DuplicateAgentProfile creates an independent copy of a profile in one
// transaction: the row is inserted with the caller-provided Enabled state
// and the MCP config row is upserted when non-nil. A failure rolls back
// and leaves no partial copy. The source rows are re-read inside the
// transaction and must still match the revisions the copy was built from;
// otherwise ErrProfileChanged is returned and no row is created.
DuplicateAgentProfile(ctx context.Context, input DuplicateAgentProfileInput) error
UpdateAgentProfile(ctx context.Context, profile *models.AgentProfile) error
UpdateAgentProfileEnabled(ctx context.Context, id string, enabled bool) (time.Time, error)
DeleteAgentProfile(ctx context.Context, id string) error
@@ -11,6 +11,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/kandev/kandev/internal/agent/settings/dto"
"github.com/kandev/kandev/internal/auth/authn"
"github.com/kandev/kandev/internal/common/logger"
ws "github.com/kandev/kandev/pkg/websocket"
@@ -328,6 +329,54 @@ func TestBroadcastToWorkspaceRoutesByOwner(t *testing.T) {
waitForMessage(t, clientA)
}
// TestBroadcastToWorkspaceOrDropFailsClosed verifies office-scoped broadcasts
// are dropped when the hub cannot route by workspace.
func TestBroadcastToWorkspaceOrDropFailsClosed(t *testing.T) {
hub := newAccessTestHub(t)
hub.setAuthPolicy(AuthPolicy{
Enforced: func() bool { return true },
WorkspaceOwner: func(_ context.Context, workspaceID string) (string, error) {
if workspaceID == "ws-a" {
return "user-a", nil
}
return "", errors.New("unknown workspace")
},
})
clientA := registerAccessClient(t, hub, "a", authn.Identity{UserID: "user-a", Role: authn.RoleMember})
clientB := registerAccessClient(t, hub, "b", authn.Identity{UserID: "user-b", Role: authn.RoleMember})
notify := func(action string) *ws.Message {
msg, err := ws.NewNotification(action, map[string]interface{}{"workspace_id": "ws-a"})
if err != nil {
t.Fatal(err)
}
return msg
}
// Resolvable workspace: only the owner receives it, the foreign user
// never does.
hub.BroadcastToWorkspaceOrDrop("ws-a", notify("agent.profile.updated"))
if got := receivedActions(clientA); len(got) != 1 {
t.Fatalf("owner received %v, want 1 message", got)
}
if got := receivedActions(clientB); len(got) != 0 {
t.Fatalf("foreign user received %v, want none — WS LEAK", got)
}
// Unresolvable workspace: DROPPED under enforced auth — never the
// global fallback that BroadcastToWorkspace applies.
hub.BroadcastToWorkspaceOrDrop("ws-mystery", notify("agent.profile.updated"))
if got := receivedActions(clientB); len(got) != 0 {
t.Fatalf("unresolvable workspace leaked globally: %v", got)
}
// Empty workspace ID under enforced auth: DROPPED.
hub.BroadcastToWorkspaceOrDrop("", notify("agent.profile.updated"))
if got := receivedActions(clientB); len(got) != 0 {
t.Fatalf("empty workspace leaked globally: %v", got)
}
}
func waitForMessage(t *testing.T, client *Client) {
t.Helper()
select {
@@ -467,4 +516,18 @@ func TestExtractWorkspaceIDFieldShapes(t *testing.T) {
if got := extractWorkspaceID("not-a-map"); got != "" {
t.Fatalf("non-map payload: %q", got)
}
// Profile events wrap the profile under "profile". The wrapper is a map
// after a JSON round-trip (remote event bus) and a struct on the
// in-process bus; both must resolve the nested workspace ID so office
// profile events never fall back to the global broadcast.
if got := extractWorkspaceID(map[string]interface{}{
"profile": map[string]interface{}{"workspace_id": "ws-nested-map"},
}); got != "ws-nested-map" {
t.Fatalf("map-nested profile workspace_id: %q", got)
}
if got := extractWorkspaceID(map[string]interface{}{
"profile": &dto.AgentProfileDTO{WorkspaceID: "ws-nested-struct"},
}); got != "ws-nested-struct" {
t.Fatalf("struct-nested profile workspace_id: %q", got)
}
}
+33 -13
View File
@@ -317,6 +317,39 @@ func (h *Hub) BroadcastToWorkspace(workspaceID string, msg *ws.Message) {
h.Broadcast(msg)
return
}
h.broadcastToOwner(owner, msg)
}
// BroadcastToWorkspaceOrDrop is the fail-closed sibling of
// BroadcastToWorkspace: when per-user auth is enforced it DROPS the message
// unless the workspace is non-empty AND resolves to a known owner — it never
// falls back to a global broadcast. Every Office notification is
// workspace-scoped, so an office payload whose workspace could not be
// resolved must never cross user boundaries. With auth disabled (single
// user) it degrades to a plain global broadcast, preserving today's
// behavior.
func (h *Hub) BroadcastToWorkspaceOrDrop(workspaceID string, msg *ws.Message) {
if !h.workspaceScopeEnforced() {
h.BroadcastToWorkspace(workspaceID, msg)
return
}
if workspaceID == "" {
return // fail closed: no unattributed office fan-out under auth
}
resolver := h.authPolicy.WorkspaceOwner
if resolver == nil {
return // fail closed: cannot scope without an owner resolver
}
owner, err := resolver(h.DispatchContext(), workspaceID)
if err != nil || owner == "" {
return // fail closed: unresolvable workspace must not go global
}
h.broadcastToOwner(owner, msg)
}
// broadcastToOwner fans a message out to the clients allowed to see the
// workspace owner. Shared by the workspace-scoped broadcast paths.
func (h *Hub) broadcastToOwner(owner string, msg *ws.Message) {
data, err := json.Marshal(msg)
if err != nil {
h.logger.Error("Failed to marshal workspace broadcast", zap.Error(err))
@@ -333,19 +366,6 @@ func (h *Hub) BroadcastToWorkspace(workspaceID string, msg *ws.Message) {
h.sendToClients(data, recipients, msg.Action)
}
// BroadcastToWorkspaceOrDrop routes like BroadcastToWorkspace but, when auth is
// enforced and the workspace is unknown, DROPS the message instead of falling
// back to a global broadcast. Every Office notification is workspace-scoped, so
// an office payload whose workspace could not be resolved must never cross user
// boundaries. With auth disabled (single user) it degrades to a plain global
// broadcast, preserving today's behavior.
func (h *Hub) BroadcastToWorkspaceOrDrop(workspaceID string, msg *ws.Message) {
if workspaceID == "" && h.workspaceScopeEnforced() {
return // fail closed: no unattributed office fan-out under auth
}
h.BroadcastToWorkspace(workspaceID, msg)
}
// workspaceScopeEnforced reports whether per-user auth is currently on.
func (h *Hub) workspaceScopeEnforced() bool {
enforced := h.authPolicy.Enforced
@@ -289,6 +289,15 @@ func (b *TaskEventBroadcaster) routeBroadcast(
// GitHub PR or GitLab MR update must never cross workspace boundaries.
b.hub.BroadcastToWorkspaceOrDrop(workspaceID, msg)
return nil
case ws.ActionAgentProfileCreated, ws.ActionAgentProfileUpdated, ws.ActionAgentProfileDeleted:
// Profile payloads wrap the profile DTO under "profile"; office-scoped
// profiles (nested workspace_id) must never cross workspace
// boundaries — route them fail-closed. Kanban profiles (empty
// workspace) are instance-wide and fall through to the global path.
if workspaceID != "" {
b.hub.BroadcastToWorkspaceOrDrop(workspaceID, msg)
return nil
}
}
// Workspace-carrying events (task/workflow/repository/…) route to the
// owner's clients; events without workspace context (executors,
@@ -298,12 +307,21 @@ func (b *TaskEventBroadcaster) routeBroadcast(
}
// extractWorkspaceID pulls a workspace ID from event payloads (map- or
// struct-shaped). Empty means "no workspace context" — the event is treated
// as instance-wide and broadcast to everyone.
// struct-shaped, nested included). Profile events wrap the profile DTO under
// "profile": the wrapper may be a map (JSON round-tripped bus) or a struct
// (in-process bus, e.g. *dto.AgentProfileDTO from the MCP publisher), so the
// nested value is inspected recursively and structs expose their ID via the
// GetWorkspaceID interface. Empty means "no workspace context" — the event is
// treated as instance-wide and broadcast to everyone.
func extractWorkspaceID(data interface{}) string {
if id := extractStringField(data, "workspace_id"); id != "" {
return id
}
if profile, ok := data.(map[string]interface{}); ok {
if id := extractWorkspaceID(profile["profile"]); id != "" {
return id
}
}
if provider, ok := data.(interface{ GetWorkspaceID() string }); ok {
return provider.GetWorkspaceID()
}
+14
View File
@@ -144,6 +144,20 @@ export async function updateAgentProfileAction(
return normalizeAgentProfile(raw);
}
/**
* Duplicate a profile: the backend copies the source's full configuration
* into a new row named "<source> copy" and returns the new profile. The
* existing `agent.profile.created` WS notification also picks the copy up in
* every open settings surface.
*/
export async function duplicateAgentProfileAction(id: string): Promise<AgentProfile> {
const raw = await agentSettingsRequest<unknown>(
`${apiBaseUrl}/api/v1/agent-profiles/${id}/duplicate`,
{ method: "POST" },
);
return normalizeAgentProfile(raw);
}
import type {
ActiveSessionInfo,
AutomationReference,
@@ -0,0 +1,190 @@
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Agent, AgentProfile } from "@/lib/types/http";
import { useProfileDuplicateAction } from "./agent-profile-duplicate-action";
type ToastArgs = {
title?: string;
description?: string;
variant?: "default" | "success" | "error" | "loading";
};
const duplicateAction = vi.fn<(id: string) => Promise<AgentProfile>>();
const saveAll = vi.fn<() => Promise<{ canLeave: boolean; failedIds: Set<string> }>>();
const cancelPendingNavigation = vi.fn<() => void>();
const routerPush = vi.fn<(href: string) => void>();
const toast = vi.fn<(args: ToastArgs) => void>();
const setState = vi.fn<() => void>();
const hoisted = vi.hoisted(() => ({
coordinatorInvalidReason: undefined as string | undefined,
}));
vi.mock("@/app/actions/agents", () => ({
duplicateAgentProfileAction: (id: string) => duplicateAction(id),
}));
vi.mock("@/components/state-provider", () => ({ useAppStoreApi: () => ({ setState }) }));
vi.mock("@/components/toast-provider", () => ({ useToast: () => ({ toast }) }));
vi.mock("@/components/settings/settings-save-provider", () => ({
useSettingsSaveCoordinator: () => ({
saveAll,
invalidReason: hoisted.coordinatorInvalidReason,
cancelPendingNavigation,
}),
}));
vi.mock("@/lib/routing/client-router", () => ({ useRouter: () => ({ push: routerPush }) }));
vi.mock("@/lib/routing/navigation-guard", () => ({
runWithNavigationBlockerBypassed: (fn: () => void) => fn(),
}));
vi.mock("@/components/settings/agent-profile-page-state", () => ({
errorMessage: (error: unknown) => (error instanceof Error ? error.message : String(error)),
}));
/** Builds an Agent fixture for the duplicate-action harness. */
function agent(): Agent {
return { id: "a1", name: "mock-agent", profiles: [] } as unknown as Agent;
}
type DraftOverrides = Partial<Omit<AgentProfile, "id" | "agentId" | "name">> & {
id?: string;
agentId?: string;
name?: string;
};
/** Builds a profile draft (SettingsSaveContributor) for the duplicate-action harness. */
function draft(overrides: DraftOverrides = {}): AgentProfile {
return {
id: "p1",
agentId: "a1",
name: "Default",
agentDisplayName: "Mock",
model: "mock-fast",
allowIndexing: false,
autoApprove: false,
cliFlags: [],
cliPassthrough: false,
enabled: true,
createdAt: "",
updatedAt: "",
...overrides,
} as unknown as AgentProfile;
}
/** Renders the duplicate action with the settings save provider and navigation guard. */
function Harness({ profileDraft = draft() }: { profileDraft?: AgentProfile }) {
const { handleDuplicate, duplicating } = useProfileDuplicateAction({
agent: agent(),
draft: profileDraft,
modelConfigResolutionPending: false,
translate: (key: string) => key,
});
return (
<button type="button" onClick={() => void handleDuplicate()} aria-busy={duplicating}>
duplicate
</button>
);
}
/** Reads the most recently pushed toast from the harness. */
function lastToast(): ToastArgs {
const call = toast.mock.calls.at(-1);
return call ? call[0] : {};
}
afterEach(() => {
cleanup();
vi.clearAllMocks();
hoisted.coordinatorInvalidReason = undefined;
});
describe("useProfileDuplicateAction", () => {
it("aborts without POSTing when a contributor cannot save", async () => {
saveAll.mockResolvedValue({ canLeave: false, failedIds: new Set() });
render(<Harness />);
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "duplicate" }));
});
expect(duplicateAction).not.toHaveBeenCalled();
expect(routerPush).not.toHaveBeenCalled();
});
it("toasts the coordinator invalid reason when the profile draft is valid but MCP is not", async () => {
hoisted.coordinatorInvalidReason = "MCP server URL invalid";
saveAll.mockResolvedValue({ canLeave: false, failedIds: new Set() });
render(<Harness />);
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "duplicate" }));
});
expect(duplicateAction).not.toHaveBeenCalled();
expect(lastToast().description).toBe("MCP server URL invalid");
});
it("toasts the profile-name validation reason when the draft name is empty", async () => {
saveAll.mockResolvedValue({ canLeave: false, failedIds: new Set() });
render(<Harness profileDraft={draft({ name: " " })} />);
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "duplicate" }));
});
expect(duplicateAction).not.toHaveBeenCalled();
expect(lastToast().description).toBe("agents:profileNameRequired");
});
it("falls back to a generic toast when the save is blocked without a specific reason", async () => {
// canLeave=false with no invalidReason and a valid draft: another save is
// in flight or newer changes appeared. The abort must still be visible.
saveAll.mockResolvedValue({ canLeave: false, failedIds: new Set() });
render(<Harness />);
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "duplicate" }));
});
expect(duplicateAction).not.toHaveBeenCalled();
expect(lastToast().description).toBe("agents:duplicateSaveBlocked");
});
it("POSTs, merges, toasts, and SPA-navigates when the save succeeds", async () => {
saveAll.mockResolvedValue({ canLeave: true, failedIds: new Set() });
duplicateAction.mockResolvedValue(draft({ id: "p2", name: "Default Copy" }));
render(<Harness />);
await act(async () => {
fireEvent.click(screen.getByRole("button", { name: "duplicate" }));
});
expect(duplicateAction).toHaveBeenCalledTimes(1);
expect(duplicateAction).toHaveBeenCalledWith("p1");
expect(setState).toHaveBeenCalledTimes(1);
expect(cancelPendingNavigation).toHaveBeenCalledTimes(1);
expect(routerPush).toHaveBeenCalledWith("/settings/agents/mock-agent/profiles/p2");
expect(toast.mock.calls.some(([t]) => t?.title === "agents:duplicateProfileSuccess")).toBe(
true,
);
});
it("ignores a second click while the first duplicate is in flight", async () => {
saveAll.mockResolvedValue({ canLeave: true, failedIds: new Set() });
let resolveDuplicate: (value: AgentProfile) => void = () => undefined;
duplicateAction.mockImplementation(
() =>
new Promise<AgentProfile>((resolve) => {
resolveDuplicate = resolve;
}),
);
render(<Harness />);
fireEvent.click(screen.getByRole("button", { name: "duplicate" }));
fireEvent.click(screen.getByRole("button", { name: "duplicate" }));
await act(async () => {
resolveDuplicate(draft({ id: "p2", name: "Default Copy" }));
});
expect(duplicateAction).toHaveBeenCalledTimes(1);
});
});
@@ -0,0 +1,133 @@
"use client";
/**
* Header duplicate action for the agent profile settings page, extracted so
* the page stays presentation-only and the save-gate + in-flight guard are
* unit-testable. Mirrors the agent-profile-page-state.ts split.
*/
import { useCallback, useRef, useState } from "react";
import { duplicateAgentProfileAction } from "@/app/actions/agents";
import { useAppStoreApi } from "@/components/state-provider";
import { useToast } from "@/components/toast-provider";
import { useSettingsSaveCoordinator } from "@/components/settings/settings-save-provider";
import { applyProfileDuplicated } from "@/hooks/domains/settings/use-profile-duplicate";
import { errorMessage } from "@/components/settings/agent-profile-page-state";
import { useRouter } from "@/lib/routing/client-router";
import { runWithNavigationBlockerBypassed } from "@/lib/routing/navigation-guard";
import type { Agent, AgentProfile } from "@/lib/types/http";
/**
* Returns the localized reason a profile draft cannot be saved yet (missing
* name or model resolution still pending), or undefined when it is savable.
*/
export function profileSaveInvalidReason(
profileName: string,
modelConfigResolutionPending: boolean,
translate: (key: string) => string,
): string | undefined {
if (!profileName.trim()) return translate("agents:profileNameRequired");
if (modelConfigResolutionPending) return translate("agents:resolvingModelOptions");
return undefined;
}
type UseProfileDuplicateActionOptions = {
agent: Agent;
draft: AgentProfile;
modelConfigResolutionPending: boolean;
translate: (key: string) => string;
};
/**
* Header "Duplicate" flow: save every dirty contributor (profile editor AND
* MCP card) through the shared settings coordinator — aborting with the
* blocking contributor's reason when anything is invalid — then POST the
* duplicate, merge the copy into the store, toast, and SPA-navigate to the
* copy's page. The in-flight guard is a ref (synchronous) so two rapid clicks
* can never issue two copies; the state only drives the button's disabled
* state.
*/
export function useProfileDuplicateAction({
agent,
draft,
modelConfigResolutionPending,
translate,
}: UseProfileDuplicateActionOptions) {
const storeApi = useAppStoreApi();
const router = useRouter();
const { saveAll, invalidReason, cancelPendingNavigation } = useSettingsSaveCoordinator();
const { toast } = useToast();
const [duplicating, setDuplicating] = useState(false);
const inFlightRef = useRef(false);
const handleDuplicate = useCallback(async () => {
if (inFlightRef.current) return;
inFlightRef.current = true;
setDuplicating(true);
try {
// Save EVERY dirty contributor (the profile editor AND the MCP card)
// so the copy starts from what the user sees. saveAll respects each
// contributor's canSave; when anything is invalid or fails to persist,
// it reports canLeave=false and we abort before posting.
const saved = await saveAll();
if (!saved.canLeave) {
// Surface whichever contributor is blocking the save (MCP error or
// an invalid profile draft); when the coordinator gives no reason
// (another save in flight, or newer changes appeared during the
// awaited save), fall back to a generic message so the abort is
// never silent.
toast({
title: translate("agents:failedToDuplicateProfile"),
description:
invalidReason ??
profileSaveInvalidReason(draft.name, modelConfigResolutionPending, translate) ??
translate("agents:duplicateSaveBlocked"),
variant: "error",
});
return;
}
const created = await duplicateAgentProfileAction(draft.id);
// Merge the copy into the store so the destination page resolves it
// without waiting on the WS round-trip.
storeApi.setState((state) => applyProfileDuplicated(state, agent, created));
toast({
title: translate("agents:duplicateProfileSuccess"),
description: created.name,
variant: "success",
});
// Supersede any navigation intent the dirty guard blocked (e.g. a
// browser-back while dirty) — this duplicate navigation replaces it.
cancelPendingNavigation();
// SPA navigation, not location.assign: the toast survives the route
// change and the dirty-settings blocker was already resolved by the
// save above (the bypass is the pattern the executor editors use
// after an awaited save).
runWithNavigationBlockerBypassed(() =>
router.push(`/settings/agents/${encodeURIComponent(agent.name)}/profiles/${created.id}`),
);
} catch (error) {
toast({
title: translate("agents:failedToDuplicateProfile"),
description: errorMessage(error),
variant: "error",
});
} finally {
inFlightRef.current = false;
setDuplicating(false);
}
}, [
agent,
cancelPendingNavigation,
draft.id,
draft.name,
invalidReason,
modelConfigResolutionPending,
router,
saveAll,
storeApi,
toast,
translate,
]);
return { handleDuplicate, duplicating };
}
@@ -0,0 +1,132 @@
import { describe, expect, it, vi } from "vitest";
import type { Agent } from "@/lib/types/http";
import type { AgentProfileOption } from "@/lib/state/slices/settings/types";
import { reconcileAgentProfileOptions } from "./agent-profile-page-state";
vi.mock("@/app/actions/agents", () => ({
deleteAgentProfileAction: vi.fn(),
updateAgentProfileAction: vi.fn(),
}));
vi.mock("@/components/state-provider", () => ({ useAppStore: vi.fn(), useAppStoreApi: vi.fn() }));
vi.mock("@/lib/i18n", () => ({ t: (key: string) => key }));
/** Builds an Agent fixture with the given profile names. */
function agent(id: string, ...profileNames: string[]): Agent {
return {
id,
name: id,
profiles: profileNames.map((name) => ({
id: name,
agentId: id,
name,
agentDisplayName: "Test Agent",
model: "",
allowIndexing: false,
autoApprove: false,
cliFlags: [],
cliPassthrough: false,
enabled: true,
createdAt: "",
updatedAt: "",
})),
} as unknown as Agent;
}
/** Builds an AgentProfileOption fixture with an optional updatedAt. */
function option(id: string, updatedAt = ""): AgentProfileOption {
return {
id,
label: id,
agent_id: "a1",
agent_name: "a1",
cli_passthrough: false,
updatedAt,
};
}
describe("reconcileAgentProfileOptions", () => {
it("rebuilds options from the next agent list", () => {
const next = reconcileAgentProfileOptions([], [agent("a1", "p1", "p2")]);
expect(next.map((o) => o.id).sort()).toEqual(["p1", "p2"]);
});
it("preserves WS-delivered orphan options the rebuild does not represent", () => {
// p-orphan was delivered by WS for an agent absent from the next list.
const next = reconcileAgentProfileOptions([option("p-orphan")], [agent("a1", "p1")]);
const ids = next.map((o) => o.id);
expect(ids).toContain("p-orphan");
expect(ids).toContain("p1");
});
it("replaces stale options with the rebuilt versions by id", () => {
const next = reconcileAgentProfileOptions([option("p1")], [agent("a1", "p1")]);
expect(next.filter((o) => o.id === "p1")).toHaveLength(1);
expect(next.find((o) => o.id === "p1")?.label).toContain("p1");
});
it("keeps a newer existing option over a stale rebuilt one", () => {
// WS updated the option (enabled=false, newer revision) while the next
// agent list carries a stale profile. The rebuild must not regress it.
const staleProfile = {
id: "a1",
name: "a1",
profiles: [
{
id: "p1",
agentId: "a1",
name: "p1",
agentDisplayName: "Test Agent",
model: "",
allowIndexing: false,
autoApprove: false,
cliFlags: [],
cliPassthrough: false,
enabled: true,
createdAt: "",
updatedAt: "2026-08-11T21:00:00Z",
},
],
} as unknown as Agent;
const newerOption = { ...option("p1", "2026-08-11T22:00:00Z"), enabled: false };
const next = reconcileAgentProfileOptions([newerOption], [staleProfile]);
const options = next.filter((o) => o.id === "p1");
expect(options).toHaveLength(1);
expect(options[0].enabled).toBe(false);
expect(options[0].updatedAt).toBe("2026-08-11T22:00:00Z");
});
it("keeps a fractional-second newer option over a whole-second rebuilt one", () => {
// Lexically "…22:00:00Z" sorts after "…22:00:00.100Z" despite being
// older, so revision precedence must compare instants, not strings.
const staleProfile = {
id: "a1",
name: "a1",
profiles: [
{
id: "p1",
agentId: "a1",
name: "p1",
agentDisplayName: "Test Agent",
model: "",
allowIndexing: false,
autoApprove: false,
cliFlags: [],
cliPassthrough: false,
enabled: true,
createdAt: "",
updatedAt: "2026-08-11T22:00:00Z",
},
],
} as unknown as Agent;
const fractionalOption = { ...option("p1", "2026-08-11T22:00:00.100Z"), enabled: false };
const next = reconcileAgentProfileOptions([fractionalOption], [staleProfile]);
const options = next.filter((o) => o.id === "p1");
expect(options).toHaveLength(1);
expect(options[0].enabled).toBe(false);
expect(options[0].updatedAt).toBe("2026-08-11T22:00:00.100Z");
});
});
@@ -12,26 +12,47 @@
import { useMemo, useState } from "react";
import { permissionsToProfilePatch } from "@/lib/agent-permissions";
import { deleteAgentProfileAction, updateAgentProfileAction } from "@/app/actions/agents";
import { useAppStore } from "@/components/state-provider";
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
import { isProfileDirty } from "@/components/settings/agent-profile-dirty";
import type { useToast } from "@/components/toast-provider";
import type { AgentProfileDeleteConflict } from "@/components/settings/agent-profile-delete-dialog";
import { t as translate } from "@/lib/i18n";
import { toAgentProfileOption } from "@/lib/state/slices/settings/types";
import {
mergeOptionsByNewest,
toAgentProfileOption,
type AgentProfileOption,
} from "@/lib/state/slices/settings/types";
import { ApiError } from "@/lib/api/client";
import type { Agent, AgentProfile, PermissionSetting } from "@/lib/types/http";
export type SaveStatus = "idle" | "loading" | "success" | "error";
/**
* Reconcile the options slice with the next agent list by ID: options the
* rebuild does not represent (e.g. profiles the WS handler delivered for
* agents temporarily absent from `settingsAgents`) are preserved, and rebuilt
* options replace any stale versions. Same rule as
* `applyProfileDuplicated` in the duplicate hook — a save must never wipe
* orphan options.
*/
export function reconcileAgentProfileOptions(
previousOptions: AgentProfileOption[],
nextAgents: Agent[],
): AgentProfileOption[] {
const rebuiltOptions = nextAgents.flatMap((agentItem) =>
agentItem.profiles.map((agentProfile) => toAgentProfileOption(agentItem, agentProfile)),
);
return mergeOptionsByNewest(previousOptions, rebuiltOptions);
}
export function useSyncAgentsToStore() {
const setSettingsAgents = useAppStore((state) => state.setSettingsAgents);
const setAgentProfiles = useAppStore((state) => state.setAgentProfiles);
const storeApi = useAppStoreApi();
return (nextAgents: Agent[]) => {
setSettingsAgents(nextAgents);
setAgentProfiles(
nextAgents.flatMap((agentItem) =>
agentItem.profiles.map((agentProfile) => toAgentProfileOption(agentItem, agentProfile)),
),
reconcileAgentProfileOptions(storeApi.getState().agentProfiles.items, nextAgents),
);
};
}
@@ -4,7 +4,7 @@ import { useCallback, useState } from "react";
import { useTranslation } from "react-i18next";
import Link from "@/components/routing/app-link";
import { useParams } from "@/lib/routing/client-router";
import { IconTrash } from "@tabler/icons-react";
import { IconCopy, IconTrash } from "@tabler/icons-react";
import { Badge } from "@kandev/ui/badge";
import { Button } from "@kandev/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@kandev/ui/card";
@@ -33,6 +33,10 @@ import {
useProfileSave,
useSyncAgentsToStore,
} from "@/components/settings/agent-profile-page-state";
import {
profileSaveInvalidReason,
useProfileDuplicateAction,
} from "@/components/settings/agent-profile-duplicate-action";
import { CustomCLIFlagsCard } from "@/components/settings/cli-flags-field";
import { ProfileEnabledHelp } from "@/components/settings/profile-enabled-help";
@@ -73,24 +77,18 @@ type ProfileEditorHeaderProps = {
savedProfileName: string;
enabled: boolean;
onEnabledChange: (enabled: boolean) => void;
onDuplicate: () => void;
duplicating: boolean;
};
function profileSaveInvalidReason(
profileName: string,
modelConfigResolutionPending: boolean,
translate: (key: string) => string,
): string | undefined {
if (!profileName.trim()) return translate("agents:profileNameRequired");
if (modelConfigResolutionPending) return translate("agents:resolvingModelOptions");
return undefined;
}
function ProfileEditorHeader({
agentName,
agentDisplayName,
savedProfileName,
enabled,
onEnabledChange,
onDuplicate,
duplicating,
}: ProfileEditorHeaderProps) {
const { t } = useTranslation();
return (
@@ -105,6 +103,18 @@ function ProfileEditorHeader({
</p>
</div>
<div className="flex items-center gap-3 sm:shrink-0">
<Button
variant="outline"
onClick={onDuplicate}
data-testid="duplicate-profile-header"
className="min-h-11"
disabled={duplicating}
aria-busy={duplicating}
title={t("agents:duplicateProfileNamed", { name: savedProfileName })}
>
<IconCopy className="h-4 w-4 mr-2" />
{t("agents:duplicate")}
</Button>
<div className="flex items-center gap-1 text-left sm:text-right">
<p className="text-sm font-medium">{t("agents:enabled")}</p>
<ProfileEnabledHelp />
@@ -403,6 +413,13 @@ function ProfileEditor({
});
const deleteState = useProfileDelete(agent, draft, settingsAgents, syncAgentsToStore, toast);
const { handleDuplicate: handleDuplicateProfile, duplicating } = useProfileDuplicateAction({
agent,
draft,
modelConfigResolutionPending,
translate: t,
});
return (
<div className="space-y-8">
<ProfileEditorHeader
@@ -411,6 +428,8 @@ function ProfileEditor({
savedProfileName={savedProfile.name}
enabled={draft.enabled ?? true}
onEnabledChange={(next) => updateDraft({ enabled: next })}
onDuplicate={() => void handleDuplicateProfile()}
duplicating={duplicating}
/>
<Separator />
@@ -6,6 +6,7 @@ import type { Agent, AgentProfile } from "@/lib/types/http";
const mocks = vi.hoisted(() => ({
deleteAgentProfileAction: vi.fn(),
duplicateAgentProfileAction: vi.fn(),
toast: vi.fn(),
routerPush: vi.fn(),
}));
@@ -41,11 +42,12 @@ const selectors = {
vi.mock("@/components/state-provider", () => ({
useAppStore: (selector: (s: unknown) => unknown) => selector({ ...storeState, ...selectors }),
useAppStoreApi: () => ({ getState: () => storeState }),
useAppStoreApi: () => ({ getState: () => storeState, setState: vi.fn() }),
}));
vi.mock("@/app/actions/agents", () => ({
deleteAgentProfileAction: mocks.deleteAgentProfileAction,
duplicateAgentProfileAction: mocks.duplicateAgentProfileAction,
}));
vi.mock("@/components/toast-provider", () => ({
@@ -68,8 +70,16 @@ vi.mock("@kandev/ui/dropdown-menu", () => ({
DropdownMenu: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
DropdownMenuTrigger: ({ children }: { children?: ReactNode }) => <>{children}</>,
DropdownMenuContent: ({ children }: { children?: ReactNode }) => <div>{children}</div>,
DropdownMenuItem: ({ children, onSelect }: { children?: ReactNode; onSelect?: () => void }) => (
<button type="button" data-testid="delete-item" onClick={onSelect}>
DropdownMenuItem: ({
children,
onSelect,
"data-testid": testId,
}: {
children?: ReactNode;
onSelect?: () => void;
"data-testid"?: string;
}) => (
<button type="button" data-testid={testId ?? "delete-item"} onClick={onSelect}>
{children}
</button>
),
@@ -158,3 +168,26 @@ describe("ProfileRow deletion", () => {
expect(storeState.agentProfiles.items).toEqual([]);
});
});
describe("ProfileRow duplicate", () => {
beforeEach(() => {
storeState = {
settingsAgents: { items: [{ ...AGENT, profiles: [...AGENT.profiles] }] },
agentProfiles: { items: [] },
};
});
it("calls the duplicate action with the profile id", async () => {
mocks.duplicateAgentProfileAction.mockResolvedValue({
id: "p-3",
name: "Alpha Copy",
} as unknown as AgentProfile);
renderRows();
const row = screen.getByLabelText("Alpha").closest('[data-testid="agent-profile-row"]');
if (!row) throw new Error("no row for Alpha");
fireEvent.click(row.querySelector('[data-testid="duplicate-profile-p-1"]')!);
await waitFor(() => expect(mocks.duplicateAgentProfileAction).toHaveBeenCalledWith("p-1"));
});
});
@@ -2,7 +2,7 @@
import { useState } from "react";
import { useTranslation } from "react-i18next";
import { IconDotsVertical, IconPlus, IconTrash } from "@tabler/icons-react";
import { IconCopy, IconDotsVertical, IconPlus, IconTrash } from "@tabler/icons-react";
import { Badge } from "@kandev/ui/badge";
import { Button } from "@kandev/ui/button";
import { Card, CardContent } from "@kandev/ui/card";
@@ -17,6 +17,7 @@ import { useAppStore, useAppStoreApi } from "@/components/state-provider";
import { useToast } from "@/components/toast-provider";
import { AgentProfileDeleteConfirmDialog } from "@/components/settings/agent-profile-delete-dialog";
import { deleteAgentProfileAction } from "@/app/actions/agents";
import { useProfileDuplicate } from "@/hooks/domains/settings/use-profile-duplicate";
import { useRouter } from "@/lib/routing/client-router";
import { toAgentProfileOption } from "@/lib/state/slices/settings/types";
import type { Agent, AgentProfile } from "@/lib/types/http";
@@ -76,6 +77,56 @@ export function AgentProfilesSubList({
);
}
/**
* The per-profile actions dropdown (duplicate, delete). The trigger exposes a
* touch-sized hitbox (>= 44px) so the row actions are reachable on mobile.
* Duplication uses the shared useProfileDuplicate hook (per-profile in-flight
* guard, revision-aware store merge).
*/
function ProfileRowActions({
agent,
profile,
onConfirmDelete,
}: {
agent: Agent;
profile: AgentProfile;
onConfirmDelete: () => void;
}) {
const { t } = useTranslation();
const handleDuplicate = useProfileDuplicate();
return (
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="cursor-pointer min-h-11 min-w-11"
aria-label={t("agents:profileActions")}
>
<IconDotsVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
className="cursor-pointer"
data-testid={`duplicate-profile-${profile.id}`}
onSelect={() => void handleDuplicate(agent, profile)}
>
<IconCopy className="h-4 w-4 mr-2" />
{t("agents:duplicate")}
</DropdownMenuItem>
<DropdownMenuItem
className="cursor-pointer text-destructive focus:text-destructive"
onSelect={onConfirmDelete}
>
<IconTrash className="h-4 w-4 mr-2" />
{t("agents:delete")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
);
}
/** One saved profile as a fully clickable row — shared by the Agents index and the agent page. */
export function ProfileRow({ agent, profile }: { agent: Agent; profile: AgentProfile }) {
const { t } = useTranslation();
@@ -150,27 +201,11 @@ export function ProfileRow({ agent, profile }: { agent: Agent; profile: AgentPro
)}
</div>
<div className="relative z-10 flex shrink-0 items-center gap-1">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="ghost"
size="sm"
className="cursor-pointer"
aria-label={t("agents:profileActions")}
>
<IconDotsVertical className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
className="cursor-pointer text-destructive focus:text-destructive"
onSelect={() => setConfirmOpen(true)}
>
<IconTrash className="h-4 w-4 mr-2" />
{t("agents:delete")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<ProfileRowActions
agent={agent}
profile={profile}
onConfirmDelete={() => setConfirmOpen(true)}
/>
</div>
</CardContent>
<AgentProfileDeleteConfirmDialog
@@ -23,6 +23,7 @@ const COULDNT_SAVE_LABEL = "Couldn't save";
const COULDNT_RESET_LABEL = "Couldn't reset";
const APPEARANCE_ID = "appearance";
const FLOATING_SAVE_TEST_ID = "settings-floating-save";
const SAVE_AND_LEAVE_LABEL = "Save and leave";
const APPEARANCE_PATH = "/settings/general/appearance";
const TERMINAL_PATH = "/settings/general/terminal";
@@ -84,6 +85,35 @@ function DraftContributor({
);
}
/** A contributor that starts clean (revision equals savedRevision) and dirties on Edit. */
function CleanStartDraftContributor({
id,
onSave,
}: {
id: string;
onSave: () => Promise<void> | void;
}) {
const [revision, setRevision] = useState(1);
const [savedRevision, setSavedRevision] = useState(1); // starts clean
useSettingsSaveContributor({
id,
revision,
isDirty: revision !== savedRevision,
save: async () => {
await onSave();
setSavedRevision(revision);
},
discard: () => setRevision(savedRevision),
});
return (
<button type="button" onClick={() => setRevision((current) => current + 1)}>
Edit {id}
</button>
);
}
function BooleanDraftContributor({ pending }: { pending: Deferred }) {
const [draft, setDraft] = useState(true);
const [baseline, setBaseline] = useState(false);
@@ -456,13 +486,13 @@ describe("SettingsSaveProvider navigation", () => {
);
fireEvent.click(screen.getByRole("link", { name: "Terminal" }));
fireEvent.click(await screen.findByRole("button", { name: "Save and leave" }));
fireEvent.click(await screen.findByRole("button", { name: SAVE_AND_LEAVE_LABEL }));
expect(await screen.findByText("Couldn't save")).toBeTruthy();
expect(window.location.pathname).toBe(APPEARANCE_PATH);
shouldFail = false;
fireEvent.click(screen.getByRole("button", { name: "Save and leave" }));
fireEvent.click(screen.getByRole("button", { name: SAVE_AND_LEAVE_LABEL }));
await waitFor(() => expect(window.location.pathname).toBe(TERMINAL_PATH));
});
@@ -477,7 +507,7 @@ describe("SettingsSaveProvider navigation", () => {
);
fireEvent.click(screen.getByRole("link", { name: "Terminal" }));
fireEvent.click(await screen.findByRole("button", { name: "Save and leave" }));
fireEvent.click(await screen.findByRole("button", { name: SAVE_AND_LEAVE_LABEL }));
await waitFor(() => expect(window.location.pathname).toBe(TERMINAL_PATH));
});
@@ -507,6 +537,73 @@ describe("SettingsSaveProvider navigation", () => {
});
});
describe("SettingsSaveProvider mid-save edits", () => {
it("stays put when a contributor becomes dirty while the save is in flight", async () => {
window.history.replaceState({}, "", APPEARANCE_PATH);
const pending = deferred();
render(
<SettingsSaveProvider>
<DraftContributor id="appearance" onSave={() => pending.promise} />
<CleanStartDraftContributor id="mcp" onSave={vi.fn()} />
<Link href={TERMINAL_PATH}>Terminal</Link>
</SettingsSaveProvider>,
);
fireEvent.click(screen.getByRole("button", { name: "Edit appearance" }));
fireEvent.click(screen.getByRole("link", { name: "Terminal" }));
fireEvent.click(await screen.findByRole("button", { name: SAVE_AND_LEAVE_LABEL }));
// The MCP contributor (clean at the save snapshot) becomes dirty while
// the appearance save is pending. Radix aria-hides the page behind the
// modal, so query with hidden:true.
fireEvent.click(screen.getByRole("button", { name: "Edit mcp", hidden: true }));
await act(async () => pending.resolve());
// The newly dirty contributor blocks leaving: the navigation must not
// proceed (saveAll reports canLeave=false).
await waitFor(() => expect(window.location.pathname).toBe(APPEARANCE_PATH));
expect(screen.getByRole("button", { name: SAVE_AND_LEAVE_LABEL })).toBeTruthy();
});
it("does not treat a re-rendered same-id contributor as newly dirty mid-save", async () => {
window.history.replaceState({}, "", APPEARANCE_PATH);
const pending = deferred();
const onSave = vi.fn(() => pending.promise);
function PokingContributor() {
const [, setPoke] = useState(0);
return (
<>
<DraftContributor id="appearance" onSave={onSave} />
<button type="button" onClick={() => setPoke((n) => n + 1)}>
Poke appearance
</button>
</>
);
}
render(
<SettingsSaveProvider>
<PokingContributor />
<Link href={TERMINAL_PATH}>Terminal</Link>
</SettingsSaveProvider>,
);
fireEvent.click(screen.getByRole("button", { name: "Edit appearance" }));
fireEvent.click(screen.getByRole("link", { name: "Terminal" }));
fireEvent.click(await screen.findByRole("button", { name: SAVE_AND_LEAVE_LABEL }));
// Re-render the contributor while its save is pending: the registry
// replaces the contributor object on every upsert, so an identity-based
// "newly dirty" check would wrongly block leaving. Same id must not count.
fireEvent.click(screen.getByRole("button", { name: "Poke appearance", hidden: true }));
await act(async () => pending.resolve());
await waitFor(() => expect(window.location.pathname).toBe(TERMINAL_PATH));
});
});
describe("SettingsSaveProvider reset coordination", () => {
it("settles navigation requested while a standalone reset is pending", async () => {
window.history.replaceState({}, "", APPEARANCE_PATH);
@@ -63,6 +63,23 @@ type SaveResult = {
const SettingsSaveRegistryContext = createContext<Registry | null>(null);
const SettingsDirtyScopeContext = createContext<DirtyScopeRegistry | null>(null);
export type SettingsSaveCoordinator = {
/** Save every dirty contributor. Respects each contributor's canSave;
* returns canLeave=false when any contributor is invalid or fails. */
saveAll: () => Promise<SaveResult>;
status: SettingsSaveStatus;
errorKind: SettingsSaveErrorKind | null;
hasDirty: boolean;
/** Reason why the first invalid dirty contributor cannot be saved, if any. */
invalidReason: string | undefined;
/** Cancel a navigation intent blocked by the dirty guard (the caller is
* superseding it with its own navigation). */
cancelPendingNavigation: () => void;
clearSavedStatus: () => void;
};
const SettingsSaveCoordinatorContext = createContext<SettingsSaveCoordinator | null>(null);
export function SettingsSaveProvider({
children,
placement = "viewport",
@@ -75,10 +92,6 @@ export function SettingsSaveProvider({
contributors,
refreshRegistry,
);
const pendingNavigationRef = useRef<NavigationIntent | null>(null);
const discardingRef = useRef(false);
const [pendingNavigation, setPendingNavigation] = useState<NavigationIntent | null>(null);
const [isDiscarding, setIsDiscarding] = useState(false);
const hasDirty = dirtyContributors.length > 0;
const invalidReason = dirtyContributors.find(({ contributor }) => contributor.canSave === false)
?.contributor.invalidReason;
@@ -90,6 +103,153 @@ export function SettingsSaveProvider({
return () => window.clearTimeout(timeout);
}, [clearSavedStatus, status]);
const {
pendingNavigation,
isDiscarding,
handleSave,
discardDirtyContributors,
discardAndLeave,
continueEditing,
} = useSaveNavigationFlow({ saveAll, contributors, markError, refreshRegistry, hasDirty });
useSettingsBeforeUnloadGuard(hasDirty);
return (
<SettingsSaveProviderBody
registry={registry}
coordinator={{
saveAll,
status,
errorKind,
hasDirty,
invalidReason,
cancelPendingNavigation: continueEditing,
clearSavedStatus,
}}
placement={placement}
displayStatus={displayStatus}
errorKind={errorKind}
dirtyContributorIds={dirtyContributors.map(({ contributor }) => contributor.id).join(",")}
invalidReason={invalidReason}
pendingNavigation={pendingNavigation}
isDiscarding={isDiscarding}
onSave={handleSave}
onReset={discardDirtyContributors}
onDiscardAndLeave={discardAndLeave}
onContinueEditing={continueEditing}
>
{children}
</SettingsSaveProviderBody>
);
}
type SettingsSaveProviderBodyProps = {
registry: Registry;
coordinator: SettingsSaveCoordinator;
placement: SettingsSavePlacement;
displayStatus: SettingsSaveStatus;
errorKind: SettingsSaveErrorKind | null;
dirtyContributorIds: string;
invalidReason: string | undefined;
pendingNavigation: NavigationIntent | null;
isDiscarding: boolean;
onSave: () => Promise<boolean>;
onReset: () => Promise<boolean>;
onDiscardAndLeave: () => Promise<void>;
onContinueEditing: () => void;
children: ReactNode;
};
/**
* Renders the provider's context stack (registry + coordinator) around the
* page content and the floating save bar/dialog. Extracted to keep
* SettingsSaveProvider under the line limit.
*/
function SettingsSaveProviderBody({
registry,
coordinator,
placement,
displayStatus,
errorKind,
dirtyContributorIds,
invalidReason,
pendingNavigation,
isDiscarding,
onSave,
onReset,
onDiscardAndLeave,
onContinueEditing,
children,
}: SettingsSaveProviderBodyProps) {
const hasDirty = coordinator.hasDirty;
return (
<SettingsSaveRegistryContext.Provider value={registry}>
<SettingsSaveCoordinatorContext.Provider value={coordinator}>
{children}
{(hasDirty || displayStatus === "saved") && (
<SettingsFloatingSave
status={displayStatus}
placement={placement}
errorKind={errorKind}
dirtyContributorIds={dirtyContributorIds}
invalidReason={invalidReason}
navigationIntent={pendingNavigation}
isDiscarding={isDiscarding}
onSave={onSave}
onReset={onReset}
onDiscardAndLeave={onDiscardAndLeave}
onContinueEditing={onContinueEditing}
/>
)}
</SettingsSaveCoordinatorContext.Provider>
</SettingsSaveRegistryContext.Provider>
);
}
/**
* Imperative handle on the shared settings save coordinator: save every dirty
* contributor (across pages that register multiple contributors, e.g. the
* profile editor and its MCP card) and learn whether the page can be left.
* Requires SettingsSaveProvider.
*/
export function useSettingsSaveCoordinator(): SettingsSaveCoordinator {
const coordinator = useContext(SettingsSaveCoordinatorContext);
if (!coordinator) throw new Error("useSettingsSaveCoordinator requires SettingsSaveProvider");
return coordinator;
}
/**
* Owns the save/discard/continue actions and the dirty-navigation blocker:
* registers the blocker while anything is dirty, saves and settles a pending
* navigation intent, or discards the dirty contributors and leaves.
*/
function useSaveNavigationFlow({
saveAll,
contributors,
markError,
refreshRegistry,
hasDirty,
}: {
saveAll: () => Promise<SaveResult>;
contributors: Map<string, RegisteredContributor>;
markError: (kind: SettingsSaveErrorKind) => void;
refreshRegistry: () => void;
hasDirty: boolean;
}) {
const pendingNavigationRef = useRef<NavigationIntent | null>(null);
const discardingRef = useRef(false);
const [pendingNavigation, setPendingNavigation] = useState<NavigationIntent | null>(null);
const [isDiscarding, setIsDiscarding] = useState(false);
useEffect(() => {
if (!hasDirty) return;
return setNavigationBlocker((intent) => {
pendingNavigationRef.current?.cancel();
pendingNavigationRef.current = intent;
setPendingNavigation(intent);
});
}, [hasDirty]);
const handleSave = useCallback(async (): Promise<boolean> => {
const result = await saveAll();
if (!result.canLeave) return false;
@@ -136,37 +296,14 @@ export function SettingsSaveProvider({
intent?.cancel();
}, []);
useEffect(() => {
if (!hasDirty) return;
return setNavigationBlocker((intent) => {
pendingNavigationRef.current?.cancel();
pendingNavigationRef.current = intent;
setPendingNavigation(intent);
});
}, [hasDirty]);
useSettingsBeforeUnloadGuard(hasDirty);
return (
<SettingsSaveRegistryContext.Provider value={registry}>
{children}
{(hasDirty || status === "saved") && (
<SettingsFloatingSave
status={displayStatus}
placement={placement}
errorKind={errorKind}
dirtyContributorIds={dirtyContributors.map(({ contributor }) => contributor.id).join(",")}
invalidReason={invalidReason}
navigationIntent={pendingNavigation}
isDiscarding={isDiscarding}
onSave={handleSave}
onReset={discardDirtyContributors}
onDiscardAndLeave={discardAndLeave}
onContinueEditing={continueEditing}
/>
)}
</SettingsSaveRegistryContext.Provider>
);
return {
pendingNavigation,
isDiscarding,
handleSave,
discardDirtyContributors,
discardAndLeave,
continueEditing,
};
}
function useSettingsBeforeUnloadGuard(enabled: boolean) {
@@ -299,11 +436,25 @@ function useSaveCoordinator(
}
savingRef.current = false;
// Revalidate the whole registry before reporting canLeave: a contributor
// that became dirty while the saves were in flight (e.g. the MCP card
// edited during the profile save) is absent from the submitted snapshot
// and would otherwise be skipped while the caller proceeds on stale data.
// Compare by id: the registry replaces the contributor object on every
// upsert, so an identity check would report submitted contributors as
// newly dirty after any re-render and block save-and-leave.
const submittedIds = new Set(submitted.map(({ contributor }) => contributor.id));
const newlyDirty = getDirtyContributors(contributors).filter(
({ contributor }) => !submittedIds.has(contributor.id),
);
const completionStatus = saveCompletionStatus(failedIds, hasNewerChanges);
setErrorKind(completionStatus === "error" ? "save" : null);
setStatus(completionStatus);
refreshRegistry();
return { canLeave: failedIds.size === 0 && !hasNewerChanges, failedIds };
return {
canLeave: failedIds.size === 0 && !hasNewerChanges && newlyDirty.length === 0,
failedIds,
};
}, [contributors, refreshRegistry]);
return { status, errorKind, saveAll, clearSavedStatus, markError };
@@ -0,0 +1,131 @@
import { test, expect } from "../../fixtures/test-base";
/**
* Verifies the agent profile duplicate flow:
*
* - The /settings/agents profile list shows a Duplicate button per row.
* - Clicking it creates a "<source> Copy" profile that appears in the list
* without a page reload, copying the source's model.
* - The copy is an independent profile with its own settings page.
*
* Uses the seeded default profile (like agent-profile-disable.spec.ts)
* rather than creating one: the profile list is hydrated on the server, so a
* freshly POSTed profile race-conditions with SSR.
*/
test.describe("Agent profile duplicate", () => {
test("duplicates the seeded profile from the settings list", async ({ testPage, apiClient }) => {
test.setTimeout(90_000);
const { agents } = await apiClient.listAgents();
const agent = agents[0];
const profile = agent.profiles[0];
const copyName = `${profile.name} Copy`;
try {
await testPage.goto("/settings/agents");
// The per-row Duplicate action lives in the row's actions dropdown.
const row = testPage.getByTestId("agent-profile-row").filter({ hasText: profile.name });
await expect(row).toBeVisible({ timeout: 15_000 });
await row.getByRole("button", { name: "Profile actions" }).click();
const duplicate = testPage.getByTestId(`duplicate-profile-${profile.id}`);
await expect(duplicate).toBeVisible({ timeout: 15_000 });
await duplicate.click();
// Backend state: the copy is a new row with the source's model. The
// duplicate POST is synchronous, so listAgents reflects it immediately.
let copy: { id: string; model: string } | undefined;
await expect
.poll(
async () => {
const { agents: after } = await apiClient.listAgents();
const afterAgent = after.find((a) => a.id === agent.id);
copy = afterAgent?.profiles.find((p) => p.name === copyName);
return copy?.id;
},
{ timeout: 15_000 },
)
.toBeTruthy();
expect(copy?.id).not.toBe(profile.id);
expect(copy?.model).toBe(profile.model);
// The copy row appears in the list without a reload. Its row link is
// the unambiguous handle (the sidebar shows a sibling link with a
// different accessible name).
await expect(testPage.getByRole("link", { name: copyName, exact: true })).toBeVisible({
timeout: 15_000,
});
// The copy has its own settings page showing the copied name.
await testPage.goto(`/settings/agents/${agent.name}/profiles/${copy?.id}`);
await expect(
testPage.getByRole("heading", {
name: new RegExp(copyName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")),
}),
).toBeVisible({ timeout: 15_000 });
} finally {
const { agents: cleanupAgents } = await apiClient.listAgents().catch(() => ({
agents: [] as typeof agents,
}));
const cleanupAgent = cleanupAgents.find((a) => a.id === agent.id);
const copy = cleanupAgent?.profiles.find((p) => p.name === copyName);
if (copy) {
await apiClient.deleteAgentProfile(copy.id, true).catch(() => {});
}
}
});
test("duplicates from the profile page header and navigates to the copy", async ({
testPage,
apiClient,
}) => {
test.setTimeout(90_000);
const { agents } = await apiClient.listAgents();
const agent = agents[0];
const profile = agent.profiles[0];
const copyName = `${profile.name} Copy`;
try {
await testPage.goto(`/settings/agents/${agent.name}/profiles/${profile.id}`);
const headerDuplicate = testPage.getByTestId("duplicate-profile-header");
await expect(headerDuplicate).toBeVisible({ timeout: 15_000 });
await headerDuplicate.click();
// The copy exists server-side and the SPA navigates to its page (no
// full reload: the URL changes to the copy's profile route).
let copy: { id: string } | undefined;
await expect
.poll(
async () => {
const { agents: after } = await apiClient.listAgents();
const afterAgent = after.find((a) => a.id === agent.id);
copy = afterAgent?.profiles.find((p) => p.name === copyName);
return copy?.id;
},
{ timeout: 15_000 },
)
.toBeTruthy();
expect(copy?.id).not.toBe(profile.id);
await expect(testPage).toHaveURL(new RegExp(`/profiles/${copy?.id}$`), {
timeout: 15_000,
});
// The copy page renders the copy's name in its header.
await expect(
testPage.getByRole("heading", {
name: new RegExp(copyName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")),
}),
).toBeVisible({ timeout: 15_000 });
} finally {
const { agents: cleanupAgents } = await apiClient.listAgents().catch(() => ({
agents: [] as typeof agents,
}));
const cleanupAgent = cleanupAgents.find((a) => a.id === agent.id);
const copy = cleanupAgent?.profiles.find((p) => p.name === copyName);
if (copy) {
await apiClient.deleteAgentProfile(copy.id, true).catch(() => {});
}
}
});
});
@@ -0,0 +1,79 @@
import { test, expect } from "../../fixtures/test-base";
/**
* Mobile parity for the agent profile duplicate flow: the row-level
* Duplicate control must be reachable by touch on a phone viewport (the
* 44px hitbox), complete the same copy, and keep the document free of
* horizontal overflow. Uses the seeded default profile like the desktop
* spec: the /settings/agents list is server-hydrated, so a freshly POSTed
* profile would race with SSR.
*/
test.describe("Mobile agent profile duplicate", () => {
test("duplicates the seeded profile from the settings list", async ({ testPage, apiClient }) => {
test.setTimeout(90_000);
const { agents } = await apiClient.listAgents();
const agent = agents[0];
const profile = agent.profiles[0];
const copyName = `${profile.name} Copy`;
try {
await testPage.goto("/settings/agents");
// No document-level horizontal overflow on the list page.
await expect
.poll(
async () =>
testPage.evaluate(() => document.documentElement.scrollWidth <= window.innerWidth),
{ timeout: 15_000 },
)
.toBe(true);
const row = testPage.getByTestId("agent-profile-row").filter({ hasText: profile.name });
await expect(row).toBeVisible({ timeout: 15_000 });
// The row's actions trigger exposes a touch-sized hitbox (>= 44px).
// Poll for the box: layout can settle a frame after visibility.
const trigger = row.getByRole("button", { name: "Profile actions" });
await expect
.poll(
async () => {
const box = await trigger.boundingBox();
if (!box) return null;
return Math.min(box.width, box.height);
},
{ timeout: 10_000 },
)
.toBeGreaterThanOrEqual(44);
await trigger.tap();
const duplicate = testPage.getByTestId(`duplicate-profile-${profile.id}`);
await expect(duplicate).toBeVisible({ timeout: 15_000 });
await duplicate.tap();
// The copy appears as its own row without a reload.
await expect
.poll(
async () => {
const { agents: after } = await apiClient.listAgents();
const afterAgent = after.find((a) => a.id === agent.id);
const copy = afterAgent?.profiles.find((p) => p.name === copyName);
return copy?.id;
},
{ timeout: 15_000 },
)
.toBeTruthy();
await expect(testPage.getByRole("link", { name: copyName, exact: true })).toBeVisible({
timeout: 15_000,
});
} finally {
const { agents: cleanupAgents } = await apiClient.listAgents().catch(() => ({
agents: [] as typeof agents,
}));
const cleanupAgent = cleanupAgents.find((a) => a.id === agent.id);
const copy = cleanupAgent?.profiles.find((p) => p.name === copyName);
if (copy) {
await apiClient.deleteAgentProfile(copy.id, true).catch(() => {});
}
}
});
});
@@ -0,0 +1,189 @@
import { describe, expect, it, vi } from "vitest";
import type { Agent, AgentProfile } from "@/lib/types/http";
import type { AgentProfileOption } from "@/lib/state/slices/settings/types";
import { applyProfileDuplicated } from "./use-profile-duplicate";
vi.mock("@/app/actions/agents", () => ({ duplicateAgentProfileAction: vi.fn() }));
vi.mock("@/components/state-provider", () => ({ useAppStoreApi: vi.fn() }));
vi.mock("@/components/toast-provider", () => ({ useToast: vi.fn() }));
const COPY_NAME = "Default Copy";
const OLD_REVISION = "2026-08-11T21:00:00Z";
const NEW_REVISION = "2026-08-11T22:00:00Z";
/** Builds an AgentProfile fixture with an optional updatedAt. */
function profile(id: string, agentId: string, name = id, updatedAt = ""): AgentProfile {
return {
id,
agentId,
name,
agentDisplayName: "Test Agent",
model: "",
allowIndexing: false,
autoApprove: false,
cliFlags: [],
cliPassthrough: false,
enabled: true,
createdAt: "",
updatedAt,
} as unknown as AgentProfile;
}
/** Builds an Agent fixture carrying the given profiles. */
function agent(id: string, ...profiles: AgentProfile[]): Agent {
return { id, name: id, profiles } as unknown as Agent;
}
/** Builds an AgentProfileOption fixture with an optional updatedAt. */
function option(id: string, updatedAt = ""): AgentProfileOption {
return {
id,
label: id,
agent_id: "a1",
agent_name: "a1",
cli_passthrough: false,
updatedAt,
};
}
/** Builds the settings slice state the duplicate merge operates on. */
function stateWith(agents: Agent[], options: AgentProfileOption[]) {
return {
settingsAgents: { items: agents, version: 0 },
agentProfiles: { items: options, version: 0 },
};
}
describe("applyProfileDuplicated", () => {
it("appends the copy to the owning agent and surfaces it as an option", () => {
const source = profile("p1", "a1", "Default");
const copy = profile("p2", "a1", COPY_NAME);
const initial = stateWith([agent("a1", source)], []);
const next = applyProfileDuplicated(initial, agent("a1"), copy);
const profiles = next.settingsAgents.items.find((a) => a.id === "a1")?.profiles ?? [];
expect(profiles.map((p) => p.id)).toEqual(["p1", "p2"]);
// Every profile (source + copy) is rebuilt into the options slice.
expect(next.agentProfiles.items.map((o) => o.id)).toEqual(["p1", "p2"]);
});
it("dedupes by id so a WS-delivered copy is not double-inserted", () => {
const source = profile("p1", "a1");
const copy = profile("p2", "a1", COPY_NAME);
// The WS agent.profile.created handler delivered the copy first.
const initial = stateWith([agent("a1", source)], [option("p2")]);
const next = applyProfileDuplicated(initial, agent("a1"), copy);
const profiles = next.settingsAgents.items.find((a) => a.id === "a1")?.profiles ?? [];
expect(profiles.filter((p) => p.id === "p2")).toHaveLength(1);
expect(next.agentProfiles.items.filter((o) => o.id === "p2")).toHaveLength(1);
});
it("keeps the copy visible when the owning agent left the store mid-request", () => {
const copy = profile("p2", "a1", COPY_NAME);
const initial = stateWith([], []);
const next = applyProfileDuplicated(initial, agent("a1"), copy);
// settingsAgents is unchanged (no agent to attach to), but the copy must
// still surface in the agentProfiles slice instead of being dropped.
expect(next.settingsAgents.items).toEqual([]);
expect(next.agentProfiles.items.map((o) => o.id)).toEqual(["p2"]);
});
it("does not erase a WS-delivered copy and refreshes it with agent metadata", () => {
const copy = profile("p2", "a1", COPY_NAME);
// WS delivered the option first (with a stub agent_name) while the
// owning agent is absent; the merge must replace it with the full-agent
// option rather than keep the empty-name stub.
const initial = stateWith([], [option("p2")]);
const next = applyProfileDuplicated(initial, agent("a1"), copy);
const options = next.agentProfiles.items.filter((o) => o.id === "p2");
expect(options).toHaveLength(1);
expect(options[0].agent_name).toBe("a1");
});
it("keeps a newer WS-delivered orphan option over a stale duplicate response", () => {
// Owner absent; WS delivered a NEWER version of the copy than this
// delayed HTTP response. The merge must not regress it to the stale one.
const staleCreated = profile("p2", "a1", COPY_NAME, OLD_REVISION);
const newerOrphan = option("p2", NEW_REVISION);
const initial = stateWith([], [newerOrphan]);
const next = applyProfileDuplicated(initial, agent("a1"), staleCreated);
const options = next.agentProfiles.items.filter((o) => o.id === "p2");
expect(options).toHaveLength(1);
// The preserved option keeps the newer revision (label from the option).
expect(options[0].label).toBe("p2");
expect(options[0].updatedAt).toBe(NEW_REVISION);
});
it("keeps a newer WS-delivered option over a stale rebuilt one when the owner is present", () => {
// The option was updated by WS (enabled=false, newer revision) while the
// settingsAgents profile is stale. The merge must not regress it to the
// rebuilt (older) version — a disabled profile must stay hidden.
const staleProfile = profile("p1", "a1", "Default", OLD_REVISION);
const copy = profile("p2", "a1", COPY_NAME, OLD_REVISION);
const newerCopyOption = { ...option("p2", NEW_REVISION), enabled: false };
const initial = stateWith([agent("a1", staleProfile)], [newerCopyOption]);
const next = applyProfileDuplicated(initial, agent("a1"), copy);
const options = next.agentProfiles.items.filter((o) => o.id === "p2");
expect(options).toHaveLength(1);
expect(options[0].enabled).toBe(false);
expect(options[0].updatedAt).toBe(NEW_REVISION);
});
it("orders revisions by instant, not lexically, for offset timestamps", () => {
// "2026-08-11T23:30:00+02:00" is 21:30 UTC — OLDER than 22:00Z, but
// lexically larger. A string compare would keep the stale duplicate
// response over the newer WS-delivered option.
const staleCreated = profile("p2", "a1", COPY_NAME, "2026-08-11T23:30:00+02:00");
const newerOrphan = option("p2", "2026-08-11T22:00:00Z");
const initial = stateWith([], [newerOrphan]);
const next = applyProfileDuplicated(initial, agent("a1"), staleCreated);
const options = next.agentProfiles.items.filter((o) => o.id === "p2");
expect(options).toHaveLength(1);
expect(options[0].updatedAt).toBe("2026-08-11T22:00:00Z");
});
it("keeps a newer WS-delivered version instead of the stale duplicate response", () => {
// Another tab edited the copy after creation: agent.profile.updated
// delivered the newer version before this delayed duplicate response.
const newer = profile("p2", "a1", "Default Copy (edited)", NEW_REVISION);
const staleCreated = profile("p2", "a1", COPY_NAME, OLD_REVISION);
const source = profile("p1", "a1");
const initial = stateWith([agent("a1", source, newer)], [option("p1"), option("p2")]);
const next = applyProfileDuplicated(initial, agent("a1"), staleCreated);
const stored = next.settingsAgents.items.find((a) => a.id === "a1")?.profiles ?? [];
expect(stored.find((p) => p.id === "p2")?.name).toBe("Default Copy (edited)");
expect(next.agentProfiles.items.find((o) => o.id === "p2")?.label).toContain(
"Default Copy (edited)",
);
});
it("preserves WS-delivered orphan options for agents absent from the store", () => {
// p-orphan was delivered by WS for an agent not present in settingsAgents;
// duplicating a profile of a DIFFERENT agent must not wipe it.
const source = profile("p1", "a2");
const copy = profile("p2", "a2", COPY_NAME);
const initial = stateWith([agent("a2", source)], [option("p-orphan")]);
const next = applyProfileDuplicated(initial, agent("a2"), copy);
const ids = next.agentProfiles.items.map((o) => o.id);
expect(ids).toContain("p-orphan");
expect(ids).toContain("p2");
expect(ids.filter((id) => id === "p2")).toHaveLength(1);
});
});
@@ -0,0 +1,116 @@
"use client";
import { useCallback, useRef } from "react";
import { duplicateAgentProfileAction } from "@/app/actions/agents";
import { useAppStoreApi } from "@/components/state-provider";
import { useToast } from "@/components/toast-provider";
import { t as translate } from "@/lib/i18n";
import {
compareTimestamps,
mergeOptionsByNewest,
toAgentProfileOption,
type AgentProfileOption,
} from "@/lib/state/slices/settings/types";
import type { AppState } from "@/lib/state/store";
import type { Agent, AgentProfile } from "@/lib/types/http";
type ProfileState = Pick<AppState, "settingsAgents" | "agentProfiles">;
/**
* Merge one duplicated profile into the latest store state. Dedupes by ID so
* a concurrent `agent.profile.created` WS delivery cannot double-insert the
* copy into either slice.
*
* The options slice is rebuilt from `settingsAgents` by ID on top of the
* existing options: options the rebuild does not represent (e.g. profiles the
* WS handler delivered for agents temporarily absent from `settingsAgents`)
* are preserved, and the new copy always appears exactly once — via the
* rebuild when its owning agent is present, otherwise via a stub so it is
* never dropped.
*
* A stale duplicate HTTP response never clobbers a newer profile: when the
* copy already exists in the store (e.g. another tab edited it and
* `agent.profile.updated` arrived first), the newer `updatedAt` wins.
*/
export function applyProfileDuplicated(
state: ProfileState,
agent: Agent,
created: AgentProfile,
): ProfileState {
const nextAgents = state.settingsAgents.items.map((item: Agent) =>
item.id === agent.id
? (() => {
const existing = item.profiles.find((p) => p.id === created.id);
const latest =
existing && compareTimestamps(existing.updatedAt, created.updatedAt) > 0
? existing
: created;
return {
...item,
profiles: [...item.profiles.filter((p) => p.id !== created.id), latest],
};
})()
: item,
);
const rebuiltOptions = nextAgents.flatMap((item) =>
item.profiles.map((profile) => toAgentProfileOption(item, profile)),
);
const merged = mergeOptionsByNewest(state.agentProfiles.items, rebuiltOptions);
// The copy must appear exactly once with the known agent metadata: append
// it when absent, replace an OLDER existing option (e.g. a WS stub) with
// it, and keep a NEWER WS-delivered option untouched.
const copyOption = toAgentProfileOption({ id: agent.id, name: agent.name }, created);
const existingCopy = merged.find((option) => option.id === created.id);
let agentProfilesItems: AgentProfileOption[];
if (!existingCopy) {
agentProfilesItems = [...merged, copyOption];
} else if (compareTimestamps(existingCopy.updatedAt, created.updatedAt) > 0) {
agentProfilesItems = merged; // keep the newer WS-delivered option
} else {
agentProfilesItems = merged.map((option) => (option.id === created.id ? copyOption : option));
}
return {
settingsAgents: { ...state.settingsAgents, items: nextAgents },
agentProfiles: { ...state.agentProfiles, items: agentProfilesItems },
};
}
/**
* Duplicate a profile from the /settings/agents profile list. The returned
* copy is merged into the store atomically so the new row appears without
* waiting on the WebSocket round-trip.
*/
export function useProfileDuplicate() {
const { toast } = useToast();
const storeApi = useAppStoreApi();
// Per-profile in-flight guard: the row button stays clickable while the
// request runs, so a double-click must not issue two copies.
const pendingRef = useRef(new Set<string>());
return useCallback(
async (agent: Agent, profile: AgentProfile) => {
if (pendingRef.current.has(profile.id)) return;
pendingRef.current.add(profile.id);
try {
const created = await duplicateAgentProfileAction(profile.id);
storeApi.setState((state) => applyProfileDuplicated(state, agent, created));
toast({
title: translate("agents:duplicateProfileSuccess"),
description: created.name,
variant: "success",
});
} catch (error) {
toast({
title: translate("agents:failedToDuplicateProfile"),
description: error instanceof Error ? error.message : translate("agents:requestFailed"),
variant: "error",
});
} finally {
pendingRef.current.delete(profile.id);
}
},
[storeApi, toast],
);
}
+80 -24
View File
@@ -3,10 +3,17 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { clearNavigationBlockerForTests, setNavigationBlocker } from "./navigation-guard";
import { useParams, usePathname, useRouter, useSearchParams } from "./client-router";
const NAV_POSITION_KEY = "__kandevNavigationPosition";
function setLocation(path: string) {
window.history.replaceState({}, "", path);
}
/** Simulates a history popstate at the given location for router tests. */
function popStateAt(position: number) {
window.dispatchEvent(new PopStateEvent("popstate", { state: { [NAV_POSITION_KEY]: position } }));
}
afterEach(() => {
clearNavigationBlockerForTests();
vi.unstubAllGlobals();
@@ -61,33 +68,82 @@ describe("client router adapter", () => {
expect(reload).toHaveBeenCalledOnce();
});
it("guards imperative push and history navigation", () => {
setLocation("/settings/general/appearance");
const attempts: Array<() => void> = [];
setNavigationBlocker((intent) => attempts.push(intent.proceed));
const go = vi.spyOn(window.history, "go").mockImplementation(() => undefined);
const back = vi.spyOn(window.history, "back").mockImplementation(() => {
window.dispatchEvent(
new PopStateEvent("popstate", {
state: { __kandevNavigationPosition: 0 },
}),
);
describe("navigation guard", () => {
function setupGuardedRouter() {
setLocation("/settings/general/appearance");
const intents: Array<{ proceed: () => void; cancel: () => void }> = [];
setNavigationBlocker((intent) => intents.push(intent));
const go = vi.spyOn(window.history, "go").mockImplementation(() => undefined);
const back = vi.spyOn(window.history, "back").mockImplementation(() => popStateAt(0));
const { result } = renderHook(() => useRouter());
return { result, intents, go, back };
}
it("guards imperative push and history navigation", () => {
const { result, intents, go, back } = setupGuardedRouter();
act(() => result.current.push("/tasks"));
expect(window.location.pathname).toBe("/settings/general/appearance");
act(() => intents.shift()?.proceed());
expect(window.location.pathname).toBe("/tasks");
act(() => result.current.back());
expect(back).toHaveBeenCalledOnce();
expect(intents).toHaveLength(1);
act(() => intents.shift()?.proceed());
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
window.dispatchEvent(new PopStateEvent("popstate", { state: null }));
expect(intents).toHaveLength(0);
expect(go).toHaveBeenCalledTimes(2);
});
const { result } = renderHook(() => useRouter());
act(() => result.current.push("/tasks"));
expect(window.location.pathname).toBe("/settings/general/appearance");
it("consumes a cancelled blocked pop's restoration popstate when no newer navigation superseded it", () => {
const { result, intents, go } = setupGuardedRouter();
act(() => attempts.shift()?.());
expect(window.location.pathname).toBe("/tasks");
act(() => result.current.push("/tasks"));
act(() => intents.pop()?.proceed()); // allow the push -> currentPosition 1
act(() => result.current.back()); // blocked pop to position 0; restoration to 1 pending
expect(intents).toHaveLength(1);
act(() => result.current.back());
expect(back).toHaveBeenCalledOnce();
expect(attempts).toHaveLength(1);
act(() => attempts.shift()?.());
window.dispatchEvent(new PopStateEvent("popstate", { state: window.history.state }));
window.dispatchEvent(new PopStateEvent("popstate", { state: null }));
expect(attempts).toHaveLength(0);
expect(go).toHaveBeenCalledTimes(2);
act(() => {
intents[0].cancel(); // cancel without any newer navigation
});
// The in-flight restoration popstate for the blocked entry is consumed
// without touching currentPosition (still 1).
act(() => popStateAt(1));
// A later real back to position 0 is a fresh guarded pop (delta -1),
// not a silent acceptance.
act(() => popStateAt(0));
expect(intents).toHaveLength(2);
expect(go).toHaveBeenCalled();
});
it("forgets a cancelled blocked pop once a newer navigation supersedes it", () => {
const { result, intents, go } = setupGuardedRouter();
act(() => result.current.push("/tasks"));
act(() => intents.pop()?.proceed()); // allow the push -> currentPosition 1
act(() => result.current.back()); // blocked pop to position 0
expect(intents).toHaveLength(1);
// Duplicate-like flow: cancel, then push a new route. The push
// supersedes the pending traversal, so the browser may never emit its
// popstate; the guard must forget the cancelled restoration instead of
// arming a stale position that could eat a later navigation.
act(() => {
intents[0].cancel();
result.current.push("/settings/agents/mock-agent/profiles/copy-1");
intents.pop()?.proceed(); // allow the duplicate push -> currentPosition 2
});
// A popstate to the blocked entry's position arrives late (or is a
// real back): it must be treated as a fresh guarded pop (delta -1 from
// position 2), not consumed as stale.
act(() => popStateAt(1));
expect(intents).toHaveLength(2);
expect(go).toHaveBeenCalled();
});
});
});
+28 -1
View File
@@ -13,6 +13,11 @@ let popstateInstalled = false;
let historyMutationsTracked = false;
let allowedPop = false;
let restoringPop = false;
// Position of a blocked-pop restoration whose traversal is still in flight
// when the intent was cancelled. The delayed popstate for that position must
// be consumed without touching currentPosition, so a newer navigation (e.g. a
// push performed right after cancel) is not clobbered.
let canceledRestorationPosition: number | null = null;
type BlockedPop = {
delta: number;
@@ -96,6 +101,7 @@ export function clearNavigationBlockerForTests(): void {
allowedPop = false;
restoringPop = false;
blockedPop = null;
canceledRestorationPosition = null;
}
function ensureHistoryTracking(): void {
@@ -132,6 +138,14 @@ function handlePopState(event: PopStateEvent): void {
return;
}
if (targetPosition === canceledRestorationPosition) {
// Popstate for a blocked-pop restoration whose intent was cancelled: a
// newer navigation may have happened since, so consume it without
// updating currentPosition.
canceledRestorationPosition = null;
return;
}
if (allowedPop) {
allowedPop = false;
currentPosition = targetPosition;
@@ -172,6 +186,7 @@ function blockPop(event: PopStateEvent, delta: number, restorePosition: number):
};
blockedPop = pending;
restoringPop = true;
canceledRestorationPosition = null; // a new block supersedes any stale one
window.history.go(-delta);
blocker({
@@ -189,11 +204,16 @@ function trackNativeHistoryMutations(): void {
const position = readPosition(state) ?? (currentPosition ?? 0) + 1;
pushState(withPosition(state, position), title, url);
currentPosition = position;
// A new navigation supersedes any blocked-pop traversal still in flight;
// without this the cancelled restoration position could eat a later
// legitimate popstate to the same position.
canceledRestorationPosition = null;
};
window.history.replaceState = (state, title, url) => {
const position = readPosition(state) ?? currentPosition ?? 0;
replaceState(withPosition(state, position), title, url);
currentPosition = position;
canceledRestorationPosition = null;
};
}
@@ -211,7 +231,14 @@ function proceedBlockedPop(pending: BlockedPop): void {
function cancelBlockedPop(pending: BlockedPop): void {
if (blockedPop !== pending) return;
pending.canceled = true;
if (pending.restored) blockedPop = null;
if (!pending.restored) {
// The history.go(-delta) restoration is still in flight. Its popstate
// must not overwrite a newer currentPosition (e.g. a push performed
// right after cancel), so consume that exact position when it arrives.
canceledRestorationPosition = pending.restorePosition;
restoringPop = false;
}
blockedPop = null;
}
function finishPopRestoration(): void {
@@ -60,6 +60,9 @@ export type AgentProfileOption = {
/** Legacy automatic-fallback opt-in. */
auto_fallback?: boolean;
workspace_id?: string;
/** Persisted profile revision (RFC3339 updated_at), used to prefer newer
* WS-delivered options over a stale in-flight response. */
updatedAt?: string;
/**
* False hides the profile from task/session creation pickers. Existing
* sessions keep their labels and the profile stays editable in settings.
@@ -79,10 +82,53 @@ export function isSelectableAgentProfile(profile: Pick<AgentProfileOption, "enab
return profile.enabled !== false;
}
/**
* Compares two RFC3339 timestamps as instants (millisecond precision).
* Lexical comparison misorders values with fractional seconds or differing
* offsets (e.g. `10:00:00.100Z` is newer than `10:00:00Z` but sorts before
* it), so revision precedence must parse the instants. Missing timestamps
* sort oldest so a present timestamp always wins.
*/
export function compareTimestamps(a: string | undefined, b: string | undefined): number {
if (a === b) return 0;
if (a === undefined || a === "") return -1;
if (b === undefined || b === "") return 1;
const aMs = Date.parse(a);
const bMs = Date.parse(b);
if (Number.isNaN(aMs)) return -1;
if (Number.isNaN(bMs)) return 1;
return aMs - bMs;
}
/**
* Merge two option lists by ID, keeping the NEWER revision per id (missing or
* equal updatedAt defers to the rebuilt option). A newer WebSocket-delivered
* option must never be regressed by a stale list rebuild — e.g. a disabled
* profile whose option was updated by `agent.profile.updated` while its owning
* agent was absent must not reappear as selectable.
*/
export function mergeOptionsByNewest(
previous: AgentProfileOption[],
rebuilt: AgentProfileOption[],
): AgentProfileOption[] {
const byId = new Map<string, AgentProfileOption>();
for (const option of previous) {
byId.set(option.id, option);
}
for (const option of rebuilt) {
const existing = byId.get(option.id);
if (!existing || compareTimestamps(option.updatedAt, existing.updatedAt) >= 0) {
byId.set(option.id, option);
}
}
return [...byId.values()];
}
/** Single source of truth for mapping an API Agent+Profile to a store AgentProfileOption. */
export function toAgentProfileOption(
agent: Pick<Agent, "id" | "name" | "capability_status" | "capability_error">,
profile: Pick<AgentProfile, "id" | "agentDisplayName" | "name" | "workspaceId"> & {
updatedAt?: string;
cliPassthrough?: boolean;
model?: string;
fallbackModel?: string;
@@ -100,6 +146,7 @@ export function toAgentProfileOption(
fallback_model: profile.fallbackModel ?? undefined,
auto_fallback: profile.autoFallback ?? undefined,
workspace_id: profile.workspaceId,
updatedAt: profile.updatedAt,
enabled: profile.enabled ?? true,
capability_status: agent.capability_status,
capability_error: agent.capability_error,
+205 -8
View File
@@ -13,23 +13,62 @@ function makeStore() {
) as unknown as StoreApi<AppState>;
}
function message(action: string, payload: unknown) {
const TIMESTAMP = "2026-07-26T10:00:00Z";
const NOTIFICATION_TYPE = "notification";
const PROFILE_CREATED = "agent.profile.created";
const PROFILE_UPDATED = "agent.profile.updated";
const PROFILE_DELETED = "agent.profile.deleted";
/** Builds a WS notification message fixture with the given action, payload, and timestamp. */
function message(action: string, payload: unknown, timestamp = TIMESTAMP) {
return {
id: `message-${action}`,
type: "notification",
type: NOTIFICATION_TYPE,
action,
timestamp: "2026-07-26T10:00:00Z",
timestamp,
payload,
};
}
describe("agent runtime update websocket handlers", () => {
/** Builds a kanban profile payload fixture, overridable per test. */
function profilePayload(overrides: Record<string, unknown> = {}) {
return {
id: "p1",
agent_id: "agent-1",
name: "Default",
model: "mock-fast",
enabled: true,
created_at: TIMESTAMP,
updated_at: TIMESTAMP,
...overrides,
};
}
/** Builds an office-scoped profile payload fixture (workspace_id set). */
function officeProfilePayload() {
return {
id: "profile-office",
agent_id: "agent-1",
name: "Office Agent",
workspace_id: "ws-1",
enabled: true,
created_at: TIMESTAMP,
updated_at: TIMESTAMP,
};
}
/** Registers the agents WS handlers and returns them keyed by action. */
function handlersFor(store: ReturnType<typeof makeStore>) {
return registerAgentsHandlers(store) as unknown as Record<
string,
(event: ReturnType<typeof message>) => void
>;
}
describe("agent update job websocket handlers", () => {
it("upserts update snapshots and appends each output chunk once", () => {
const store = makeStore();
const handlers = registerAgentsHandlers(store) as unknown as Record<
string,
(event: ReturnType<typeof message>) => void
>;
const handlers = handlersFor(store);
const snapshot = {
job_id: "update-1",
agent_name: "claude-acp",
@@ -64,3 +103,161 @@ describe("agent runtime update websocket handlers", () => {
).toMatchObject({ status: "succeeded", output: "downloaded\n" });
});
});
describe("agent profile events", () => {
it("ignores office-scoped profile events so they never leak into global settings", () => {
const store = makeStore();
const handlers = handlersFor(store);
// The backend wraps the profile under { profile: ... } in the event.
const payload = { profile: officeProfilePayload() };
handlers[PROFILE_CREATED](message(PROFILE_CREATED, payload));
handlers[PROFILE_UPDATED](message(PROFILE_UPDATED, payload));
const state = store.getState();
expect(state.agentProfiles.items).toHaveLength(0);
expect(state.settingsAgents.items).toHaveLength(0);
});
it("does not let a delayed profile event overwrite newer stored state", () => {
const store = makeStore();
const handlers = handlersFor(store);
const newer = profilePayload({ model: "new-model", updated_at: "2026-07-26T11:00:00Z" });
handlers[PROFILE_CREATED](message(PROFILE_CREATED, { profile: newer }, "2026-07-26T11:05:00Z"));
// A delayed older event (e.g. a replayed duplicate response) must not
// regress the newer revision.
const older = profilePayload({ model: "stale-model", updated_at: "2026-07-26T09:00:00Z" });
handlers[PROFILE_UPDATED](message(PROFILE_UPDATED, { profile: older }, "2026-07-26T11:04:00Z"));
const stored = store.getState().agentProfiles.items[0];
expect(stored?.model).toBe("new-model");
});
it("does not resurrect a deleted profile from a delayed create event", () => {
const store = makeStore();
const handlers = handlersFor(store);
handlers[PROFILE_CREATED](
message(PROFILE_CREATED, { profile: profilePayload() }, "2026-07-26T10:00:00Z"),
);
expect(store.getState().agentProfiles.items).toHaveLength(1);
handlers[PROFILE_DELETED](
message(PROFILE_DELETED, { profile: profilePayload() }, "2026-07-26T12:00:00Z"),
);
expect(store.getState().agentProfiles.items).toHaveLength(0);
// A create event produced BEFORE the deletion is stale: no resurrection.
handlers[PROFILE_CREATED](
message(PROFILE_CREATED, { profile: profilePayload() }, "2026-07-26T11:00:00Z"),
);
expect(store.getState().agentProfiles.items).toHaveLength(0);
// A genuinely newer create (after the deletion) wins and clears the
// tombstone.
handlers[PROFILE_CREATED](
message(
"agent.profile.created",
{ profile: profilePayload({ updated_at: "2026-07-26T13:00:00Z" }) },
"2026-07-26T13:00:00Z",
),
);
expect(store.getState().agentProfiles.items).toHaveLength(1);
});
it("ignores office-scoped delete events", () => {
const store = makeStore();
const handlers = handlersFor(store);
handlers[PROFILE_DELETED](message(PROFILE_DELETED, { profile: officeProfilePayload() }));
expect(store.getState().agentProfiles.items).toHaveLength(0);
expect(store.getState().settingsAgents.items).toHaveLength(0);
});
});
describe("agent profile event ordering", () => {
it("ignores a stale delete event when a newer revision already exists", () => {
const store = makeStore();
const handlers = handlersFor(store);
const current = profilePayload({
id: "p-stale",
model: "new-model",
updated_at: "2026-07-26T11:00:00Z",
});
handlers[PROFILE_CREATED](
message(PROFILE_CREATED, { profile: current }, "2026-07-26T11:05:00Z"),
);
expect(store.getState().agentProfiles.items).toHaveLength(1);
// A delayed delete carrying an OLDER snapshot than the stored revision
// must not remove the current profile.
const staleDelete = profilePayload({
id: "p-stale",
model: "new-model",
updated_at: TIMESTAMP,
});
handlers[PROFILE_DELETED](
message(PROFILE_DELETED, { profile: staleDelete }, "2026-07-26T11:02:00Z"),
);
const state = store.getState();
expect(state.agentProfiles.items).toHaveLength(1);
expect(state.agentProfiles.items[0]?.model).toBe("new-model");
// A genuinely newer delete (after the stored revision) still applies.
handlers[PROFILE_DELETED](
message(PROFILE_DELETED, { profile: current }, "2026-07-26T12:00:00Z"),
);
expect(store.getState().agentProfiles.items).toHaveLength(0);
});
it("orders revisions by instant, not lexically, for fractional-second timestamps", () => {
const store = makeStore();
const handlers = handlersFor(store);
// Lexically "…10:00:00Z" sorts AFTER "…10:00:00.100Z", so a naive string
// compare would treat the whole-second revision as newer and regress it.
const fractional = profilePayload({
id: "p-frac",
model: "fractional-model",
updated_at: "2026-07-26T10:00:00.100Z",
});
handlers[PROFILE_CREATED](
message(PROFILE_CREATED, { profile: fractional }, "2026-07-26T10:00:00.100Z"),
);
const wholeSecond = profilePayload({
id: "p-frac",
model: "whole-second-model",
updated_at: TIMESTAMP,
});
handlers[PROFILE_UPDATED](message(PROFILE_UPDATED, { profile: wholeSecond }));
expect(store.getState().agentProfiles.items[0]?.model).toBe("fractional-model");
});
it("keeps the tombstone ordered by instant for fractional-second deletes", () => {
const store = makeStore();
const handlers = handlersFor(store);
handlers[PROFILE_CREATED](
message(PROFILE_CREATED, { profile: profilePayload({ id: "p-tomb" }) }),
);
// Delete at a fractional second; the tombstone must beat a whole-second
// create produced before it.
handlers[PROFILE_DELETED](
message(
PROFILE_DELETED,
{ profile: profilePayload({ id: "p-tomb" }) },
"2026-07-26T10:00:00.100Z",
),
);
expect(store.getState().agentProfiles.items).toHaveLength(0);
handlers[PROFILE_CREATED](
message(
PROFILE_CREATED,
{ profile: profilePayload({ id: "p-tomb" }) },
"2026-07-26T10:00:00.050Z",
),
);
expect(store.getState().agentProfiles.items).toHaveLength(0);
});
});
+121 -22
View File
@@ -1,7 +1,7 @@
import type { StoreApi } from "zustand";
import type { AppState } from "@/lib/state/store";
import type { WsHandlers } from "@/lib/ws/handlers/types";
import { toAgentProfileOption } from "@/lib/state/slices/settings/types";
import { compareTimestamps, toAgentProfileOption } from "@/lib/state/slices/settings/types";
import { normalizeAgentProfile } from "@/lib/api/domains/agent-profile-normalize";
import type { AgentProfile } from "@/lib/types/agent-profile";
@@ -15,8 +15,78 @@ function getAgentId(raw: unknown): string {
return typeof value === "string" ? value : "";
}
function handleProfileCreated(state: AppState, profile: unknown): Partial<AppState> {
/**
* Office-scoped profiles are owned by the office channels, never the kanban
* settings surface (the HTTP agent list hides them via filterGlobalProfiles).
* Defense in depth: ignore their events here so a stray broadcast cannot leak
* them into the global settings store and selectors.
*/
function isOfficeScoped(normalized: { workspaceId?: string }): boolean {
return Boolean(normalized.workspaceId);
}
/** Finds a profile in the settings agents list by id, across all agents. */
function findExistingProfile(state: AppState, profileId: string): AgentProfile | undefined {
for (const item of state.settingsAgents.items) {
const found = item.profiles.find((p) => p.id === profileId);
if (found) return found;
}
return undefined;
}
// Deletion tombstones keyed by profile id -> deletion event timestamp, so a
// delayed create/update event cannot resurrect a profile that was deleted
// after the event was produced. Cleared when a genuinely newer create arrives.
// Tombstones are keyed by UUID and profiles are never recreated under the same
// ID, so the map is bounded by the number of profiles deleted in this session
// (typically single digits to low dozens — no eviction needed).
const deletionTombstones = new Map<string, string>();
/**
* A profile event is stale when the store already holds a newer revision of
* the profile or its option (e.g. a delayed duplicate response or a newer
* WebSocket update arrived first), or when the profile was deleted after the
* event was produced (tombstone). Events must never regress newer state.
* Missing event timestamps (never produced by the backend) are treated as
* not-stale so they cannot trip the guards.
*/
function isStaleProfileEvent(
state: AppState,
normalized: { id: string; updatedAt?: string },
eventTimestamp: string | undefined,
): boolean {
const tombstone = deletionTombstones.get(normalized.id);
if (
tombstone !== undefined &&
eventTimestamp &&
compareTimestamps(tombstone, eventTimestamp) >= 0
) {
return true;
}
const existingProfile = findExistingProfile(state, normalized.id);
if (existingProfile && compareTimestamps(existingProfile.updatedAt, normalized.updatedAt) > 0) {
return true;
}
const existingOption = state.agentProfiles.items.find((o) => o.id === normalized.id);
return Boolean(
existingOption && compareTimestamps(existingOption.updatedAt, normalized.updatedAt) > 0,
);
}
/**
* Applies an agent.profile.created event, skipping office-scoped or stale
* events (see isStaleProfileEvent) and clearing the deletion tombstone when a
* genuinely newer create arrives.
*/
function handleProfileCreated(
state: AppState,
profile: unknown,
eventTimestamp: string | undefined,
): Partial<AppState> {
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 ?? "" };
@@ -41,8 +111,18 @@ function handleProfileCreated(state: AppState, profile: unknown): Partial<AppSta
};
}
function handleProfileUpdated(state: AppState, profile: unknown): Partial<AppState> {
/**
* Applies an agent.profile.updated event, skipping office-scoped or stale
* events so a delayed update never regresses newer stored state.
*/
function handleProfileUpdated(
state: AppState,
profile: unknown,
eventTimestamp: string | undefined,
): Partial<AppState> {
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 ?? "" };
@@ -63,6 +143,41 @@ function handleProfileUpdated(state: AppState, profile: unknown): Partial<AppSta
};
}
/**
* Applies an agent.profile.deleted event: removes the profile from both
* slices and records a deletion tombstone (keyed by the event timestamp) so a
* delayed create/update cannot resurrect it. Office-scoped and stale deletes
* (a delete whose snapshot is older than the stored revision — e.g. a delayed
* event after a newer update already applied) are ignored so the handler
* never regresses newer state.
*/
function handleProfileDeleted(
state: AppState,
profile: unknown,
eventTimestamp: string | undefined,
): Partial<AppState> {
const normalized = normalizeAgentProfile(profile);
if (isOfficeScoped(normalized)) return {};
if (isStaleProfileEvent(state, normalized, eventTimestamp)) return {};
if (eventTimestamp) deletionTombstones.set(normalized.id, eventTimestamp);
const agentId = getAgentId(profile);
const nextAgents = state.settingsAgents.items.map((item) =>
item.id === agentId
? {
...item,
profiles: item.profiles.filter((p) => p.id !== normalized.id),
}
: item,
);
return {
agentProfiles: {
...state.agentProfiles,
items: state.agentProfiles.items.filter((p) => p.id !== normalized.id),
},
settingsAgents: { items: nextAgents },
};
}
export function registerAgentsHandlers(store: StoreApi<AppState>): WsHandlers {
return {
"agent.available.updated": (message) => {
@@ -118,35 +233,19 @@ export function registerAgentsHandlers(store: StoreApi<AppState>): WsHandlers {
"agent.profile.created": (message) => {
store.setState((state) => ({
...state,
...handleProfileCreated(state, message.payload.profile),
...handleProfileCreated(state, message.payload.profile, message.timestamp),
}));
},
"agent.profile.updated": (message) => {
store.setState((state) => ({
...state,
...handleProfileUpdated(state, message.payload.profile),
...handleProfileUpdated(state, message.payload.profile, message.timestamp),
}));
},
"agent.profile.deleted": (message) => {
const profile = message.payload.profile as Record<string, unknown>;
const profileId = profile.id as string;
const agentId = getAgentId(profile);
store.setState((state) => ({
...state,
agentProfiles: {
...state.agentProfiles,
items: state.agentProfiles.items.filter((p) => p.id !== profileId),
},
settingsAgents: {
items: state.settingsAgents.items.map((item) =>
item.id === agentId
? {
...item,
profiles: item.profiles.filter((p) => p.id !== profileId),
}
: item,
),
},
...handleProfileDeleted(state, message.payload.profile, message.timestamp),
}));
},
};
+6 -1
View File
@@ -214,5 +214,10 @@
"watcherKindGithubIssue": "GitHub Issues",
"watcherKindGithubReview": "GitHub PR Reviews",
"watcherKindJira": "Jira",
"watcherKindLinear": "Linear"
"watcherKindLinear": "Linear",
"duplicate": "Duplicate",
"duplicateProfileNamed": "Duplicate {{name}}",
"duplicateProfileSuccess": "Profile duplicated",
"duplicateSaveBlocked": "Settings are still saving. Try again in a moment.",
"failedToDuplicateProfile": "Failed to duplicate profile"
}
+6 -1
View File
@@ -214,5 +214,10 @@
"watcherKindGithubIssue": "ĜĩţĤũƀ Ĩśśũēś",
"watcherKindGithubReview": "ĜĩţĤũƀ ƤŔ Ŕēvĩēŵś",
"watcherKindJira": "Ĵĩŕà",
"watcherKindLinear": "Ĺĩńēàŕ"
"watcherKindLinear": "Ĺĩńēàŕ",
"duplicate": "Ďũƥĺĩćàţē",
"duplicateProfileNamed": "Ďũƥĺĩćàţē {{name}}",
"duplicateProfileSuccess": "Ƥŕōƒĩĺē ďũƥĺĩćàţēď",
"duplicateSaveBlocked": "Śēţţĩńĝś àŕē śţĩĺĺ śàvĩńĝ. Ţŕŷ àĝàĩń ĩń à ḿōḿēńţ.",
"failedToDuplicateProfile": "Ƒàĩĺēď ţō ďũƥĺĩćàţē ƥŕōƒĩĺē"
}
+256
View File
@@ -0,0 +1,256 @@
---
spec: docs/specs/agents/profile-duplicate.md
created: 2026-08-11
status: complete
---
# Implementation Plan: Agent Profile Duplicate
## Overview
Add a one-click "duplicate" for agent profiles on the settings agents surface
(`/settings/agents` profile list and the per-profile settings page). A new
interlock-protected endpoint `POST /api/v1/agent-profiles/:id/duplicate`
copies the source profile's full configuration (model, mode, config options,
CLI flags, env vars, launcher prefix, auto-approve flags, enabled state, MCP
config row) into a fresh row named `<source> Copy`, broadcasts the existing
`agent.profile.created` WS event, and returns the new profile DTO.
## Backend
### Controller: `DuplicateProfile`
Add to `apps/backend/internal/agent/settings/controller/profile_crud.go`:
- `type DuplicateProfileRequest struct { ID string }`.
- `func (c *Controller) DuplicateProfile(ctx, req) (*dto.AgentProfileDTO, error)`:
1. `repo.GetAgentProfile(ctx, req.ID)`; map the "agent profile not found"
error to `ErrAgentProfileNotFound` exactly like `DeleteProfile` does
(the sqlite store wraps `sql.ErrNoRows` in a message containing
"agent profile not found").
2. Build a fresh `models.AgentProfile` copying every configuration field:
`AgentID`, `AgentDisplayName`, `Model`, `FallbackModel` (trimmed),
`AutoFallback`, `Mode`, `ConfigOptions` (through
`profileconfig.SanitizeConfigOptions` on a copied map),
`AllowIndexing`, `AutoApprove`, `CLIPassthrough`, `CLIFlags` (deep
copy of the slice), `EnvVars` (deep copy of the slice, keeping
`SecretID` refs), `CommandPrefix`, `UserModified: true`, and the office
enrichment configuration fields (`WorkspaceID`, `Role`, `Icon`,
`ReportsTo`, `SkillIDs`, `DesiredSkills`, `MaxConcurrentSessions`,
`CooldownSec`, `SkipIdleRuns`, `FailureThreshold` (copied pointer),
`ExecutorPreference`, `BudgetMonthlyCents`, `Settings`, `Permissions`).
Do NOT copy runtime state: `Status`, `PauseReason`, `LastRunFinishedAt`,
`ConsecutiveFailures`, `DeletedAt`, `MigratedFrom`, `CustomPrompt`,
`DangerouslySkipPermissions`.
3. Name: `strings.TrimSpace(source.Name) + " Copy"`. The name is persisted
data, not UI copy (same convention as seeded executor/repository names),
so the suffix is a plain string in Go.
4. Read the source's MCP config row when it has one (`repo
.GetAgentProfileMcpConfig(ctx, source.ID)`; tolerate `sql.ErrNoRows` /
nil); deep-copy `Servers` and `Meta` into a fresh
`models.AgentProfileMcpConfig` (ProfileID filled by the repo). A source
without a row leaves the copy without one — the default-config
semantics and boot `EnsureDefaultMcpConfig` cover MCP-supporting
agents.
5. `repo.DuplicateAgentProfile(ctx, store.DuplicateAgentProfileInput{...})`
— NEW atomic repository operation (adversarial review round 1): one
transaction inserts the row with the caller-provided `Enabled` state
(NOT forced true like `CreateAgentProfile`, so a disabled source never
becomes briefly selectable) and upserts the MCP config row. A failure
rolls back, leaving no partial copy. Rollback makes each attempt
atomic, but the endpoint is not HTTP-idempotent: a retried request
creates another row (the UI guards against double-clicks). The store
assigns the fresh UUID and a single `CreatedAt`/`UpdatedAt` pair,
which the returned DTO reflects (no stale timestamp after a second
write).
6. **Consistent snapshot (adversarial review round 5):** inside the
transaction the repository re-reads the source profile and MCP rows and
verifies their `updated_at` still match the revisions the copy was
built from (`ErrProfileChanged` / `ErrSourceProfileNotFound` otherwise);
WAL snapshot isolation aborts the write with a busy error if a
concurrent writer commits between the verification and the insert. The
controller retries (bounded, `maxDuplicateRetries = 2`) on
`ErrProfileChanged` / `ErrSourceProfileNotFound` / busy errors with a
fresh source read, so the copy always reflects one consistent snapshot.
7. Return `toProfileDTO(clone)`.
Env-var secret refs are copied verbatim; they were validated when the source
was created/updated, so no re-validation is needed.
### Handler + route
In `apps/backend/internal/agent/settings/handlers/handlers.go`:
- Register `api.POST("/agent-profiles/:id/duplicate", h.interlock,
h.httpDuplicateProfile)` next to the other `/agent-profiles/:id` routes.
- `httpDuplicateProfile`: require `:id`, call
`controller.DuplicateProfile`, map `ErrAgentProfileNotFound` → 404, other
errors → 500; on success broadcast
`ws.ActionAgentProfileCreated` with `{"profile": resp}` (same payload
shape as `httpCreateProfile`) and return the DTO with 200.
### Tests (backend)
- Controller, new file
`apps/backend/internal/agent/settings/controller/profile_duplicate_test.go`
(using the existing `newTestController` + `newFakeStore`):
- full-config copy: source with model/fallback/mode/config options/CLI
flags/env vars/command prefix/auto-approve/cli-passthrough duplicates
with equal fields, new ID, `Default Copy` name, `user_modified` true;
- disabled source → disabled copy stored in the single atomic write (no
follow-up enabled flip, timestamps match the stored row);
- MCP config row copied to the new profile ID with equal enabled/servers/meta
(extend the shared `fakeStore` in `reconciler_test.go` with an
`mcpConfigs` map + working `GetAgentProfileMcpConfig` /
`UpsertAgentProfileMcpConfig` + `DuplicateAgentProfile`, additively —
other tests only observe the existing nil behaviour);
- store failure propagates and leaves no partial copy;
- unknown ID → `ErrAgentProfileNotFound`;
- empty source name (`""` → `" Copy"` is acceptable; source names are
non-empty by validation, but pin the suffix behaviour).
- Store, new file `apps/backend/internal/agent/settings/store/sqlite_duplicate_test.go`:
sqlite `DuplicateAgentProfile` round-trip — fresh ID, full configuration
preserved, disabled copy stays disabled (not forced enabled), MCP row
copied, source untouched; no MCP row created when none passed.
- Handler, `apps/backend/internal/agent/settings/handlers/interim_settings_interlock_test.go`:
add `{method: POST, path: "/api/v1/agent-profiles/profile-1/duplicate"}`
to the route list that must return 403 without the interlock token.
- Handler test (mandatory, adversarial review round 9): an office-scoped
source (`WorkspaceID != ""`) returns 404 with zero broadcasts on any
channel — global or workspace-scoped — and the office profile is rejected
before MCP config is read or written. Also assert 404 mapping and the
`agent.profile.created` broadcast for kanban profiles, following
`agent_update_handlers_test.go`'s controller-stub pattern.
## Frontend
### API action
In `apps/web/app/actions/agents.ts` add:
```ts
export async function duplicateAgentProfileAction(profileId: string): Promise<AgentProfile> {
const raw = await agentSettingsRequest<unknown>(
`${apiBaseUrl}/api/v1/agent-profiles/${profileId}/duplicate`,
{ method: "POST" },
);
return normalizeAgentProfile(raw);
}
```
### List page: per-row Duplicate button
- `apps/web/app/settings/agents/profile-list-item.tsx`: accept an
`onDuplicate: (profile: AgentProfile) => void` prop; render an icon-only
button (copy icon, e.g. `IconCopy` from `@tabler/icons-react`) outside the
link, next to the enabled switch, with `aria-label` / tooltip via
`t("agents:duplicateProfileNamed", { name: profile.name })` and
`data-testid={`duplicate-profile-${profile.id}`}`.
- `apps/web/app/settings/agents/page.tsx`: thread `onDuplicate` through
`AgentProfilesSection`; add a `handleDuplicateProfile` wired like
`useProfileEnabledToggle` (POST via the action, then merge the returned
profile into `settingsAgents` + `agentProfiles` store slices atomically via
`useAppStoreApi().setState`, appending the new profile to its agent's
`profiles`; toast success/failure via `agents:duplicateProfileSuccess` /
`agents:failedToDuplicateProfile`). The `agent.profile.created` WS handler
already upserts the same profile; the direct merge keeps the UI consistent
even if WS is delayed. The merge (`applyProfileDuplicated` in
`use-profile-duplicate.ts`) dedupes by ID, preserves WS-delivered options
whose owning agent is absent, never lets a stale duplicate response clobber
a newer `agent.profile.updated` version (newer `updatedAt` wins), and
always rebuilds the copy option with the known agent metadata.
### Profile settings page: header Duplicate button
- `apps/web/components/settings/agent-profile-page.tsx`: add a Duplicate
button to `ProfileEditorHeader` (copy icon + `t("agents:duplicate")`,
`data-testid="duplicate-profile-header"`, disabled + `aria-busy` while a
duplicate is in flight). The flow lives in the extracted
`useProfileDuplicateAction` hook
(`components/settings/agent-profile-duplicate-action.ts`, unit-tested):
a ref-based in-flight guard (two rapid clicks can never issue two
copies), then save EVERY dirty contributor via the shared settings save
coordinator (`useSettingsSaveCoordinator().saveAll` — the profile editor
AND its MCP card; `saveAll` respects each contributor's `canSave`, and the
abort toasts the blocking contributor's `invalidReason` — MCP error or
profile-name validation), POST the duplicate, merge the copy into the
store, toast `agents:duplicateProfileSuccess`, cancel any pending
navigation intent the dirty guard had blocked, and SPA-navigate via
`runWithNavigationBlockerBypassed(() => router.push(...))` — never
`window.location.assign`, so the success toast survives and the
dirty-settings blocker is already resolved by the save. The row-level
duplicate hook guards against double-clicks (per-profile in-flight set).
The profile save path (`syncAgentsToStore`) reconciles the options slice
by ID (`reconcileAgentProfileOptions`), preserving WS-delivered orphan
options exactly like the duplicate merge. The merge keeps a newer
WS-delivered orphan option (revision carried on the option as `updatedAt`)
over a stale duplicate HTTP response, matching the newer-wins rule used
when the owning agent is present.
### i18n
Add to `apps/web/src/locales/en/agents.json`:
- `"duplicate": "Duplicate"`
- `"duplicateProfile": "Duplicate profile"`
- `"duplicateProfileNamed": "Duplicate {{name}}"`
- `"duplicateProfileSuccess": "Profile duplicated"`
- `"failedToDuplicateProfile": "Failed to duplicate profile"`
Regenerate the pseudo locale (`pnpm --filter @kandev/web i18n:pseudo`). Real
locales (`zh-cn`, `pt-pt`) fall back to en; key-parity is a warning there,
missing en keys are a hard error.
### Tests (frontend)
- `apps/web/app/settings/agents/profile-list-item.test.tsx`: extend with a
case asserting the Duplicate button renders and calls `onDuplicate` with
the profile (mirroring the existing toggle tests).
- `apps/web/lib/api/domains/agent-profile-normalize.test.ts` or the actions
layer: only if an existing action-test pattern exists; otherwise the
component test plus E2E covers the contract.
## E2E
New `apps/web/e2e/tests/settings/agent-profile-duplicate.spec.ts` modeled on
`agent-profile-delete.spec.ts`:
- Create a source profile via `apiClient.createAgentProfile(agent.id,
"Dup Me", { model: agent.profiles[0].model, cli_flags: [...], command_prefix: ... })`.
- `testPage.goto("/settings/agents")`, wait for the profile list, click the
duplicate button on the "Dup Me" row (`duplicate-profile-<id>`).
- Expect a "Dup Me Copy" row to appear without reload.
- Navigate to the copy's profile page and assert the copied model/cli flag
values render.
- `finally`: delete both profiles via `apiClient.deleteAgentProfile(..., true)`.
## Implementation Waves
Execution is sequential in the primary conversation; no subagents are
authorized.
Wave 1:
- [x] [Task 01: Backend duplicate endpoint](task-01-backend-duplicate-endpoint.md)
Wave 2:
- [x] [Task 02: Frontend duplicate UI](task-02-frontend-duplicate-ui.md)
Wave 3:
- [x] [Task 03: E2E duplicate flow](task-03-duplicate-e2e.md)
## Risks
- `DuplicateAgentProfile` inserts the copy with the caller-provided enabled
state inside one transaction, unlike `CreateAgentProfile` which forces
`Enabled=true` for other callers — a store regression that forces the
duplicate enabled is pinned by `sqlite_duplicate_test.go` (disabled copy
stays disabled) and by the controller test asserting no follow-up write.
- `GetAgentProfileMcpConfig` returns different "absent" shapes across the
sqlite store (`sql.ErrNoRows`) and the shared fake store (`nil, nil`);
the controller must tolerate both.
- The list-page direct store merge and the WS `agent.profile.created`
broadcast can both insert the copy; the WS handler upserts by ID so this
is safe (verify while implementing).
@@ -0,0 +1,81 @@
---
id: "01-backend-duplicate-endpoint"
title: "Add the backend profile duplicate endpoint"
status: done
wave: 1
depends_on: []
plan: "plan.md"
spec: "../../specs/agents/profile-duplicate.md"
---
# Task 01: Backend profile duplicate endpoint
## Acceptance
- `POST /api/v1/agent-profiles/:id/duplicate` (interlock-protected) creates a
new profile named `<source name> Copy` with a distinct ID and
`user_modified: true`, copying model, fallback model, auto-fallback, mode,
config options, allow-indexing, auto-approve, CLI passthrough, CLI flags,
env vars (secret refs included), command prefix, enabled state, and the
source's MCP config row (enabled + servers + meta) when one exists.
- Runtime state is not copied: the copy is idle, no pause reason, no last-run
timestamp, zero consecutive failures.
- A disabled source produces a disabled copy; an enabled source produces an
enabled copy.
- The copy is committed atomically (row + MCP config in one repository
transaction, inserted with the source's enabled state): a failure leaves no
partial profile and a disabled source never becomes briefly selectable.
- Unknown or soft-deleted source ID → `ErrAgentProfileNotFound` → HTTP 404,
and nothing is created.
- An office-scoped source (non-empty `workspace_id`) → `ErrAgentProfileNotFound`
→ HTTP 404 (existence hidden), rejected before MCP config is read or any
row is written, with zero broadcasts on any channel (global or
workspace-scoped).
- Success returns the new `AgentProfileDTO` and broadcasts the
`agent.profile.created` WS notification with `{"profile": <dto>}`.
- The route is added to the interlock 403 route list.
## Verification
- RED/GREEN controller:
`cd apps/backend && go test -run 'TestDuplicateProfile' ./internal/agent/settings/controller`
- Interlock list:
`cd apps/backend && go test -run 'TestRegisterRoutesProtectsEveryStateChangingAgentSettingsRoute' ./internal/agent/settings/handlers`
- Full package after refactor:
`cd apps/backend && go test ./internal/agent/settings/...`
## Files likely touched
- `apps/backend/internal/agent/settings/controller/profile_crud.go`
- `apps/backend/internal/agent/settings/controller/profile_duplicate_test.go` (new)
- `apps/backend/internal/agent/settings/controller/reconciler_test.go` (extend shared `fakeStore` with MCP config methods + `DuplicateAgentProfile`, additively)
- `apps/backend/internal/agent/settings/store/store.go` (add `DuplicateAgentProfile` to the repository interface)
- `apps/backend/internal/agent/settings/store/sqlite.go` (atomic `DuplicateAgentProfile` in one transaction; shared insert/upsert helpers)
- `apps/backend/internal/agent/settings/store/sqlite_duplicate_test.go` (new)
- `apps/backend/internal/agent/settings/handlers/handlers.go`
- `apps/backend/internal/agent/settings/handlers/interim_settings_interlock_test.go`
- Optional: `apps/backend/internal/agent/settings/handlers/profile_duplicate_handlers_test.go`
## Dependencies
None.
## Parallelism
Sequential by default; file-disjoint from Tasks 02–03 and may run in parallel
only with explicit user authorization.
## Inputs
- Spec duplicate scenarios
- `profile_crud.go` existing `DeleteProfile` not-found mapping and
`CreateProfile` field list; `store.Repository` interface; sqlite
`CreateAgentProfile` / `GetAgentProfileMcpConfig` /
`UpsertAgentProfileMcpConfig`; `ws.ActionAgentProfileCreated` broadcast
pattern from `httpCreateProfile`.
## Output contract
Report RED and GREEN results, the response/error contract, changed files, the
enabled-state and MCP-copy behavior, and update this task plus `plan.md`
status.
@@ -0,0 +1,72 @@
---
id: "02-frontend-duplicate-ui"
title: "Add the frontend duplicate UI"
status: done
wave: 2
depends_on: ["01-backend-duplicate-endpoint"]
plan: "plan.md"
spec: "../../specs/agents/profile-duplicate.md"
---
# Task 02: Frontend duplicate UI
## Acceptance
- `duplicateAgentProfileAction(profileId)` POSTs to
`/api/v1/agent-profiles/:id/duplicate` and returns the normalized
`AgentProfile`.
- Each profile row on `/settings/agents` shows a Duplicate icon button
(outside the row link, beside the enabled switch) with an accessible label
`Duplicate <name>`, `data-testid="duplicate-profile-<id>"`, and a touch
target of at least 44×44px. Clicking it creates the copy and adds the new
row to the store immediately (toast on success/failure). No navigation.
- The profile settings page header (`/settings/agents/<agent>/profiles/<id>`)
shows a Duplicate button (`data-testid="duplicate-profile-header"`,
`min-h-11` touch target). On success it toasts and navigates to the copy's
settings page.
- All new user-facing copy goes through `t()`; the persisted copy name stays
server-side (`<source> Copy`) and is not localized.
- New en keys exist in `agents.json`; the pseudo locale is regenerated;
`i18n:check` and `i18n:ratchet` pass for changed lines.
## Verification
- Component test:
`cd apps/web && pnpm vitest run app/settings/agents/profile-list-item.test.tsx`
- i18n:
`cd apps/web && pnpm run i18n:pseudo && pnpm run i18n:check`
- Typecheck + lint of changed files:
`cd apps/web && pnpm run typecheck`
`cd apps && pnpm --filter @kandev/web lint` (or the repo's configured lint command)
## Files likely touched
- `apps/web/app/actions/agents.ts`
- `apps/web/app/settings/agents/profile-list-item.tsx`
- `apps/web/app/settings/agents/profile-list-item.test.tsx`
- `apps/web/app/settings/agents/page.tsx`
- `apps/web/components/settings/agent-profile-page.tsx`
- `apps/web/src/locales/en/agents.json`
- `apps/web/src/locales/pseudo/agents.json` (regenerated)
## Dependencies
Task 01 (endpoint must exist for the action to hit).
## Parallelism
Sequential by default; may run in parallel with Task 03 only with explicit
user authorization.
## Inputs
- Spec duplicate scenarios and API surface
- `useProfileEnabledToggle` / `applyEnabledProfileUpdate` store-merge
pattern; `agent-profile-page-state.ts` delete/navigate flow; `normalizeAgentProfile`;
`ws/handlers/agents.ts` `handleProfileCreated` upsert-by-ID behaviour
(verify no double-row when the direct merge and WS both insert).
## Output contract
Report RED and GREEN results, store-merge approach, toast keys, changed
files, and update this task plus `plan.md` status.
@@ -0,0 +1,56 @@
---
id: "03-duplicate-e2e"
title: "Add the E2E duplicate flow"
status: done
wave: 3
depends_on: ["01-backend-duplicate-endpoint", "02-frontend-duplicate-ui"]
plan: "plan.md"
spec: "../../specs/agents/profile-duplicate.md"
---
# Task 03: E2E duplicate flow
## Acceptance
- An E2E spec (`agent-profile-duplicate.spec.ts`) proves the user-facing
flow: create a profile with distinctive settings via `apiClient`, open
`/settings/agents`, click its Duplicate button, and see a
`<name> Copy` row appear without a page reload.
- The copy's profile page shows the copied settings (model / CLI flag /
command prefix) matching the source.
- The spec cleans up both profiles in `finally`.
## Verification
- `cd apps/web && pnpm e2e:raw --grep "agent profile duplicate"` (or the
repo's E2E runner for `tests/settings/agent-profile-duplicate.spec.ts`).
- Mobile parity: the new row button must be reachable at mobile widths; reuse
the desktop spec unless a mobile-only interaction appears (the icon button
sits outside the row link exactly like the existing switch, which already
has mobile coverage patterns).
## Files likely touched
- `apps/web/e2e/tests/settings/agent-profile-duplicate.spec.ts` (new)
- `apps/web/e2e/tests/settings/mobile-agent-profile-duplicate.spec.ts` (new — mobile parity: Pixel 5 tap on the 44px row control, copy row appears, no horizontal overflow)
## Dependencies
Tasks 01 and 02 (endpoint and UI must exist).
## Parallelism
Sequential by default; may run in parallel with Task 02 only with explicit
user authorization.
## Inputs
- Spec duplicate scenarios
- `agent-profile-delete.spec.ts` structure (apiClient setup, testPage.goto,
row assertions); `apiClient.createAgentProfile` / `deleteAgentProfile`
helpers; `cleanupTestProfiles` convention.
## Output contract
Report the passing E2E run (or the exact failure to investigate), cleanup
behaviour, changed files, and update this task plus `plan.md` status.
+106
View File
@@ -0,0 +1,106 @@
---
status: draft
created: 2026-08-11
owner: kandev
---
# Duplicate an Agent Profile
## Why
Profiles are the per-agent configuration unit (model, mode, config options,
CLI flags, env vars, launcher prefix, auto-approve). Creating a variant of an
existing profile means re-entering every field by hand today: there is no way
to start from a working configuration. Users need a one-click "duplicate" that
copies a profile's full configuration under a new name, so they can tweak the
copy (a different model, an extra CLI flag, a sandbox launcher) without
touching the source.
## What
- Every profile row on the settings agents page
(`/settings/agents`, the "Manage existing profiles by agent" list) gets a
**Duplicate** action.
- The profile settings page
(`/settings/agents/<agent>/profiles/<id>`) gets the same **Duplicate**
action in its header.
- Duplicating creates a new profile that is a faithful copy of the source's
configuration: name-derived new name, model, fallback model, auto-fallback,
mode, config options, allow-indexing, auto-approve, CLI passthrough, CLI
flags, env vars, command prefix, enabled state, and MCP config (enabled
flag + servers + meta) when the source has one.
- The copy is an independent row: it gets a new ID, `user_modified` is set,
and editing or deleting it never affects the source. No session, task,
watcher, automation, or routing reference points at the copy.
- The copy is committed atomically: the row is inserted with the source's
enabled state and the MCP config row is upserted in one repository
transaction, so a duplicated profile inherits the source's selection state
and a disabled source never becomes briefly selectable. A failure rolls
back and leaves no partial copy.
- Runtime state is never copied: the copy starts idle with no pause reason,
no last-run timestamp, and a zero consecutive-failure count. Office
enrichment configuration (workspace, role, budget, permissions, skills,
executor preference, …) is copied when present, matching the faithful-copy
intent; the settings surface only lists global (non-office) profiles, so in
practice those fields are empty on the rows this feature shows.
- The generated name is persisted user data, not UI copy: it is
`<source name> Copy` (e.g. `Default` → `Default Copy`), matching the
repo convention that stored names do not depend on the locale they were
created in (same rule as seeded executor and repository names).
## API surface
`POST /api/v1/agent-profiles/:id/duplicate` (interim-settings-interlock
protected, like every other profile mutation):
- Request body: none. The copy name is derived server-side as
`<source name> Copy`.
- Response `200`: the new `AgentProfileDTO` (same shape as
`POST /agents/:id/profiles`).
- `404` when the source profile does not exist or is soft-deleted.
- Broadcasts the existing `agent.profile.created` WebSocket notification so
every open settings surface picks the copy up live.
The endpoint is not idempotent in the HTTP sense: each call creates one new
row (there is no idempotency key), so a retried POST after a network timeout
may create a second copy. Callers must treat duplicates as one-shot
operations; the UI guards against double-clicks. The copy performs no
reference checks because a brand-new row cannot be referenced by anything
yet.
## Scenarios
- **GIVEN** a profile named `Default` with model, CLI flags, env vars, and a
command prefix, **WHEN** the user clicks Duplicate on its row in
`/settings/agents`, **THEN** a new profile row `Default Copy` appears
immediately with every configuration field equal to the source, a distinct
ID, and `user_modified` true.
- **GIVEN** an MCP-capable agent profile with an MCP config (enabled with
servers), **WHEN** it is duplicated, **THEN** the copy has the same MCP
enabled state, servers, and meta under the new profile ID.
- **GIVEN** a disabled profile, **WHEN** it is duplicated, **THEN** the copy
is also disabled.
- **GIVEN** a profile with an active session, **WHEN** it is duplicated,
**THEN** the duplicate succeeds (unlike delete, no in-use checks apply) and
the session keeps using the source.
- **GIVEN** the profile settings page of a profile, **WHEN** the user clicks
Duplicate in the header, **THEN** a toast confirms the copy and the user is
taken to the copy's settings page to edit it.
- **GIVEN** an unknown profile ID, **WHEN** the duplicate endpoint is called,
**THEN** it returns `404` and creates nothing.
## Out of scope
- Duplicating office workspace agents through the office UI (`/office/agents`):
office has its own agent creation flows and permission model. This feature
targets the `/settings/agents` profile flavor. The settings duplicate
endpoint is fail-closed against office-scoped sources: a profile with a
non-empty `workspace_id` returns `404` (existence hidden) before any MCP
read or write, so the instance-level settings surface can never read or
clone another workspace's configuration. Office duplication, when added,
belongs on the workspace-scoped office API surface.
- Renaming after duplicate: the copy is a normal profile the user renames via
the existing profile editor.
- Bulk/queue duplication, templates, or copy-paste between agents.
- Choosing the copy name in the duplicate dialog: name is derived, then edited
on the copy's settings page.