diff --git a/apps/backend/internal/backendapp/helpers.go b/apps/backend/internal/backendapp/helpers.go
index 91bd131c19..c5f98e821e 100644
--- a/apps/backend/internal/backendapp/helpers.go
+++ b/apps/backend/internal/backendapp/helpers.go
@@ -39,6 +39,7 @@ import (
"github.com/kandev/kandev/internal/common/config"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/internal/common/ports"
+ "github.com/kandev/kandev/internal/db"
debughandlers "github.com/kandev/kandev/internal/debug"
editorcontroller "github.com/kandev/kandev/internal/editors/controller"
editorhandlers "github.com/kandev/kandev/internal/editors/handlers"
@@ -51,6 +52,7 @@ import (
"github.com/kandev/kandev/internal/health/oslimits"
"github.com/kandev/kandev/internal/i18n"
"github.com/kandev/kandev/internal/improvekandev"
+ "github.com/kandev/kandev/internal/integrations/workspacescope"
"github.com/kandev/kandev/internal/jira"
"github.com/kandev/kandev/internal/linear"
lspinstaller "github.com/kandev/kandev/internal/lsp/installer"
@@ -526,6 +528,7 @@ type routeParams struct {
systemSvc *systemsvc.Service
workspaceRestorer taskhandlers.WorkspaceQuarantineRestorer
runtimeFlagsSvc *runtimeflags.Service
+ dbPool *db.Pool
agentSettingsController *agentsettingscontroller.Controller
agentSettingsRepo settingsstore.Repository
agentList taskhandlers.AgentLister
@@ -1177,7 +1180,15 @@ func registerSecondaryRoutes(
}
if p.repoCloner != nil {
- ikHandler := improvekandev.NewHandler(p.taskSvc, p.repoCloner, p.version, p.log)
+ var ghCopier improvekandev.GitHubWorkspaceCopier
+ var resolveDefaultWorkspace improvekandev.DefaultWorkspaceResolver
+ if p.services.GitHub != nil && p.dbPool != nil {
+ ghCopier = p.services.GitHub
+ resolveDefaultWorkspace = func(context.Context) (string, error) {
+ return workspacescope.ResolveMigrationTarget(p.dbPool.Reader())
+ }
+ }
+ ikHandler := improvekandev.NewHandler(p.taskSvc, p.repoCloner, ghCopier, resolveDefaultWorkspace, p.version, p.log)
if p.systemSvc != nil {
ikHandler.SetLogBundles(p.systemSvc.LogBundles)
}
diff --git a/apps/backend/internal/backendapp/httpserver_test.go b/apps/backend/internal/backendapp/httpserver_test.go
index 02d2e3c4d2..a92142c4d8 100644
--- a/apps/backend/internal/backendapp/httpserver_test.go
+++ b/apps/backend/internal/backendapp/httpserver_test.go
@@ -22,7 +22,7 @@ func TestBuildHTTPServerAbortsWhenInterlockTokenGenerationFails(t *testing.T) {
newInterimSettingsInterlockToken = func() (string, error) { return "", wantErr }
t.Cleanup(func() { newInterimSettingsInterlockToken = original })
- server, err := buildHTTPServer(&config.Config{}, testLogger(t), nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
+ server, err := buildHTTPServer(&config.Config{}, testLogger(t), nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil)
if !errors.Is(err, wantErr) {
t.Fatalf("buildHTTPServer error = %v, want %v", err, wantErr)
}
diff --git a/apps/backend/internal/backendapp/main.go b/apps/backend/internal/backendapp/main.go
index 6788bd15f1..c6a4df3080 100644
--- a/apps/backend/internal/backendapp/main.go
+++ b/apps/backend/internal/backendapp/main.go
@@ -848,7 +848,7 @@ func startGatewayAndServe(
// ============================================
server, err := buildHTTPServer(cfg, log, gateway, repos, services, agentSettingsController,
lifecycleMgr, eventBus, orchestratorSvc, notificationCtrl, msgCreator, agentRegistry, hostUtilityMgr,
- addCleanup, repoCloner, systemSvc, storageComposition.workspaceRestorer)
+ addCleanup, repoCloner, systemSvc, storageComposition.workspaceRestorer, dbPool)
if err != nil {
log.Error("Failed to build HTTP server", zap.Error(err))
return false
@@ -1749,6 +1749,7 @@ func buildHTTPServer(
repoCloner *repoclone.Cloner,
systemSvc *systemsvc.Service,
workspaceRestorer taskhandlers.WorkspaceQuarantineRestorer,
+ dbPool *db.Pool,
) (*http.Server, error) {
gin.SetMode(gin.ReleaseMode)
router := gin.New()
@@ -1811,6 +1812,7 @@ func buildHTTPServer(
systemSvc: systemSvc,
workspaceRestorer: workspaceRestorer,
runtimeFlagsSvc: services.RuntimeFlags,
+ dbPool: dbPool,
agentSettingsController: agentSettingsController,
agentSettingsRepo: repos.AgentSettings,
agentList: agentRegistry,
diff --git a/apps/backend/internal/backendapp/services.go b/apps/backend/internal/backendapp/services.go
index 36c06ececf..007e911aac 100644
--- a/apps/backend/internal/backendapp/services.go
+++ b/apps/backend/internal/backendapp/services.go
@@ -110,6 +110,8 @@ func provideServices(cfg *config.Config, log *logger.Logger, repos *Repositories
// Wire workflow provider to workflow service for export/import
workflowSvc.SetWorkflowProvider(&workflowProviderAdapter{svc: taskSvc})
+ // Wire workspace provider for the read-only guard (Improve Kandev workspace)
+ workflowSvc.SetWorkspaceProvider(&workflowProviderAdapter{svc: taskSvc})
// Wire agent profile resolver/matcher for workflow export/import
workflowSvc.SetAgentProfileFuncs(
@@ -795,6 +797,11 @@ func (a *workflowProviderAdapter) GetWorkflow(ctx context.Context, id string) (*
return a.svc.GetWorkflow(ctx, id)
}
+// GetWorkspace implements workflowservice.WorkspaceProvider.
+func (a *workflowProviderAdapter) GetWorkspace(ctx context.Context, id string) (*taskmodels.Workspace, error) {
+ return a.svc.GetWorkspace(ctx, id)
+}
+
// CreateWorkflow implements workflowservice.WorkflowProvider.
func (a *workflowProviderAdapter) CreateWorkflow(ctx context.Context, workspaceID, name, description string) (*taskmodels.Workflow, error) {
return a.svc.CreateWorkflow(ctx, &taskservice.CreateWorkflowRequest{
diff --git a/apps/backend/internal/github/service_connections.go b/apps/backend/internal/github/service_connections.go
index cfbb178542..39ca93157e 100644
--- a/apps/backend/internal/github/service_connections.go
+++ b/apps/backend/internal/github/service_connections.go
@@ -404,3 +404,50 @@ func (s *Service) clearAuthCaches() {
s.protectionCache.clear()
}
}
+
+// CopyWorkspaceConnectionToWorkspace duplicates the source workspace's GitHub
+// connection onto the destination workspace, including the PAT secret for
+// `pat` sources. No-op when the source workspace has no connection or the two
+// workspaces are the same. Used by the improve-kandev bootstrap when it
+// creates the dedicated workspace so improve tasks inherit the user's GitHub
+// access without re-authenticating.
+func (s *Service) CopyWorkspaceConnectionToWorkspace(ctx context.Context, srcWorkspaceID, dstWorkspaceID string) error {
+ if srcWorkspaceID == "" || dstWorkspaceID == "" || srcWorkspaceID == dstWorkspaceID {
+ return nil
+ }
+ src, err := s.store.GetWorkspaceConnection(ctx, srcWorkspaceID)
+ if err != nil {
+ return fmt.Errorf("load source workspace connection: %w", err)
+ }
+ if src == nil {
+ return nil
+ }
+ connection := &WorkspaceConnection{
+ WorkspaceID: dstWorkspaceID,
+ Source: src.Source,
+ GitHubHost: src.GitHubHost,
+ Login: src.Login,
+ InstallationID: src.InstallationID,
+ InstallationAccountLogin: src.InstallationAccountLogin,
+ InstallationAccountType: src.InstallationAccountType,
+ AppRegistrationID: src.AppRegistrationID,
+ Status: src.Status,
+ CredentialGeneration: nextCredentialGeneration(nil),
+ CreatedAt: time.Now().UTC(),
+ UpdatedAt: time.Now().UTC(),
+ }
+ if err := s.store.UpsertWorkspaceConnection(ctx, connection); err != nil {
+ return fmt.Errorf("store destination workspace connection: %w", err)
+ }
+ if src.Source == ConnectionSourcePAT {
+ token, err := s.connectionSecrets.Reveal(ctx, WorkspacePATSecretKey(srcWorkspaceID))
+ if err != nil {
+ return fmt.Errorf("reveal source workspace PAT: %w", err)
+ }
+ if err := s.connectionSecrets.Set(ctx, WorkspacePATSecretKey(dstWorkspaceID), workspacePATSecretName, token); err != nil {
+ return fmt.Errorf("store destination workspace PAT: %w", err)
+ }
+ }
+ s.invalidateWorkspaceCredential(dstWorkspaceID)
+ return nil
+}
diff --git a/apps/backend/internal/github/service_connections_test.go b/apps/backend/internal/github/service_connections_test.go
index fdb07ca73f..460e7f1777 100644
--- a/apps/backend/internal/github/service_connections_test.go
+++ b/apps/backend/internal/github/service_connections_test.go
@@ -8,6 +8,7 @@ import (
"time"
"github.com/kandev/kandev/internal/auth/authn"
+ "github.com/stretchr/testify/require"
)
type fakeConnectionSecrets struct {
@@ -455,3 +456,49 @@ func TestWorkspaceConnectionStaleUsesConflictResponse(t *testing.T) {
t.Fatalf("stale response = %d, %q", status, code)
}
}
+
+func TestCopyWorkspaceConnectionToWorkspace(t *testing.T) {
+ t.Run("copies PAT connection and secret", func(t *testing.T) {
+ service, secrets := newWorkspaceConnectionService(t, "alice")
+ ctx := context.Background()
+ if _, err := service.store.db.Exec(`INSERT INTO workspaces (id) VALUES ('ws-dst')`); err != nil {
+ t.Fatalf("seed destination workspace: %v", err)
+ }
+ if _, err := service.SetWorkspaceConnection(ctx, "ws-1", SetWorkspaceConnectionRequest{
+ Source: ConnectionSourcePAT,
+ Login: "alice",
+ Token: "ghp_source_token",
+ }); err != nil {
+ t.Fatalf("seed source connection: %v", err)
+ }
+
+ require.NoError(t, service.CopyWorkspaceConnectionToWorkspace(ctx, "ws-1", "ws-dst"))
+
+ got, err := service.store.GetWorkspaceConnection(ctx, "ws-dst")
+ require.NoError(t, err)
+ require.NotNil(t, got)
+ require.Equal(t, ConnectionSourcePAT, got.Source)
+ require.Equal(t, "alice", got.Login)
+ require.Equal(t, ConnectionStatusActive, got.Status)
+ token, err := secrets.Reveal(ctx, WorkspacePATSecretKey("ws-dst"))
+ require.NoError(t, err)
+ require.Equal(t, "ghp_source_token", token)
+ })
+
+ t.Run("no-op without a source connection", func(t *testing.T) {
+ service, _ := newWorkspaceConnectionService(t, "alice")
+ ctx := context.Background()
+ if _, err := service.store.db.Exec(`INSERT INTO workspaces (id) VALUES ('ws-dst')`); err != nil {
+ t.Fatalf("seed destination workspace: %v", err)
+ }
+ require.NoError(t, service.CopyWorkspaceConnectionToWorkspace(ctx, "ws-1", "ws-dst"))
+ got, err := service.store.GetWorkspaceConnection(ctx, "ws-dst")
+ require.NoError(t, err)
+ require.Nil(t, got)
+ })
+
+ t.Run("no-op for identical workspaces", func(t *testing.T) {
+ service, _ := newWorkspaceConnectionService(t, "alice")
+ require.NoError(t, service.CopyWorkspaceConnectionToWorkspace(context.Background(), "ws-1", "ws-1"))
+ })
+}
diff --git a/apps/backend/internal/improvekandev/handler.go b/apps/backend/internal/improvekandev/handler.go
index eb7ddc4bb2..00c8f7a6fa 100644
--- a/apps/backend/internal/improvekandev/handler.go
+++ b/apps/backend/internal/improvekandev/handler.go
@@ -10,7 +10,6 @@ import (
"time"
"github.com/gin-gonic/gin"
- "github.com/google/uuid"
"go.uber.org/zap"
"github.com/kandev/kandev/internal/auth/authn"
@@ -40,6 +39,14 @@ const (
issueTemplateID = "report-kandev-issue"
issueWorkflowName = "Report Kandev Issue"
issueWorkflowDesc = "Hidden workflow for publishing a kdlbs/kandev issue without changing code."
+
+ // improveWorkspaceName aliases the canonical identity in task/models so
+ // every guard and the bootstrap agree on the exact name.
+ improveWorkspaceName = taskmodels.WorkspaceNameImproveKandev
+ improveWorkspaceDesc = "Dedicated workspace for Improve Kandev contribution tasks, isolated from regular work."
+
+ // errorKey is the JSON key every error response body uses.
+ errorKey = "error"
)
// Cloner is the minimal subset of repoclone.Cloner the bootstrap endpoint uses.
@@ -51,12 +58,29 @@ type Cloner interface {
) (string, error)
}
+// GitHubWorkspaceCopier copies a workspace's GitHub connection onto another
+// workspace. Implemented by the github service; nil disables the copy.
+type GitHubWorkspaceCopier interface {
+ CopyWorkspaceConnectionToWorkspace(ctx context.Context, srcWorkspaceID, dstWorkspaceID string) error
+}
+
+// DefaultWorkspaceResolver resolves the workspace whose GitHub configuration
+// the dedicated workspace inherits on creation (active workspace in user
+// settings → first-created workspace → literal "default").
+type DefaultWorkspaceResolver func(ctx context.Context) (string, error)
+
// Handler exposes the improve-kandev HTTP endpoints.
type Handler struct {
taskSvc *taskservice.Service
cloner Cloner
log *logger.Logger
logBundles diagnosticBundleService
+ // ghCopier copies the default workspace's GitHub connection onto the
+ // dedicated workspace when bootstrap creates it. Nil disables the copy.
+ ghCopier GitHubWorkspaceCopier
+ // defaultWorkspaceResolver picks the source workspace for the copy. Nil
+ // disables the copy.
+ defaultWorkspaceResolver DefaultWorkspaceResolver
// gh resolves the authenticated user's login and write access. Defaults
// to a gh-CLI shell-out; tests can substitute a fake.
gh GitHubInfo
@@ -69,15 +93,24 @@ type diagnosticBundleService interface {
OpenArchive(owner, id string) (*os.File, logbundle.JobView, error)
}
-// NewHandler constructs a Handler.
-func NewHandler(taskSvc *taskservice.Service, cloner Cloner, version string, log *logger.Logger) *Handler {
+// NewHandler constructs a Handler. version is embedded into bundle metadata.
+func NewHandler(
+ taskSvc *taskservice.Service,
+ cloner Cloner,
+ ghCopier GitHubWorkspaceCopier,
+ defaultWorkspaceResolver DefaultWorkspaceResolver,
+ version string,
+ log *logger.Logger,
+) *Handler {
_ = version
return &Handler{
- taskSvc: taskSvc,
- cloner: cloner,
- log: log,
- gh: newDefaultGitHubInfo(),
- resolveRemote: taskservice.ResolveGitRemoteProvider,
+ taskSvc: taskSvc,
+ cloner: cloner,
+ log: log,
+ ghCopier: ghCopier,
+ defaultWorkspaceResolver: defaultWorkspaceResolver,
+ gh: newDefaultGitHubInfo(),
+ resolveRemote: taskservice.ResolveGitRemoteProvider,
}
}
@@ -97,7 +130,16 @@ func RegisterRoutes(router *gin.Engine, h *Handler) {
// BootstrapRequest is the JSON body for POST /bootstrap.
type BootstrapRequest struct {
- WorkspaceID string `json:"workspace_id"`
+ // WorkspaceID is the fallback workspace (the user's active workspace) used
+ // when the dedicated Improve Kandev workspace does not exist and the user
+ // declines to create it (CreateWorkspace=false). It is ignored when the
+ // dedicated workspace exists or is being created.
+ WorkspaceID string `json:"workspace_id,omitempty"`
+ // CreateWorkspace opts into creating the dedicated Improve Kandev
+ // workspace when it does not exist (surfaced to the user as a checkbox in
+ // the dialog). When false and the workspace is missing, bootstrap falls
+ // back to WorkspaceID (legacy behavior).
+ CreateWorkspace bool `json:"create_workspace,omitempty"`
}
// ForkStatus reports the result of the bootstrap fork-capability probe. The
@@ -124,6 +166,9 @@ const (
// BootstrapResponse describes the artifacts the dialog needs to submit a task.
type BootstrapResponse struct {
+ // WorkspaceID is the dedicated Improve Kandev workspace the task must be
+ // created in.
+ WorkspaceID string `json:"workspace_id"`
RepositoryID string `json:"repository_id"`
WorkflowID string `json:"workflow_id"`
IssueWorkflowID string `json:"issue_workflow_id"`
@@ -139,32 +184,35 @@ type BootstrapResponse struct {
func (h *Handler) httpBootstrap(c *gin.Context) {
identity, ok := authn.FromGin(c)
if !ok || identity.UserID == "" {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "authentication required"})
+ c.JSON(http.StatusUnauthorized, gin.H{errorKey: "authentication required"})
return
}
var req BootstrapRequest
- if err := c.ShouldBindJSON(&req); err != nil || req.WorkspaceID == "" {
- c.JSON(http.StatusBadRequest, gin.H{"error": "workspace_id is required"})
- return
- }
- workspaceID, err := canonicalWorkspaceID(req.WorkspaceID)
- if err != nil {
- c.JSON(http.StatusBadRequest, gin.H{"error": "workspace_id must be a UUID"})
+ if err := c.ShouldBindJSON(&req); err != nil {
+ c.JSON(http.StatusBadRequest, gin.H{errorKey: "invalid payload"})
return
}
ctx := c.Request.Context()
+ workspace, err := h.ensureImproveWorkspace(ctx, req.CreateWorkspace, req.WorkspaceID)
+ if err != nil {
+ h.log.Error("improve-kandev: dedicated workspace resolution failed", zap.Error(err))
+ c.JSON(http.StatusInternalServerError, gin.H{errorKey: "failed to resolve the Improve Kandev workspace"})
+ return
+ }
+ workspaceID := workspace.ID
+
repo, err := h.resolveOrCloneRepo(ctx, workspaceID)
if err != nil {
h.log.Error("improve-kandev: repository upsert failed", zap.Error(err))
- c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to register kandev repository"})
+ c.JSON(http.StatusInternalServerError, gin.H{errorKey: "failed to register kandev repository"})
return
}
workflows, err := h.taskSvc.ListWorkflows(ctx, workspaceID, true)
if err != nil {
h.log.Error("improve-kandev: workflow list failed", zap.Error(err))
- c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list improve-kandev workflows"})
+ c.JSON(http.StatusInternalServerError, gin.H{errorKey: "failed to list improve-kandev workflows"})
return
}
workflow, err := h.ensureWorkflow(
@@ -177,7 +225,7 @@ func (h *Handler) httpBootstrap(c *gin.Context) {
)
if err != nil {
h.log.Error("improve-kandev: workflow upsert failed", zap.Error(err))
- c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to ensure improve-kandev workflow"})
+ c.JSON(http.StatusInternalServerError, gin.H{errorKey: "failed to ensure improve-kandev workflow"})
return
}
issueWorkflow, err := h.ensureWorkflow(
@@ -190,19 +238,20 @@ func (h *Handler) httpBootstrap(c *gin.Context) {
)
if err != nil {
h.log.Error("improve-kandev: issue workflow upsert failed", zap.Error(err))
- c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to ensure report-kandev-issue workflow"})
+ c.JSON(http.StatusInternalServerError, gin.H{errorKey: "failed to ensure report-kandev-issue workflow"})
return
}
dir, err := createBundleDir(identity.UserID)
if err != nil {
h.log.Error("improve-kandev: bundle dir creation failed", zap.Error(err))
- c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create bundle dir"})
+ c.JSON(http.StatusInternalServerError, gin.H{errorKey: "failed to create bundle dir"})
return
}
access := h.resolveGitHubAccess(ctx)
c.JSON(http.StatusOK, BootstrapResponse{
+ WorkspaceID: workspaceID,
RepositoryID: repo.ID,
WorkflowID: workflow.ID,
IssueWorkflowID: issueWorkflow.ID,
@@ -216,12 +265,95 @@ func (h *Handler) httpBootstrap(c *gin.Context) {
})
}
-func canonicalWorkspaceID(value string) (string, error) {
- id, err := uuid.Parse(value)
- if err != nil {
- return "", err
+// ensureImproveWorkspace returns the dedicated Improve Kandev workspace.
+//
+// - Exists (matched by exact name): returned as-is; create_workspace and
+// workspace_id are ignored.
+// - Missing + createWorkspace: created (kanban-bootstrapped), and the GitHub
+// connection from the user's default workspace is copied onto it
+// (best-effort). A creation failure re-reads the list to converge on a
+// workspace a concurrent bootstrap may have created.
+// - Missing + !createWorkspace: legacy fallback — returns the requested
+// fallbackWorkspaceID (the user's active workspace) so improve tasks land
+// there without a dedicated workspace.
+func (h *Handler) ensureImproveWorkspace(ctx context.Context, createWorkspace bool, fallbackWorkspaceID string) (*taskmodels.Workspace, error) {
+ findByName := func(workspaces []*taskmodels.Workspace) *taskmodels.Workspace {
+ for _, workspace := range workspaces {
+ if workspace != nil && workspace.Name == improveWorkspaceName {
+ return workspace
+ }
+ }
+ return nil
+ }
+
+ workspaces, err := h.taskSvc.ListWorkspaces(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if workspace := findByName(workspaces); workspace != nil {
+ return workspace, nil
+ }
+
+ if !createWorkspace {
+ if fallbackWorkspaceID == "" {
+ return nil, errors.New("workspace_id is required when the Improve Kandev workspace does not exist")
+ }
+ workspace, err := h.taskSvc.GetWorkspace(ctx, fallbackWorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ return workspace, nil
+ }
+
+ created, err := h.taskSvc.CreateWorkspace(ctx, &taskservice.CreateWorkspaceRequest{
+ Name: improveWorkspaceName,
+ Description: improveWorkspaceDesc,
+ // No Kanban bootstrap: the dedicated workspace only ever contains the
+ // hidden Improve Kandev / Report Kandev Issue workflows, so its
+ // workflow configuration must not show a default "Kanban" workflow.
+ })
+ if err == nil {
+ // A concurrent bootstrap may have created another row with the same
+ // name in the same instant (workspace names are not unique). Re-read
+ // and converge on the deterministic first match so every caller agrees
+ // on one workspace id; the duplicate row is left to the next bootstrap
+ // to ignore.
+ if latest, listErr := h.taskSvc.ListWorkspaces(ctx); listErr == nil {
+ if winner := findByName(latest); winner != nil {
+ h.copyGitHubConnectionFromDefaultWorkspace(ctx, winner.ID)
+ return winner, nil
+ }
+ }
+ h.copyGitHubConnectionFromDefaultWorkspace(ctx, created.ID)
+ return created, nil
+ }
+
+ latest, listErr := h.taskSvc.ListWorkspaces(ctx)
+ if listErr == nil {
+ if workspace := findByName(latest); workspace != nil {
+ return workspace, nil
+ }
+ }
+ return nil, err
+}
+
+// copyGitHubConnectionFromDefaultWorkspace copies the user's default
+// workspace GitHub connection onto the newly created dedicated workspace.
+// Best-effort: failures are logged, never fail bootstrap.
+func (h *Handler) copyGitHubConnectionFromDefaultWorkspace(ctx context.Context, workspaceID string) {
+ if h.ghCopier == nil || h.defaultWorkspaceResolver == nil {
+ return
+ }
+ srcWorkspaceID, err := h.defaultWorkspaceResolver(ctx)
+ if err != nil || srcWorkspaceID == "" {
+ if err != nil {
+ h.log.Warn("improve-kandev: default workspace resolution failed; skipping GitHub connection copy", zap.Error(err))
+ }
+ return
+ }
+ if err := h.ghCopier.CopyWorkspaceConnectionToWorkspace(ctx, srcWorkspaceID, workspaceID); err != nil {
+ h.log.Warn("improve-kandev: GitHub connection copy failed; improve workspace starts without one", zap.Error(err))
}
- return id.String(), nil
}
// resolveOrCloneRepo returns the workspace's kandev repository, preferring an
@@ -448,26 +580,26 @@ type leaseBundleRequest struct {
func (h *Handler) httpLeaseBundle(c *gin.Context) {
identity, ok := authn.FromGin(c)
if !ok || identity.UserID == "" {
- c.JSON(http.StatusUnauthorized, gin.H{"error": "authentication required"})
+ c.JSON(http.StatusUnauthorized, gin.H{errorKey: "authentication required"})
return
}
var req leaseBundleRequest
if err := c.ShouldBindJSON(&req); err != nil || req.BundleID == "" {
- c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
+ c.JSON(http.StatusBadRequest, gin.H{errorKey: "invalid payload"})
return
}
dir, err := validateBundleDir(req.BundleDir, identity.UserID)
if err != nil {
- c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
+ c.JSON(http.StatusForbidden, gin.H{errorKey: err.Error()})
return
}
if h.logBundles == nil {
- c.JSON(http.StatusServiceUnavailable, gin.H{"error": "diagnostic bundles unavailable"})
+ c.JSON(http.StatusServiceUnavailable, gin.H{errorKey: "diagnostic bundles unavailable"})
return
}
archive, view, err := h.logBundles.OpenArchive(identity.UserID, req.BundleID)
if err != nil {
- c.JSON(http.StatusConflict, gin.H{"error": "diagnostic bundle is not ready"})
+ c.JSON(http.StatusConflict, gin.H{errorKey: "diagnostic bundle is not ready"})
return
}
defer func() { _ = archive.Close() }()
@@ -479,7 +611,7 @@ func (h *Handler) httpLeaseBundle(c *gin.Context) {
if errors.Is(err, errBundleTooLarge) {
status = http.StatusRequestEntityTooLarge
}
- c.JSON(status, gin.H{"error": "failed to lease diagnostic bundle"})
+ c.JSON(status, gin.H{errorKey: "failed to lease diagnostic bundle"})
return
}
time.AfterFunc(staleBundleAge, func() { _ = os.Remove(path) })
diff --git a/apps/backend/internal/improvekandev/handler_test.go b/apps/backend/internal/improvekandev/handler_test.go
index 01862783dc..e1d5d40c17 100644
--- a/apps/backend/internal/improvekandev/handler_test.go
+++ b/apps/backend/internal/improvekandev/handler_test.go
@@ -48,20 +48,6 @@ func newTestHandler(gh GitHubInfo) *Handler {
return &Handler{gh: gh, log: logger.Default()}
}
-func TestCanonicalWorkspaceID(t *testing.T) {
- const canonical = "123e4567-e89b-12d3-a456-426614174000"
- got, err := canonicalWorkspaceID("123E4567-E89B-12D3-A456-426614174000")
- if err != nil {
- t.Fatalf("canonicalWorkspaceID() error = %v", err)
- }
- if got != canonical {
- t.Fatalf("canonicalWorkspaceID() = %q, want %q", got, canonical)
- }
- if _, err := canonicalWorkspaceID("../workspace"); err == nil {
- t.Fatal("canonicalWorkspaceID() expected invalid UUID error")
- }
-}
-
type fakeDiagnosticBundles struct {
path string
owner string
diff --git a/apps/backend/internal/integration/improve_kandev_test.go b/apps/backend/internal/integration/improve_kandev_test.go
index 13e189d1c3..770117b703 100644
--- a/apps/backend/internal/integration/improve_kandev_test.go
+++ b/apps/backend/internal/integration/improve_kandev_test.go
@@ -21,6 +21,19 @@ type improveKandevTestCloner struct {
path string
}
+// newImproveKandevTestRouter registers the improve-kandev routes with a
+// synthetic identity, mirroring the production auth middleware (bootstrap
+// requires an authenticated identity).
+func newImproveKandevTestRouter(handler *improvekandev.Handler) *gin.Engine {
+ router := gin.New()
+ router.Use(func(c *gin.Context) {
+ authn.SetOnGin(c, authn.Identity{UserID: "test-user"})
+ c.Next()
+ })
+ improvekandev.RegisterRoutes(router, handler)
+ return router
+}
+
func (c improveKandevTestCloner) EnsureWorkspaceCloned(
_ context.Context, _, _, _, _, _ string,
) (string, error) {
@@ -29,25 +42,15 @@ func (c improveKandevTestCloner) EnsureWorkspaceCloned(
func TestImproveKandevBootstrapCreatesBothHiddenWorkflowsIdempotently(t *testing.T) {
ts := NewOrchestratorTestServer(t)
- workspaceID := "123e4567-e89b-12d3-a456-426614174000"
- require.NoError(t, ts.TaskRepo.CreateWorkspace(context.Background(), &models.Workspace{
- ID: workspaceID,
- Name: "Improve Kandev",
- }))
repoPath := t.TempDir()
require.NoError(t, exec.Command("git", "init", repoPath).Run())
- router := gin.New()
- router.Use(func(c *gin.Context) {
- authn.SetOnGin(c, authn.Identity{UserID: "test-user"})
- c.Next()
- })
- handler := improvekandev.NewHandler(ts.TaskSvc, improveKandevTestCloner{path: repoPath}, "test", ts.Logger)
- improvekandev.RegisterRoutes(router, handler)
+ handler := improvekandev.NewHandler(ts.TaskSvc, improveKandevTestCloner{path: repoPath}, nil, nil, "test", ts.Logger)
+ router := newImproveKandevTestRouter(handler)
bootstrap := func() improvekandev.BootstrapResponse {
t.Helper()
- body, err := json.Marshal(improvekandev.BootstrapRequest{WorkspaceID: workspaceID})
+ body, err := json.Marshal(improvekandev.BootstrapRequest{CreateWorkspace: true})
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, "/api/v1/system/improve-kandev/bootstrap", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
@@ -61,13 +64,20 @@ func TestImproveKandevBootstrapCreatesBothHiddenWorkflowsIdempotently(t *testing
first := bootstrap()
second := bootstrap()
+ require.NotEmpty(t, first.WorkspaceID, "bootstrap must return the dedicated workspace id")
+ require.Equal(t, first.WorkspaceID, second.WorkspaceID)
require.NotEmpty(t, first.WorkflowID)
require.NotEmpty(t, first.IssueWorkflowID)
require.NotEqual(t, first.WorkflowID, first.IssueWorkflowID)
require.Equal(t, first.WorkflowID, second.WorkflowID)
require.Equal(t, first.IssueWorkflowID, second.IssueWorkflowID)
- workflows, err := ts.TaskRepo.ListWorkflows(context.Background(), workspaceID, true)
+ // The bootstrap auto-created a workspace named "Improve Kandev".
+ workspace, err := ts.TaskRepo.GetWorkspace(context.Background(), first.WorkspaceID)
+ require.NoError(t, err)
+ require.Equal(t, "Improve Kandev", workspace.Name)
+
+ workflows, err := ts.TaskRepo.ListWorkflows(context.Background(), first.WorkspaceID, true)
require.NoError(t, err)
byTemplate := make(map[string]*models.Workflow, len(workflows))
for _, workflow := range workflows {
@@ -87,3 +97,165 @@ func TestImproveKandevBootstrapCreatesBothHiddenWorkflowsIdempotently(t *testing
require.Equal(t, "Open issue", issueSteps[0].Name)
require.True(t, issueSteps[0].IsStartStep)
}
+
+func TestImproveKandevBootstrapReusesExistingImproveWorkspace(t *testing.T) {
+ ts := NewOrchestratorTestServer(t)
+ workspaceID := "123e4567-e89b-12d3-a456-426614174000"
+ require.NoError(t, ts.TaskRepo.CreateWorkspace(context.Background(), &models.Workspace{
+ ID: workspaceID,
+ Name: "Improve Kandev",
+ }))
+
+ repoPath := t.TempDir()
+ require.NoError(t, exec.Command("git", "init", repoPath).Run())
+ handler := improvekandev.NewHandler(ts.TaskSvc, improveKandevTestCloner{path: repoPath}, nil, nil, "test", ts.Logger)
+ router := newImproveKandevTestRouter(handler)
+
+ // The request may still carry a workspace_id from an older client; it must
+ // be ignored in favor of the dedicated Improve Kandev workspace.
+ body, err := json.Marshal(improvekandev.BootstrapRequest{WorkspaceID: "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"})
+ require.NoError(t, err)
+ req := httptest.NewRequest(http.MethodPost, "/api/v1/system/improve-kandev/bootstrap", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ res := httptest.NewRecorder()
+ router.ServeHTTP(res, req)
+ require.Equal(t, http.StatusOK, res.Code, res.Body.String())
+ var response improvekandev.BootstrapResponse
+ require.NoError(t, json.Unmarshal(res.Body.Bytes(), &response))
+
+ require.Equal(t, workspaceID, response.WorkspaceID)
+ workflows, err := ts.TaskRepo.ListWorkflows(context.Background(), workspaceID, true)
+ require.NoError(t, err)
+ require.NotEmpty(t, workflows, "hidden workflows must live in the pre-existing Improve Kandev workspace")
+}
+
+func TestImproveKandevBootstrapFallsBackToRequestedWorkspaceWhenCreationDeclined(t *testing.T) {
+ ts := NewOrchestratorTestServer(t)
+ fallbackID := "123e4567-e89b-12d3-a456-426614174000"
+ require.NoError(t, ts.TaskRepo.CreateWorkspace(context.Background(), &models.Workspace{
+ ID: fallbackID,
+ Name: "Active Workspace",
+ }))
+
+ repoPath := t.TempDir()
+ require.NoError(t, exec.Command("git", "init", repoPath).Run())
+ handler := improvekandev.NewHandler(ts.TaskSvc, improveKandevTestCloner{path: repoPath}, nil, nil, "test", ts.Logger)
+ router := newImproveKandevTestRouter(handler)
+
+ // No dedicated workspace exists and the caller declines creation
+ // (create_workspace=false): bootstrap falls back to the requested
+ // workspace and scopes the hidden workflows there.
+ body, err := json.Marshal(improvekandev.BootstrapRequest{WorkspaceID: fallbackID})
+ require.NoError(t, err)
+ req := httptest.NewRequest(http.MethodPost, "/api/v1/system/improve-kandev/bootstrap", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ res := httptest.NewRecorder()
+ router.ServeHTTP(res, req)
+ require.Equal(t, http.StatusOK, res.Code, res.Body.String())
+ var response improvekandev.BootstrapResponse
+ require.NoError(t, json.Unmarshal(res.Body.Bytes(), &response))
+ require.Equal(t, fallbackID, response.WorkspaceID)
+
+ workflows, err := ts.TaskRepo.ListWorkflows(context.Background(), fallbackID, true)
+ require.NoError(t, err)
+ require.NotEmpty(t, workflows, "hidden workflows must live in the fallback workspace")
+}
+
+type fakeGitHubWorkspaceCopier struct {
+ calls []struct{ src, dst string }
+}
+
+func (f *fakeGitHubWorkspaceCopier) CopyWorkspaceConnectionToWorkspace(_ context.Context, src, dst string) error {
+ f.calls = append(f.calls, struct{ src, dst string }{src, dst})
+ return nil
+}
+
+func TestImproveKandevBootstrapCopiesGitHubConnectionOnWorkspaceCreation(t *testing.T) {
+ ts := NewOrchestratorTestServer(t)
+ copier := &fakeGitHubWorkspaceCopier{}
+
+ repoPath := t.TempDir()
+ require.NoError(t, exec.Command("git", "init", repoPath).Run())
+ resolveDefault := func(context.Context) (string, error) {
+ return "default-workspace-id", nil
+ }
+ handler := improvekandev.NewHandler(ts.TaskSvc, improveKandevTestCloner{path: repoPath}, copier, resolveDefault, "test", ts.Logger)
+ router := newImproveKandevTestRouter(handler)
+
+ body, err := json.Marshal(improvekandev.BootstrapRequest{CreateWorkspace: true})
+ require.NoError(t, err)
+ req := httptest.NewRequest(http.MethodPost, "/api/v1/system/improve-kandev/bootstrap", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ res := httptest.NewRecorder()
+ router.ServeHTTP(res, req)
+ require.Equal(t, http.StatusOK, res.Code, res.Body.String())
+ var response improvekandev.BootstrapResponse
+ require.NoError(t, json.Unmarshal(res.Body.Bytes(), &response))
+
+ require.Len(t, copier.calls, 1, "connection must be copied exactly once on workspace creation")
+ require.Equal(t, "default-workspace-id", copier.calls[0].src)
+ require.Equal(t, response.WorkspaceID, copier.calls[0].dst)
+
+ // A second bootstrap (workspace now exists) must not copy again.
+ req2 := httptest.NewRequest(http.MethodPost, "/api/v1/system/improve-kandev/bootstrap", bytes.NewReader(body))
+ req2.Header.Set("Content-Type", "application/json")
+ res2 := httptest.NewRecorder()
+ router.ServeHTTP(res2, req2)
+ require.Equal(t, http.StatusOK, res2.Code, res2.Body.String())
+ require.Len(t, copier.calls, 1, "existing workspace must not re-copy the connection")
+}
+
+func TestImproveKandevBootstrapRequiresWorkspaceIDWhenCreationDeclined(t *testing.T) {
+ ts := NewOrchestratorTestServer(t)
+ repoPath := t.TempDir()
+ require.NoError(t, exec.Command("git", "init", repoPath).Run())
+ handler := improvekandev.NewHandler(ts.TaskSvc, improveKandevTestCloner{path: repoPath}, nil, nil, "test", ts.Logger)
+ router := newImproveKandevTestRouter(handler)
+
+ body, err := json.Marshal(improvekandev.BootstrapRequest{})
+ require.NoError(t, err)
+ req := httptest.NewRequest(http.MethodPost, "/api/v1/system/improve-kandev/bootstrap", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ res := httptest.NewRecorder()
+ router.ServeHTTP(res, req)
+ require.Equal(t, http.StatusInternalServerError, res.Code, res.Body.String())
+}
+
+func TestImproveKandevBootstrapConvergesOnSingleWorkspace(t *testing.T) {
+ ts := NewOrchestratorTestServer(t)
+ // Simulate the outcome of two concurrent first-time bootstraps: two rows
+ // with the same name (workspace names are not unique). Bootstrap must
+ // converge on a single, deterministic workspace id across calls.
+ for _, id := range []string{
+ "aaaaaaaa-0000-0000-0000-000000000001",
+ "aaaaaaaa-0000-0000-0000-000000000002",
+ } {
+ require.NoError(t, ts.TaskRepo.CreateWorkspace(context.Background(), &models.Workspace{
+ ID: id,
+ Name: "Improve Kandev",
+ }))
+ }
+
+ repoPath := t.TempDir()
+ require.NoError(t, exec.Command("git", "init", repoPath).Run())
+ handler := improvekandev.NewHandler(ts.TaskSvc, improveKandevTestCloner{path: repoPath}, nil, nil, "test", ts.Logger)
+ router := newImproveKandevTestRouter(handler)
+
+ bootstrap := func() improvekandev.BootstrapResponse {
+ t.Helper()
+ body, err := json.Marshal(improvekandev.BootstrapRequest{CreateWorkspace: true})
+ require.NoError(t, err)
+ req := httptest.NewRequest(http.MethodPost, "/api/v1/system/improve-kandev/bootstrap", bytes.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ res := httptest.NewRecorder()
+ router.ServeHTTP(res, req)
+ require.Equal(t, http.StatusOK, res.Code, res.Body.String())
+ var response improvekandev.BootstrapResponse
+ require.NoError(t, json.Unmarshal(res.Body.Bytes(), &response))
+ return response
+ }
+
+ first := bootstrap()
+ second := bootstrap()
+ require.Equal(t, first.WorkspaceID, second.WorkspaceID, "both bootstraps must agree on one workspace")
+}
diff --git a/apps/backend/internal/task/handlers/repository_handlers.go b/apps/backend/internal/task/handlers/repository_handlers.go
index 8039d6f99d..a35620a912 100644
--- a/apps/backend/internal/task/handlers/repository_handlers.go
+++ b/apps/backend/internal/task/handlers/repository_handlers.go
@@ -326,12 +326,85 @@ type httpInitializeLocalRepositoryRequest struct {
ParentPath string `json:"parent_path"`
}
+// rejectReadOnlyWorkspaceHTTP returns 409 when the workspace is the dedicated
+// Improve Kandev workspace, whose repositories are read-only. Lookup errors
+// surface as not-found so callers keep their existing error handling.
+func (h *RepositoryHandlers) rejectReadOnlyWorkspaceHTTP(c *gin.Context, workspaceID string) bool {
+ if workspaceID == "" {
+ return false
+ }
+ workspace, err := h.service.GetWorkspace(c.Request.Context(), workspaceID)
+ if err != nil {
+ handleNotFound(c, h.logger, err, "workspace not found")
+ return true
+ }
+ if workspace.IsImproveKandev() {
+ c.JSON(http.StatusConflict, gin.H{"error": workspaceReadOnlyMsg})
+ return true
+ }
+ return false
+}
+
+// rejectReadOnlyRepositoryHTTP loads the repository and returns 409 when it
+// lives in the read-only Improve Kandev workspace.
+func (h *RepositoryHandlers) rejectReadOnlyRepositoryHTTP(c *gin.Context, id string) bool {
+ repository, err := h.service.GetRepository(c.Request.Context(), id)
+ if err != nil {
+ handleNotFound(c, h.logger, err, "repository not found")
+ return true
+ }
+ return h.rejectReadOnlyWorkspaceHTTP(c, repository.WorkspaceID)
+}
+
+// wsRejectReadOnlyWorkspace returns a conflict WS error when the workspace is
+// the dedicated Improve Kandev workspace, whose repositories are read-only.
+// Returns (nil, false) when the mutation is allowed.
+func (h *RepositoryHandlers) wsRejectReadOnlyWorkspace(ctx context.Context, msg *ws.Message, workspaceID string) (*ws.Message, bool) {
+ if workspaceID == "" {
+ return nil, false
+ }
+ workspace, err := h.service.GetWorkspace(ctx, workspaceID)
+ if err != nil {
+ errMsg, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeNotFound, "Workspace not found", nil)
+ return errMsg, true
+ }
+ if workspace.IsImproveKandev() {
+ errMsg, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeConflict, workspaceReadOnlyMsg, nil)
+ return errMsg, true
+ }
+ return nil, false
+}
+
+// readOnlyRepositoryMessage returns the workspace read-only reason when the
+// repository lives in the dedicated Improve Kandev workspace. Lookup errors
+// surface as ("", false) so the caller's normal not-found path handles them.
+func (h *RepositoryHandlers) readOnlyRepositoryMessage(ctx context.Context, repositoryID string) (string, bool) {
+ repository, err := h.service.GetRepository(ctx, repositoryID)
+ if err != nil {
+ return "", false
+ }
+ if repository == nil || repository.WorkspaceID == "" {
+ return "", false
+ }
+ workspace, err := h.service.GetWorkspace(ctx, repository.WorkspaceID)
+ if err != nil {
+ return "", false
+ }
+ if workspace.IsImproveKandev() {
+ return workspaceReadOnlyMsg, true
+ }
+ return "", false
+}
+
func (h *RepositoryHandlers) httpInitializeLocalRepository(c *gin.Context) {
var body httpInitializeLocalRepositoryRequest
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
return
}
+ if h.rejectReadOnlyWorkspaceHTTP(c, c.Param("id")) {
+ return
+ }
initialized, err := h.service.InitializeLocalRepository(c.Request.Context(), &service.InitializeLocalRepositoryRequest{
WorkspaceID: c.Param("id"),
Name: body.Name,
@@ -364,6 +437,9 @@ func (h *RepositoryHandlers) httpCreateRepository(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "name is required"})
return
}
+ if h.rejectReadOnlyWorkspaceHTTP(c, c.Param("id")) {
+ return
+ }
repository, err := h.service.CreateRepository(c.Request.Context(), &service.CreateRepositoryRequest{
WorkspaceID: c.Param("id"),
Name: body.Name,
@@ -481,6 +557,9 @@ func (h *RepositoryHandlers) httpUpdateRepository(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request body"})
return
}
+ if h.rejectReadOnlyRepositoryHTTP(c, c.Param("id")) {
+ return
+ }
repository, err := h.service.UpdateRepository(c.Request.Context(), c.Param("id"), &service.UpdateRepositoryRequest{
Name: body.Name,
SourceType: body.SourceType,
@@ -512,6 +591,9 @@ func (h *RepositoryHandlers) httpUpdateRepository(c *gin.Context) {
}
func (h *RepositoryHandlers) httpDeleteRepository(c *gin.Context) {
+ if h.rejectReadOnlyRepositoryHTTP(c, c.Param("id")) {
+ return
+ }
if err := h.service.DeleteRepository(c.Request.Context(), c.Param("id")); err != nil {
if errors.Is(err, service.ErrActiveTaskSessions) {
c.JSON(http.StatusConflict, gin.H{"error": "repository is used by an active agent session"})
@@ -588,6 +670,9 @@ func (h *RepositoryHandlers) wsCreateRepository(ctx context.Context, msg *ws.Mes
if req.WorkspaceID == "" || req.Name == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workspace_id and name are required", nil)
}
+ if errMsg, blocked := h.wsRejectReadOnlyWorkspace(ctx, msg, req.WorkspaceID); blocked {
+ return errMsg, nil
+ }
repository, err := h.service.CreateRepository(ctx, &service.CreateRepositoryRequest{
WorkspaceID: req.WorkspaceID,
Name: req.Name,
@@ -664,6 +749,9 @@ func (h *RepositoryHandlers) wsUpdateRepository(ctx context.Context, msg *ws.Mes
if req.ID == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "id is required", nil)
}
+ if reason, readOnly := h.readOnlyRepositoryMessage(ctx, req.ID); readOnly {
+ return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeConflict, reason, nil)
+ }
repository, err := h.service.UpdateRepository(ctx, req.ID, &service.UpdateRepositoryRequest{
Name: req.Name,
SourceType: req.SourceType,
@@ -704,6 +792,9 @@ func (h *RepositoryHandlers) wsDeleteRepository(ctx context.Context, msg *ws.Mes
if req.ID == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "id is required", nil)
}
+ if reason, readOnly := h.readOnlyRepositoryMessage(ctx, req.ID); readOnly {
+ return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeConflict, reason, nil)
+ }
if err := h.service.DeleteRepository(ctx, req.ID); err != nil {
h.logger.Error("failed to delete repository", zap.Error(err))
if errors.Is(err, service.ErrActiveTaskSessions) {
diff --git a/apps/backend/internal/task/handlers/repository_handlers_test.go b/apps/backend/internal/task/handlers/repository_handlers_test.go
index 658f042b2f..11241b4ba4 100644
--- a/apps/backend/internal/task/handlers/repository_handlers_test.go
+++ b/apps/backend/internal/task/handlers/repository_handlers_test.go
@@ -23,6 +23,8 @@ import (
"github.com/kandev/kandev/internal/task/repository"
taskrepo "github.com/kandev/kandev/internal/task/repository/sqlite"
"github.com/kandev/kandev/internal/task/service"
+ ws "github.com/kandev/kandev/pkg/websocket"
+ "github.com/stretchr/testify/require"
)
func TestHTTPCreateRepositoryRejectsInvalidLocalPathWithoutPersistence(t *testing.T) {
@@ -540,3 +542,119 @@ func TestRepositoryUpdateRequestJSONCopyFilesPointer(t *testing.T) {
}
})
}
+
+func TestRepositoryMutationsRejectedInImproveKandevWorkspace(t *testing.T) {
+ router, repo, _ := newRepositoryHTTPTestRouterWithService(t)
+ ctx := context.Background()
+ require.NoError(t, repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-improve", Name: "Improve Kandev"}))
+
+ // Create repository -> 409.
+ body := strings.NewReader(`{"name":"new-repo","source_type":"local","local_path":"/tmp/x"}`)
+ req := httptest.NewRequest(http.MethodPost, "/api/v1/workspaces/ws-improve/repositories", body)
+ req.Header.Set("Content-Type", "application/json")
+ res := httptest.NewRecorder()
+ router.ServeHTTP(res, req)
+ require.Equal(t, http.StatusConflict, res.Code, res.Body.String())
+
+ // Initialize-local -> 409.
+ body2 := strings.NewReader(`{"name":"proj","parent_path":"/tmp"}`)
+ req2 := httptest.NewRequest(http.MethodPost, "/api/v1/workspaces/ws-improve/repositories/initialize-local", body2)
+ req2.Header.Set("Content-Type", "application/json")
+ res2 := httptest.NewRecorder()
+ router.ServeHTTP(res2, req2)
+ require.Equal(t, http.StatusConflict, res2.Code, res2.Body.String())
+
+ // A normal workspace keeps working (initialize-local succeeds).
+ okPath := t.TempDir()
+ body3 := strings.NewReader(`{"name":"ok-repo","parent_path":` + strconv.Quote(okPath) + `}`)
+ req3 := httptest.NewRequest(http.MethodPost, "/api/v1/workspaces/ws-1/repositories/initialize-local", body3)
+ req3.Header.Set("Content-Type", "application/json")
+ res3 := httptest.NewRecorder()
+ router.ServeHTTP(res3, req3)
+ require.Equal(t, http.StatusCreated, res3.Code, res3.Body.String())
+
+ // Update/delete of a repo in the improve workspace -> 409.
+ created := &models.Repository{ID: "repo-improve", WorkspaceID: "ws-improve", Name: "kandev"}
+ require.NoError(t, repo.CreateRepository(ctx, created))
+ req4 := httptest.NewRequest(http.MethodPatch, "/api/v1/repositories/repo-improve", strings.NewReader(`{"name":"renamed"}`))
+ req4.Header.Set("Content-Type", "application/json")
+ res4 := httptest.NewRecorder()
+ router.ServeHTTP(res4, req4)
+ require.Equal(t, http.StatusConflict, res4.Code, res4.Body.String())
+
+ req5 := httptest.NewRequest(http.MethodDelete, "/api/v1/repositories/repo-improve", nil)
+ res5 := httptest.NewRecorder()
+ router.ServeHTTP(res5, req5)
+ require.Equal(t, http.StatusConflict, res5.Code, res5.Body.String())
+}
+
+// TestWSRepositoryMutationsRejectedInImproveKandevWorkspace verifies the
+// WebSocket repository mutation handlers carry the same Improve Kandev
+// read-only guard as their HTTP counterparts: create by workspace id, and
+// update/delete (plus repository-script mutations) by repository workspace.
+func TestWSRepositoryMutationsRejectedInImproveKandevWorkspace(t *testing.T) {
+ _, repo, svc := newRepositoryHTTPTestRouterWithService(t)
+ ctx := context.Background()
+ require.NoError(t, repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-improve", Name: "Improve Kandev"}))
+ require.NoError(t, repo.CreateRepository(ctx, &models.Repository{
+ ID: "repo-improve", WorkspaceID: "ws-improve", Name: "kandev",
+ }))
+ log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json", OutputPath: "stdout"})
+ require.NoError(t, err)
+ h := NewRepositoryHandlers(svc, log)
+
+ assertConflict := func(t *testing.T, resp *ws.Message, err error) {
+ t.Helper()
+ require.NoError(t, err)
+ require.NotNil(t, resp)
+ require.Equal(t, ws.MessageTypeError, resp.Type)
+ var payload ws.ErrorPayload
+ require.NoError(t, json.Unmarshal(resp.Payload, &payload))
+ require.Equal(t, ws.ErrorCodeConflict, payload.Code)
+ require.Contains(t, payload.Message, "managed by Improve Kandev")
+ }
+
+ t.Run("create_rejected", func(t *testing.T) {
+ msg := &ws.Message{ID: "1", Action: ws.ActionRepositoryCreate,
+ Payload: json.RawMessage(`{"workspace_id":"ws-improve","name":"new-repo","source_type":"local","local_path":"/tmp/x"}`)}
+ resp, err := h.wsCreateRepository(ctx, msg)
+ assertConflict(t, resp, err)
+ })
+
+ t.Run("update_rejected", func(t *testing.T) {
+ msg := &ws.Message{ID: "2", Action: ws.ActionRepositoryUpdate,
+ Payload: json.RawMessage(`{"id":"repo-improve","name":"renamed"}`)}
+ resp, err := h.wsUpdateRepository(ctx, msg)
+ assertConflict(t, resp, err)
+ })
+
+ t.Run("delete_rejected", func(t *testing.T) {
+ msg := &ws.Message{ID: "3", Action: ws.ActionRepositoryDelete,
+ Payload: json.RawMessage(`{"id":"repo-improve"}`)}
+ resp, err := h.wsDeleteRepository(ctx, msg)
+ assertConflict(t, resp, err)
+ })
+
+ t.Run("script_create_rejected", func(t *testing.T) {
+ msg := &ws.Message{ID: "4", Action: ws.ActionRepositoryScriptCreate,
+ Payload: json.RawMessage(`{"repository_id":"repo-improve","name":"dev","command":"npm run dev"}`)}
+ resp, err := h.wsCreateRepositoryScript(ctx, msg)
+ assertConflict(t, resp, err)
+ })
+
+ t.Run("script_update_rejected", func(t *testing.T) {
+ script := &models.RepositoryScript{ID: "script-1", RepositoryID: "repo-improve", Name: "dev", Command: "npm run dev"}
+ require.NoError(t, repo.CreateRepositoryScript(ctx, script))
+ msg := &ws.Message{ID: "5", Action: ws.ActionRepositoryScriptUpdate,
+ Payload: json.RawMessage(`{"id":"script-1","command":"npm test"}`)}
+ resp, err := h.wsUpdateRepositoryScript(ctx, msg)
+ assertConflict(t, resp, err)
+ })
+
+ t.Run("script_delete_rejected", func(t *testing.T) {
+ msg := &ws.Message{ID: "6", Action: ws.ActionRepositoryScriptDelete,
+ Payload: json.RawMessage(`{"id":"script-1"}`)}
+ resp, err := h.wsDeleteRepositoryScript(ctx, msg)
+ assertConflict(t, resp, err)
+ })
+}
diff --git a/apps/backend/internal/task/handlers/repository_script_handlers.go b/apps/backend/internal/task/handlers/repository_script_handlers.go
index 721fcb2d45..63ceb4248b 100644
--- a/apps/backend/internal/task/handlers/repository_script_handlers.go
+++ b/apps/backend/internal/task/handlers/repository_script_handlers.go
@@ -131,6 +131,30 @@ func (h *RepositoryHandlers) wsListRepositoryScripts(ctx context.Context, msg *w
return ws.NewResponse(msg.ID, msg.Action, scriptsToListResponse(scripts))
}
+// wsRejectReadOnlyRepository returns a conflict WS error when the repository
+// lives in the dedicated Improve Kandev workspace, whose repositories (and
+// their scripts) are read-only. Lookup errors surface as not-found.
+func (h *RepositoryHandlers) wsRejectReadOnlyRepository(ctx context.Context, msg *ws.Message, repositoryID string) (*ws.Message, bool) {
+ repository, err := h.service.GetRepository(ctx, repositoryID)
+ if err != nil {
+ errMsg, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeNotFound, "Repository not found", nil)
+ return errMsg, true
+ }
+ return h.wsRejectReadOnlyWorkspace(ctx, msg, repository.WorkspaceID)
+}
+
+// wsRejectReadOnlyScript returns a conflict WS error when the script's
+// repository lives in the dedicated Improve Kandev workspace. Lookup errors
+// surface as not-found.
+func (h *RepositoryHandlers) wsRejectReadOnlyScript(ctx context.Context, msg *ws.Message, scriptID string) (*ws.Message, bool) {
+ script, err := h.service.GetRepositoryScript(ctx, scriptID)
+ if err != nil {
+ errMsg, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeNotFound, "Repository script not found", nil)
+ return errMsg, true
+ }
+ return h.wsRejectReadOnlyRepository(ctx, msg, script.RepositoryID)
+}
+
type wsCreateRepositoryScriptRequest struct {
RepositoryID string `json:"repository_id"`
Name string `json:"name"`
@@ -146,6 +170,9 @@ func (h *RepositoryHandlers) wsCreateRepositoryScript(ctx context.Context, msg *
if req.RepositoryID == "" || req.Name == "" || req.Command == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "repository_id, name, and command are required", nil)
}
+ if errMsg, blocked := h.wsRejectReadOnlyRepository(ctx, msg, req.RepositoryID); blocked {
+ return errMsg, nil
+ }
script, err := h.service.CreateRepositoryScript(ctx, &service.CreateRepositoryScriptRequest{
RepositoryID: req.RepositoryID,
Name: req.Name,
@@ -193,6 +220,9 @@ func (h *RepositoryHandlers) wsUpdateRepositoryScript(ctx context.Context, msg *
if req.ID == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "id is required", nil)
}
+ if errMsg, blocked := h.wsRejectReadOnlyScript(ctx, msg, req.ID); blocked {
+ return errMsg, nil
+ }
script, err := h.service.UpdateRepositoryScript(ctx, req.ID, &service.UpdateRepositoryScriptRequest{
Name: req.Name,
Command: req.Command,
@@ -217,6 +247,9 @@ func (h *RepositoryHandlers) wsDeleteRepositoryScript(ctx context.Context, msg *
if req.ID == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "id is required", nil)
}
+ if errMsg, blocked := h.wsRejectReadOnlyScript(ctx, msg, req.ID); blocked {
+ return errMsg, nil
+ }
if err := h.service.DeleteRepositoryScript(ctx, req.ID); err != nil {
h.logger.Error("failed to delete repository script", zap.Error(err))
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeNotFound, "Repository script not found", nil)
diff --git a/apps/backend/internal/task/handlers/workflow_handlers.go b/apps/backend/internal/task/handlers/workflow_handlers.go
index bb55dc82fb..8232044aab 100644
--- a/apps/backend/internal/task/handlers/workflow_handlers.go
+++ b/apps/backend/internal/task/handlers/workflow_handlers.go
@@ -168,6 +168,9 @@ func (h *WorkflowHandlers) httpCreateWorkflow(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "workspace_id and name are required"})
return
}
+ if h.rejectReadOnlyWorkspaceHTTP(c, body.WorkspaceID) {
+ return
+ }
workflow, err := h.service.CreateWorkflow(c.Request.Context(), &service.CreateWorkflowRequest{
WorkspaceID: body.WorkspaceID,
Name: body.Name,
@@ -188,30 +191,79 @@ func (h *WorkflowHandlers) httpCreateWorkflow(c *gin.Context) {
// service layer directly and never hits these handlers.
const workflowReadOnlyMsg = "workflow is managed by GitHub sync and is read-only; edit its definition in the synced repository"
-// isWorkflowReadOnly reports whether the workflow is managed by workflow
-// sync. Lookup errors surface as (false, err) so callers keep their existing
-// not-found handling.
-func (h *WorkflowHandlers) isWorkflowReadOnly(ctx context.Context, id string) (bool, error) {
+// workspaceReadOnlyMsg is returned when a UI mutation targets the dedicated
+// Improve Kandev workspace, whose workflows and repositories are read-only.
+const workspaceReadOnlyMsg = "this workspace is managed by Improve Kandev and is read-only"
+
+// readOnlyWorkflowMessage returns the reason a workflow is read-only, when it
+// is: GitHub-sync-managed workflows and workflows living in the dedicated
+// Improve Kandev workspace are both immutable. Lookup errors surface as
+// ("", false) so callers keep their existing not-found handling.
+func (h *WorkflowHandlers) readOnlyWorkflowMessage(ctx context.Context, id string) (string, bool) {
workflow, err := h.service.GetWorkflow(ctx, id)
if err != nil {
- return false, err
+ return "", false
}
- return workflow.Source == models.WorkflowSourceGitHub, nil
+ if workflow.Source == models.WorkflowSourceGitHub {
+ return workflowReadOnlyMsg, true
+ }
+ if workflow.WorkspaceID != "" {
+ workspace, err := h.service.GetWorkspace(ctx, workflow.WorkspaceID)
+ if err != nil {
+ return "", false
+ }
+ if workspace.IsImproveKandev() {
+ return workspaceReadOnlyMsg, true
+ }
+ }
+ return "", false
}
func (h *WorkflowHandlers) rejectReadOnlyWorkflowHTTP(c *gin.Context, id string) bool {
- readOnly, err := h.isWorkflowReadOnly(c.Request.Context(), id)
- if err != nil {
- handleNotFound(c, h.logger, err, "workflow not found")
- return true
- }
- if readOnly {
- c.JSON(http.StatusConflict, gin.H{"error": workflowReadOnlyMsg})
+ if msg, readOnly := h.readOnlyWorkflowMessage(c.Request.Context(), id); readOnly {
+ c.JSON(http.StatusConflict, gin.H{"error": msg})
return true
}
return false
}
+// rejectReadOnlyWorkspaceHTTP returns 409 when the workspace is the dedicated
+// Improve Kandev workspace (matched by exact name). Lookup errors surface as
+// not-found so callers keep their existing error handling.
+func (h *WorkflowHandlers) rejectReadOnlyWorkspaceHTTP(c *gin.Context, workspaceID string) bool {
+ if workspaceID == "" {
+ return false
+ }
+ workspace, err := h.service.GetWorkspace(c.Request.Context(), workspaceID)
+ if err != nil {
+ handleNotFound(c, h.logger, err, "workspace not found")
+ return true
+ }
+ if workspace.IsImproveKandev() {
+ c.JSON(http.StatusConflict, gin.H{"error": workspaceReadOnlyMsg})
+ return true
+ }
+ return false
+}
+
+// wsRejectReadOnlyWorkspace returns a conflict WS error when the workspace is
+// the dedicated Improve Kandev workspace. Returns (nil, false) when allowed.
+func (h *WorkflowHandlers) wsRejectReadOnlyWorkspace(ctx context.Context, msg *ws.Message, workspaceID string) (*ws.Message, bool) {
+ if workspaceID == "" {
+ return nil, false
+ }
+ workspace, err := h.service.GetWorkspace(ctx, workspaceID)
+ if err != nil {
+ errMsg, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeNotFound, "Workspace not found", nil)
+ return errMsg, true
+ }
+ if workspace.IsImproveKandev() {
+ errMsg, _ := ws.NewError(msg.ID, msg.Action, ws.ErrorCodeConflict, workspaceReadOnlyMsg, nil)
+ return errMsg, true
+ }
+ return nil, false
+}
+
type httpUpdateWorkflowRequest struct {
Name *string `json:"name"`
Description *string `json:"description"`
@@ -404,6 +456,9 @@ func (h *WorkflowHandlers) wsCreateWorkflow(ctx context.Context, msg *ws.Message
if req.WorkspaceID == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workspace_id is required", nil)
}
+ if errMsg, blocked := h.wsRejectReadOnlyWorkspace(ctx, msg, req.WorkspaceID); blocked {
+ return errMsg, nil
+ }
workflow, err := h.service.CreateWorkflow(ctx, &service.CreateWorkflowRequest{
WorkspaceID: req.WorkspaceID,
@@ -455,8 +510,8 @@ func (h *WorkflowHandlers) wsUpdateWorkflow(ctx context.Context, msg *ws.Message
if req.ID == "" {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "id is required", nil)
}
- if readOnly, roErr := h.isWorkflowReadOnly(ctx, req.ID); roErr == nil && readOnly {
- return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeConflict, workflowReadOnlyMsg, nil)
+ if reason, readOnly := h.readOnlyWorkflowMessage(ctx, req.ID); readOnly {
+ return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeConflict, reason, nil)
}
workflow, err := h.service.UpdateWorkflow(ctx, req.ID, &service.UpdateWorkflowRequest{
@@ -479,8 +534,8 @@ func (h *WorkflowHandlers) wsDeleteWorkflow(ctx context.Context, msg *ws.Message
ID string `json:"id"`
}
if err := msg.ParsePayload(&req); err == nil && req.ID != "" {
- if readOnly, roErr := h.isWorkflowReadOnly(ctx, req.ID); roErr == nil && readOnly {
- return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeConflict, workflowReadOnlyMsg, nil)
+ if reason, readOnly := h.readOnlyWorkflowMessage(ctx, req.ID); readOnly {
+ return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeConflict, reason, nil)
}
}
return wsHandleIDRequest(ctx, msg, h.logger, "failed to delete workflow",
@@ -507,6 +562,9 @@ func (h *WorkflowHandlers) httpReorderWorkflows(c *gin.Context) {
c.JSON(http.StatusBadRequest, gin.H{"error": "workflow_ids is required"})
return
}
+ if h.rejectReadOnlyWorkspaceHTTP(c, workspaceID) {
+ return
+ }
if err := h.service.ReorderWorkflows(c.Request.Context(), workspaceID, req.WorkflowIDs); err != nil {
h.logger.Error("failed to reorder workflows", zap.Error(err))
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to reorder workflows"})
@@ -529,6 +587,9 @@ func (h *WorkflowHandlers) wsReorderWorkflows(ctx context.Context, msg *ws.Messa
if len(req.WorkflowIDs) == 0 {
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workflow_ids is required", nil)
}
+ if errMsg, blocked := h.wsRejectReadOnlyWorkspace(ctx, msg, req.WorkspaceID); blocked {
+ return errMsg, nil
+ }
if err := h.service.ReorderWorkflows(ctx, req.WorkspaceID, req.WorkflowIDs); err != nil {
h.logger.Error("failed to reorder workflows", zap.Error(err))
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to reorder workflows", nil)
diff --git a/apps/backend/internal/task/models/models.go b/apps/backend/internal/task/models/models.go
index 783bc46d48..c5a41ca09f 100644
--- a/apps/backend/internal/task/models/models.go
+++ b/apps/backend/internal/task/models/models.go
@@ -690,6 +690,18 @@ type Workflow struct {
UpdatedAt time.Time `json:"updated_at"`
}
+// WorkspaceNameImproveKandev is the exact name of the dedicated Improve Kandev
+// workspace created by the improve-kandev bootstrap. The workspace is matched
+// by this name everywhere (bootstrap, guards, frontend) and is
+// configuration-immutable: its workflows and repositories are read-only.
+const WorkspaceNameImproveKandev = "Improve Kandev"
+
+// IsImproveKandev reports whether the workspace is the dedicated Improve
+// Kandev workspace (matched by exact name).
+func (w *Workspace) IsImproveKandev() bool {
+ return w != nil && w.Name == WorkspaceNameImproveKandev
+}
+
// Workspace represents a workspace
type Workspace struct {
ID string `json:"id"`
diff --git a/apps/backend/internal/workflow/handlers/handlers.go b/apps/backend/internal/workflow/handlers/handlers.go
index 6ddc782bdb..e824b4b0bc 100644
--- a/apps/backend/internal/workflow/handlers/handlers.go
+++ b/apps/backend/internal/workflow/handlers/handlers.go
@@ -191,7 +191,7 @@ func (h *Handlers) httpUpdateStep(c *gin.Context) {
}
func (h *Handlers) writeStepMutationError(c *gin.Context, err error) {
- if errors.Is(err, service.ErrWorkflowReadOnly) {
+ if errors.Is(err, service.ErrWorkflowReadOnly) || errors.Is(err, service.ErrWorkflowWorkspaceReadOnly) {
c.JSON(http.StatusConflict, gin.H{"error": err.Error()})
return
}
diff --git a/apps/backend/internal/workflow/service/readonly.go b/apps/backend/internal/workflow/service/readonly.go
index 6df174ec6b..99e4ad6e58 100644
--- a/apps/backend/internal/workflow/service/readonly.go
+++ b/apps/backend/internal/workflow/service/readonly.go
@@ -12,24 +12,40 @@ import (
// never hits the guarded controller/handler paths.
var ErrWorkflowReadOnly = errors.New("workflow is managed by GitHub sync and is read-only; edit its definition in the synced repository")
+// ErrWorkflowWorkspaceReadOnly rejects UI mutations of workflows that live in
+// the dedicated Improve Kandev workspace, whose workflows are read-only. The
+// message is the canonical user-facing string shared with the handler layer
+// (task/handlers `workspaceReadOnlyMsg`), so both layers surface identical
+// wording for the same restriction.
+var ErrWorkflowWorkspaceReadOnly = errors.New("this workspace is managed by Improve Kandev and is read-only")
+
// EnsureWorkflowMutable returns ErrWorkflowReadOnly when the workflow's
-// definition is owned by workflow sync (source == "github"). UI-facing
-// mutation paths (step CRUD, template application) call this before writing.
+// definition is owned by workflow sync (source == "github"), and
+// ErrWorkflowWorkspaceReadOnly when the workflow lives in the read-only
+// Improve Kandev workspace. UI-facing mutation paths (step CRUD, template
+// application) call this before writing.
//
-// The guard fails open when the workflow can't be resolved: its only job is
-// to block GitHub-managed workflows, the underlying mutation surfaces real
-// not-found errors itself, and callers like the MCP handlers operate on
-// workflows the wired provider may not track.
+// The guard fails open when the workflow or workspace can't be resolved: its
+// only job is to block GitHub-managed workflows and improve-workspace
+// workflows, the underlying mutation surfaces real not-found errors itself,
+// and callers like the MCP handlers operate on workflows the wired provider
+// may not track.
func (s *Service) EnsureWorkflowMutable(ctx context.Context, workflowID string) error {
if s.workflowProvider == nil {
return nil
}
wf, err := s.workflowProvider.GetWorkflow(ctx, workflowID)
if err != nil {
- return nil //nolint:nilerr // fail open: guard only blocks resolved github-sourced workflows
+ return nil //nolint:nilerr // fail open: guard only blocks resolved workflows
}
if wf.Source == taskmodels.WorkflowSourceGitHub {
return ErrWorkflowReadOnly
}
+ if s.workspaceProvider != nil && wf.WorkspaceID != "" {
+ workspace, wsErr := s.workspaceProvider.GetWorkspace(ctx, wf.WorkspaceID)
+ if wsErr == nil && workspace != nil && workspace.IsImproveKandev() {
+ return ErrWorkflowWorkspaceReadOnly
+ }
+ }
return nil
}
diff --git a/apps/backend/internal/workflow/service/service.go b/apps/backend/internal/workflow/service/service.go
index 765ec19bc6..975252fc40 100644
--- a/apps/backend/internal/workflow/service/service.go
+++ b/apps/backend/internal/workflow/service/service.go
@@ -25,12 +25,19 @@ type WorkflowProvider interface {
// Service provides workflow business logic
type Service struct {
- repo *repository.Repository
- logger *logger.Logger
- workflowProvider WorkflowProvider
- resolveProfile models.AgentProfileResolver
- matchProfile models.AgentProfileMatcher
- syncOps SyncWorkflowOps
+ repo *repository.Repository
+ logger *logger.Logger
+ workflowProvider WorkflowProvider
+ workspaceProvider WorkspaceProvider
+ resolveProfile models.AgentProfileResolver
+ matchProfile models.AgentProfileMatcher
+ syncOps SyncWorkflowOps
+}
+
+// WorkspaceProvider resolves a workspace by ID so the read-only guard can tell
+// whether a workflow lives in the dedicated Improve Kandev workspace.
+type WorkspaceProvider interface {
+ GetWorkspace(ctx context.Context, id string) (*taskmodels.Workspace, error)
}
// SetWorkflowProvider wires the workflow provider (set during service init to break circular deps).
@@ -38,6 +45,12 @@ func (s *Service) SetWorkflowProvider(wp WorkflowProvider) {
s.workflowProvider = wp
}
+// SetWorkspaceProvider wires the workspace provider used by the read-only guard
+// (set during service init to break circular deps).
+func (s *Service) SetWorkspaceProvider(wp WorkspaceProvider) {
+ s.workspaceProvider = wp
+}
+
// SetAgentProfileFuncs wires the agent profile resolver and matcher for export/import.
func (s *Service) SetAgentProfileFuncs(resolve models.AgentProfileResolver, match models.AgentProfileMatcher) {
s.resolveProfile = resolve
diff --git a/apps/backend/internal/workflow/service/sync_apply_test.go b/apps/backend/internal/workflow/service/sync_apply_test.go
index 69be8e5f7d..1884dda982 100644
--- a/apps/backend/internal/workflow/service/sync_apply_test.go
+++ b/apps/backend/internal/workflow/service/sync_apply_test.go
@@ -446,6 +446,33 @@ func TestEnsureWorkflowMutable(t *testing.T) {
"guard fails open on lookup errors; the mutation itself surfaces not-found")
}
+func TestEnsureWorkflowMutable_BlocksImproveWorkspace(t *testing.T) {
+ svc, provider, _ := setupSyncService(t)
+ ctx := context.Background()
+ provider.addWorkflow("wf-improve", "ws-improve", "Improve Kandev Workflow")
+ svc.SetWorkspaceProvider(&fakeWorkspaceProvider{
+ workspaces: map[string]*taskmodels.Workspace{
+ "ws-improve": {ID: "ws-improve", Name: "Improve Kandev"},
+ "ws-normal": {ID: "ws-normal", Name: "Default Workspace"},
+ },
+ })
+ provider.addWorkflow("wf-normal", "ws-normal", "Normal Flow")
+
+ assert.ErrorIs(t, svc.EnsureWorkflowMutable(ctx, "wf-improve"), ErrWorkflowWorkspaceReadOnly)
+ assert.NoError(t, svc.EnsureWorkflowMutable(ctx, "wf-normal"))
+}
+
+type fakeWorkspaceProvider struct {
+ workspaces map[string]*taskmodels.Workspace
+}
+
+func (f *fakeWorkspaceProvider) GetWorkspace(_ context.Context, id string) (*taskmodels.Workspace, error) {
+ if workspace, ok := f.workspaces[id]; ok {
+ return workspace, nil
+ }
+ return nil, fmt.Errorf("workspace not found: %s", id)
+}
+
func TestReleaseSyncedWorkflows(t *testing.T) {
svc, provider, _ := setupSyncService(t)
ctx := context.Background()
diff --git a/apps/web/app/settings/workspace/workspace-repositories-client.tsx b/apps/web/app/settings/workspace/workspace-repositories-client.tsx
index 095524a337..4396444d29 100644
--- a/apps/web/app/settings/workspace/workspace-repositories-client.tsx
+++ b/apps/web/app/settings/workspace/workspace-repositories-client.tsx
@@ -1,9 +1,9 @@
"use client";
import { useMemo, useState } from "react";
+import { WorkspaceSettingsHeader } from "@/app/settings/workspace/workspace-settings-header";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
-import Link from "@/components/routing/app-link";
import { useRouter } from "@/lib/routing/client-router";
import { IconGitBranch } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
@@ -50,6 +50,8 @@ type RepositoryItem = RepositoryWithScripts & { __autoOpen?: boolean };
type WorkspaceRepositoriesClientProps = {
workspace: Workspace | null;
repositories: RepositoryWithScripts[];
+ /** The dedicated Improve Kandev workspace is configuration-immutable. */
+ isImproveWorkspace?: boolean;
};
function buildDraftRepo(
@@ -518,9 +520,13 @@ function useWorkspaceRepositoriesPage(
export function WorkspaceRepositoriesClient({
workspace,
repositories,
+ isImproveWorkspace = false,
}: WorkspaceRepositoriesClientProps) {
- const state = useWorkspaceRepositoriesPage(workspace, repositories);
const { t } = useTranslation();
+ const pageDescription = isImproveWorkspace
+ ? t("workspaces:repositoriesReadOnlyImprove")
+ : t("workspaces:manageRepositoriesConnected");
+ const state = useWorkspaceRepositoriesPage(workspace, repositories);
const {
router,
repositoryItems,
@@ -554,28 +560,18 @@ export function WorkspaceRepositoriesClient({
return (
-
-
-
{workspace.name}
-
- {t("workspaces:manageRepositoriesConnected")}
-
-
-
-
+
}
title={t("workspaces:repositories")}
description={t("workspaces:repositoriesInThisWorkspace")}
action={
-
+ isImproveWorkspace ? undefined : (
+
+ )
}
>
@@ -587,6 +583,7 @@ export function WorkspaceRepositoriesClient({
isRepositoryDirty={isRepositoryDirty(repo, savedRepositoriesById.get(repo.id))}
areScriptsDirty={areRepositoryScriptsDirty(repo, savedRepositoriesById.get(repo.id))}
autoOpen={Boolean(repo.__autoOpen)}
+ readOnly={isImproveWorkspace}
onUpdate={handleUpdateRepository}
onAddScript={handleAddRepositoryScript}
onUpdateScript={handleUpdateRepositoryScript}
@@ -597,23 +594,25 @@ export function WorkspaceRepositoriesClient({
))}
-
+ {!isImproveWorkspace && (
+
+ )}
);
}
diff --git a/apps/web/app/settings/workspace/workspace-settings-header.tsx b/apps/web/app/settings/workspace/workspace-settings-header.tsx
new file mode 100644
index 0000000000..caf29acd67
--- /dev/null
+++ b/apps/web/app/settings/workspace/workspace-settings-header.tsx
@@ -0,0 +1,29 @@
+"use client";
+
+import Link from "@/components/routing/app-link";
+import { Button } from "@kandev/ui/button";
+import { useTranslation } from "react-i18next";
+import type { Workspace } from "@/lib/types/http";
+
+export function WorkspaceSettingsHeader({
+ workspace,
+ description,
+}: {
+ workspace: Workspace;
+ description: string;
+}) {
+ const { t } = useTranslation();
+ return (
+
+
+
{workspace.name}
+
{description}
+
+
+
+ );
+}
diff --git a/apps/web/app/settings/workspace/workspace-workflows-client.tsx b/apps/web/app/settings/workspace/workspace-workflows-client.tsx
index 1472a6d071..4a32ee3dfa 100644
--- a/apps/web/app/settings/workspace/workspace-workflows-client.tsx
+++ b/apps/web/app/settings/workspace/workspace-workflows-client.tsx
@@ -28,7 +28,6 @@ import { WorkflowCard } from "@/components/settings/workflow-card";
import { WorkflowSectionActions } from "@/components/settings/workflow-section-actions";
import { WorkflowSyncSection } from "@/components/settings/workflow-sync-section";
import { useSettingsSaveContributor } from "@/components/settings/settings-save-provider";
-import { WorkflowExportDialog } from "@/components/settings/workflow-export-dialog";
import { useToast } from "@/components/toast-provider";
import { useWorkflowSettings } from "@/hooks/domains/settings/use-workflow-settings";
import {
@@ -44,10 +43,7 @@ import {
type Workspace,
type WorkflowTemplate,
} from "@/lib/types/http";
-import {
- CreateWorkflowDialog,
- ImportWorkflowsDialog,
-} from "@/app/settings/workspace/workspace-workflows-dialogs";
+import { WorkflowDialogs } from "@/app/settings/workspace/workspace-workflows-dialogs";
import { useWorkflowCreation } from "@/app/settings/workspace/use-workflow-creation";
import { WorkspaceNotFoundCard } from "@/app/settings/workspace/workspace-not-found-card";
@@ -55,6 +51,8 @@ type WorkspaceWorkflowsClientProps = {
workspace: Workspace | null;
workflows: Workflow[];
workflowTemplates: WorkflowTemplate[];
+ /** The dedicated Improve Kandev workspace is configuration-immutable. */
+ isImproveWorkspace?: boolean;
};
const TEMP_WORKFLOW_PREFIX = "temp-workflow-";
@@ -292,6 +290,8 @@ type WorkflowListProps = {
orderDirtyIds: ReadonlySet;
initialStepsByWorkflowId: Map;
isWorkflowDirty: (wf: Workflow) => boolean;
+ /** The dedicated Improve Kandev workspace renders workflows read-only. */
+ isImproveWorkspace?: boolean;
onUpdate: (
id: string,
u: { name?: string; description?: string; agent_profile_id?: string },
@@ -305,14 +305,17 @@ type WorkflowListProps = {
function SortableWorkflowItem({
workflow,
isDirty,
+ readOnly,
children,
}: {
workflow: Workflow;
isDirty: boolean;
+ readOnly?: boolean;
children: React.ReactNode;
}) {
const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({
id: workflow.id,
+ disabled: readOnly,
});
const style = {
transform: CSS.Transform.toString(transform),
@@ -328,14 +331,16 @@ function SortableWorkflowItem({
data-settings-dirty-level="container"
data-testid={`workflow-order-item-${workflow.id}`}
>
-
-
-
+ {!readOnly && (
+
+
+
+ )}
{children}
);
@@ -347,6 +352,7 @@ function WorkflowList({
orderDirtyIds,
initialStepsByWorkflowId,
isWorkflowDirty,
+ isImproveWorkspace,
onUpdate,
onDelete,
onWorkflowSaved,
@@ -386,6 +392,7 @@ function WorkflowList({
key={workflow.id}
workflow={workflow}
isDirty={orderDirtyIds.has(workflow.id)}
+ readOnly={isImproveWorkspace}
>
w.id !== workflow.id)}
+ isImproveWorkspace={isImproveWorkspace}
onUpdateWorkflow={(updates) => onUpdate(workflow.id, updates)}
onDeleteWorkflow={async () => {
await onDelete(workflow.id);
@@ -409,45 +417,11 @@ function WorkflowList({
);
}
-function WorkflowDialogs({ page }: { page: ReturnType }) {
- const { t } = useTranslation();
- return (
- <>
-
-
-
- >
- );
-}
-
export function WorkspaceWorkflowsClient({
workspace,
workflows,
workflowTemplates,
+ isImproveWorkspace = false,
}: WorkspaceWorkflowsClientProps) {
const { t } = useTranslation();
const page = useWorkspaceWorkflowsPage(workspace, workflows, workflowTemplates);
@@ -462,7 +436,9 @@ export function WorkspaceWorkflowsClient({
{workspace.name}
- {t("workflows:manageWorkflowsForThisWorkspace")}
+ {isImproveWorkspace
+ ? t("workflows:workflowsReadOnlyImprove")
+ : t("workflows:manageWorkflowsForThisWorkspace")}