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")}

+ + + + + + ); +} + function IntroBullet({ children }: { children: React.ReactNode }) { return (
  • @@ -373,3 +502,112 @@ function readSkipIntro(): boolean { return false; } } + +// useResetOnClose restores the dialog to a fresh state whenever the parent +// closes it, so a re-open re-runs the auth check and workspace-choice flow. +// The setters are read through a ref so the effect only runs on `open` changes +// (the setters object literal would otherwise re-trigger it every render). +function useResetOnClose( + open: boolean, + setters: { + setMode: (mode: Mode) => void; + setSkipIntro: (skip: boolean) => void; + setAuth: (auth: AuthState) => void; + setBootstrap: (bootstrap: BootstrapState) => void; + setCaptureLogs: (capture: boolean) => void; + setCreateWorkspace: (create: boolean) => void; + setWorkspaceChoiceConfirmed: (confirmed: boolean) => void; + }, +) { + const settersRef = useRef(setters); + settersRef.current = setters; + useEffect(() => { + if (open) return; + const s = settersRef.current; + /* eslint-disable react-hooks/set-state-in-effect */ + s.setMode(initialImproveKandevMode(readSkipIntro())); + s.setSkipIntro(readSkipIntro()); + s.setAuth({ kind: "checking" }); + s.setBootstrap({ kind: "idle" }); + s.setCaptureLogs(true); + s.setCreateWorkspace(true); + s.setWorkspaceChoiceConfirmed(false); + /* eslint-enable react-hooks/set-state-in-effect */ + }, [open]); +} + +// ImproveKandevCreateStage renders the create stage: the workspace-choice gate +// when the dedicated workspace does not exist yet, otherwise the create form. +function ImproveKandevCreateStage({ + open, + onOpenChange, + workspaceId, + bootstrap, + captureLogs, + setCaptureLogs, + onSuccess, + externalBlockedReason, + improveWorkspaceMissing, + workspaceChoiceConfirmed, + createWorkspace, + onCreateWorkspaceChange, + onConfirmWorkspaceChoice, + onCancel, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + workspaceId: string | null; + bootstrap: BootstrapState; + captureLogs: boolean; + setCaptureLogs: (capture: boolean) => void; + onSuccess?: (task: Task) => void; + externalBlockedReason: string | null; + improveWorkspaceMissing: boolean; + workspaceChoiceConfirmed: boolean; + createWorkspace: boolean; + onCreateWorkspaceChange: (checked: boolean) => void; + onConfirmWorkspaceChoice: () => void; + onCancel: () => void; +}) { + const handleSuccess = useCallback( + (task: Task) => { + onOpenChange(false); + onSuccess?.(task); + }, + [onOpenChange, onSuccess], + ); + + const transformDescription = useCallback( + async (description: string) => { + if (bootstrap.kind !== "ready") return description; + return buildImproveKandevDescription(description, bootstrap.data, captureLogs); + }, + [bootstrap, captureLogs], + ); + + if (improveWorkspaceMissing && !workspaceChoiceConfirmed) { + return ( + + ); + } + return ( + + ); +} diff --git a/apps/web/components/settings/repository-card-preview.tsx b/apps/web/components/settings/repository-card-preview.tsx new file mode 100644 index 0000000000..d618ae5a5a --- /dev/null +++ b/apps/web/components/settings/repository-card-preview.tsx @@ -0,0 +1,155 @@ +"use client"; + +import { useTranslation } from "react-i18next"; +import type { TFunction } from "i18next"; +import { IconEdit, IconGitBranch, IconTrash } from "@tabler/icons-react"; +import { Badge } from "@kandev/ui/badge"; +import { CardContent } from "@kandev/ui/card"; +import { Button } from "@kandev/ui/button"; +import { UnsavedChangesBadge } from "@/components/settings/unsaved-indicator"; +import { SettingsCard } from "@/components/settings/settings-card"; +import type { Repository, RepositoryScript } from "@/lib/types/http"; + +type RepositoryWithScripts = Repository & { scripts: RepositoryScript[] }; + +type RepositoryPreviewProps = { + repository: RepositoryWithScripts; + isDirty: boolean; + deleteLoading: boolean; + onOpenDelete: () => void; + open: () => void; +}; + +// These two build every string in the collapsed card, and neither holds JSX, so +// `i18next/no-literal-string` could never see any of it — the lint count for this +// file reported zero for the whole block. `t` is a parameter rather than the +// module-level import so each label resolves when the card renders. +function buildRepoScriptsSummary(t: TFunction, repository: RepositoryWithScripts) { + const setupScript = repository.setup_script ?? ""; + const cleanupScript = repository.cleanup_script ?? ""; + const devScript = repository.dev_script ?? ""; + const scriptsCount = repository.scripts.length; + const hasSetupScript = Boolean(setupScript.trim()); + const hasCleanupScript = Boolean(cleanupScript.trim()); + const hasDevScript = Boolean(devScript.trim()); + const showScriptsSummary = scriptsCount > 0 || hasSetupScript || hasCleanupScript || hasDevScript; + // Was `custom script${count === 1 ? "" : "s"}` — an English morpheme built at + // the call site, which leaves a translator no way to express a third form. + const scriptsLabel = + scriptsCount === 0 + ? t("workspaces:noCustomScripts") + : t("workspaces:customScripts", { count: scriptsCount }); + return { + scriptsCount, + hasSetupScript, + hasCleanupScript, + hasDevScript, + showScriptsSummary, + scriptsLabel, + }; +} + +function buildRepoPreviewData(t: TFunction, repository: RepositoryWithScripts) { + const repositoryName = repository.name ?? ""; + // `source_type` is the wire value; only its badge label is copy. + const sourceLabel = + repository.source_type === "local" ? t("workspaces:sourceLocal") : t("workspaces:sourceRemote"); + // The path and the `owner/name` slug are user data / git metadata; only the + // two "nothing recorded" fallbacks are copy. + const subtitle = + repository.source_type === "local" + ? repository.local_path || t("workspaces:localPathNotSet") + : [repository.provider_owner, repository.provider_name].filter(Boolean).join("/") || + repository.provider || + t("workspaces:remoteRepository"); + return { + repositoryName, + sourceLabel, + subtitle, + ...buildRepoScriptsSummary(t, repository), + }; +} + +export function RepositoryPreview({ + repository, + isDirty, + deleteLoading, + onOpenDelete, + open, +}: RepositoryPreviewProps) { + const { t } = useTranslation(); + const { + repositoryName, + scriptsCount, + hasSetupScript, + hasCleanupScript, + hasDevScript, + showScriptsSummary, + scriptsLabel, + sourceLabel, + subtitle, + } = buildRepoPreviewData(t, repository); + + return ( + + +
    +
    +
    + +
    +
    +
    +

    + {repositoryName || t("workspaces:untitledRepository")} +

    + + {sourceLabel} + + {isDirty && } +
    +
    {subtitle}
    + {showScriptsSummary ? ( +
    + {scriptsCount > 0 && {scriptsLabel}} + {hasSetupScript && {t("workspaces:buildScriptChip")}} + {hasCleanupScript && {t("workspaces:cleanupScriptChip")}} + {hasDevScript && {t("workspaces:devScriptChip")}} +
    + ) : null} +
    +
    +
    + + +
    +
    +
    +
    + ); +} diff --git a/apps/web/components/settings/repository-card.tsx b/apps/web/components/settings/repository-card.tsx index 252668c5b9..e7e7a446cc 100644 --- a/apps/web/components/settings/repository-card.tsx +++ b/apps/web/components/settings/repository-card.tsx @@ -3,8 +3,7 @@ import { useState } from "react"; import { Trans, useTranslation } from "react-i18next"; import type { TFunction } from "i18next"; -import { IconEdit, IconGitBranch, IconTrash, IconX } from "@tabler/icons-react"; -import { Badge } from "@kandev/ui/badge"; +import { IconGitBranch, IconTrash, IconX } from "@tabler/icons-react"; import { CardContent } from "@kandev/ui/card"; import { Button } from "@kandev/ui/button"; import { Checkbox } from "@kandev/ui/checkbox"; @@ -16,6 +15,7 @@ import { useToast } from "@/components/toast-provider"; import { UnsavedChangesBadge } from "@/components/settings/unsaved-indicator"; import { useSettingsSaveContributor } from "@/components/settings/settings-save-provider"; import { SettingsCard } from "@/components/settings/settings-card"; +import { RepositoryPreview } from "@/components/settings/repository-card-preview"; import { EditableCard } from "@/components/settings/editable-card"; import { RepositoryBranchTemplateHelp } from "@/components/settings/repository-branch-template-help"; import { DeleteRepositoryDialog } from "@/components/settings/repository-delete-dialog"; @@ -322,64 +322,6 @@ function RepositoryEditView({ ); } -type RepositoryPreviewProps = { - repository: RepositoryWithScripts; - isDirty: boolean; - deleteLoading: boolean; - onOpenDelete: () => void; - open: () => void; -}; - -// These two build every string in the collapsed card, and neither holds JSX, so -// `i18next/no-literal-string` could never see any of it — the lint count for this -// file reported zero for the whole block. `t` is a parameter rather than the -// module-level import so each label resolves when the card renders. -function buildRepoScriptsSummary(t: TFunction, repository: RepositoryWithScripts) { - const setupScript = repository.setup_script ?? ""; - const cleanupScript = repository.cleanup_script ?? ""; - const devScript = repository.dev_script ?? ""; - const scriptsCount = repository.scripts.length; - const hasSetupScript = Boolean(setupScript.trim()); - const hasCleanupScript = Boolean(cleanupScript.trim()); - const hasDevScript = Boolean(devScript.trim()); - const showScriptsSummary = scriptsCount > 0 || hasSetupScript || hasCleanupScript || hasDevScript; - // Was `custom script${count === 1 ? "" : "s"}` — an English morpheme built at - // the call site, which leaves a translator no way to express a third form. - const scriptsLabel = - scriptsCount === 0 - ? t("workspaces:noCustomScripts") - : t("workspaces:customScripts", { count: scriptsCount }); - return { - scriptsCount, - hasSetupScript, - hasCleanupScript, - hasDevScript, - showScriptsSummary, - scriptsLabel, - }; -} - -function buildRepoPreviewData(t: TFunction, repository: RepositoryWithScripts) { - const repositoryName = repository.name ?? ""; - // `source_type` is the wire value; only its badge label is copy. - const sourceLabel = - repository.source_type === "local" ? t("workspaces:sourceLocal") : t("workspaces:sourceRemote"); - // The path and the `owner/name` slug are user data / git metadata; only the - // two "nothing recorded" fallbacks are copy. - const subtitle = - repository.source_type === "local" - ? repository.local_path || t("workspaces:localPathNotSet") - : [repository.provider_owner, repository.provider_name].filter(Boolean).join("/") || - repository.provider || - t("workspaces:remoteRepository"); - return { - repositoryName, - sourceLabel, - subtitle, - ...buildRepoScriptsSummary(t, repository), - }; -} - function repositorySecretInvalidReason( t: TFunction, validation: ReturnType, @@ -397,96 +339,14 @@ function repositorySecretInvalidReason( } } -function RepositoryPreview({ - repository, - isDirty, - deleteLoading, - onOpenDelete, - open, -}: RepositoryPreviewProps) { - const { t } = useTranslation(); - const { - repositoryName, - scriptsCount, - hasSetupScript, - hasCleanupScript, - hasDevScript, - showScriptsSummary, - scriptsLabel, - sourceLabel, - subtitle, - } = buildRepoPreviewData(t, repository); - - return ( - - -
    -
    -
    - -
    -
    -
    -

    - {repositoryName || t("workspaces:untitledRepository")} -

    - - {sourceLabel} - - {isDirty && } -
    -
    {subtitle}
    - {showScriptsSummary ? ( -
    - {scriptsCount > 0 && {scriptsLabel}} - {hasSetupScript && {t("workspaces:buildScriptChip")}} - {hasCleanupScript && {t("workspaces:cleanupScriptChip")}} - {hasDevScript && {t("workspaces:devScriptChip")}} -
    - ) : null} -
    -
    -
    - - -
    -
    -
    -
    - ); -} - type RepositoryCardProps = { repository: RepositoryWithScripts; savedRepository?: RepositoryWithScripts; isRepositoryDirty: boolean; areScriptsDirty: boolean; autoOpen?: boolean; + /** Repositories in the dedicated Improve Kandev workspace are read-only. */ + readOnly?: boolean; onUpdate: (repoId: string, updates: Partial) => void; onAddScript: (repoId: string) => void; onUpdateScript: (repoId: string, scriptId: string, updates: Partial) => void; @@ -565,6 +425,7 @@ export function RepositoryCard({ isRepositoryDirty, areScriptsDirty, autoOpen = false, + readOnly = false, onUpdate, onAddScript, onUpdateScript, @@ -603,6 +464,20 @@ export function RepositoryCard({ discard: () => undefined, }); + // Read-only (dedicated Improve Kandev workspace): show the repository + // without edit/delete affordances. + if (readOnly) { + return ( + {}} + open={() => {}} + /> + ); + } + return ( <> ) => Promise; handleAddWorkflowStep: () => Promise; @@ -237,6 +241,42 @@ type WorkflowCardBodyProps = { readOnly: boolean; }; +function WorkflowNameField({ + workflow, + savedWorkflow, + onUpdateWorkflow, + readOnly, + isImproveWorkspace, +}: Pick< + WorkflowCardBodyProps, + "workflow" | "savedWorkflow" | "onUpdateWorkflow" | "readOnly" | "isImproveWorkspace" +>) { + const { t } = useTranslation(); + return ( +
    + + onUpdateWorkflow({ name: e.target.value })} + disabled={readOnly} + data-settings-dirty={isWorkflowFieldDirty(workflow, savedWorkflow, "name")} + /> +
    + ); +} + function WorkflowCardBody({ workflow, savedWorkflow, @@ -246,6 +286,7 @@ function WorkflowCardBody({ savedWorkflowSteps, diagnostics, mutationPending, + isImproveWorkspace, stepActions, readOnly, }: WorkflowCardBodyProps) { @@ -256,23 +297,13 @@ function WorkflowCardBody({ <>
    -
    - - onUpdateWorkflow({ name: e.target.value })} - disabled={readOnly} - data-settings-dirty={isWorkflowFieldDirty(workflow, savedWorkflow, "name")} - /> -
    +
    ); } - -function matchSingle(pathname: string, pattern: RegExp): string | null { - const match = pathname.match(pattern); - return safeDecodePathSegment(match?.[1]); -} - -function matchDouble(pathname: string, pattern: RegExp): [string, string] | null { - const match = pathname.match(pattern); - if (!match?.[1] || !match[2]) return null; - const first = safeDecodePathSegment(match[1]); - const second = safeDecodePathSegment(match[2]); - return first && second ? [first, second] : null; -} - -function normalizeSettingsPath(pathname: string): string { - if (!pathname || pathname === "/settings/") return "/settings"; - return pathname.length > 1 && pathname.endsWith("/") ? pathname.slice(0, -1) : pathname; -} diff --git a/docs/plans/improve-kandev-workspace/plan.md b/docs/plans/improve-kandev-workspace/plan.md new file mode 100644 index 0000000000..bdeb9349d6 --- /dev/null +++ b/docs/plans/improve-kandev-workspace/plan.md @@ -0,0 +1,180 @@ +--- +spec: docs/specs/improve-kandev/spec.md +created: 2026-08-01 +status: implemented +--- + +# Implementation Plan: Improve Kandev Workspace Isolation + +## Overview + +Improve Kandev tasks currently land in the user's active workspace, mixing +contribution work with their regular tasks. This change makes the +`improve-kandev` bootstrap endpoint find-or-create a dedicated, idempotently +reused workspace named `Improve Kandev`, scope the repository registration and +both hidden workflows to it, and return its `workspace_id` so the frontend +creates the task there. Backend contract first, then frontend wiring, then E2E +evidence of isolation. + +--- + +## Backend + +### `internal/improvekandev/handler.go` +- `BootstrapRequest.WorkspaceID` becomes optional (`json:"workspace_id,omitempty"`). + Remove the `req.WorkspaceID == ""` 400 validation and the + `canonicalWorkspaceID` call; delete `canonicalWorkspaceID` (and its unit + test). The field is accepted and ignored for backward compatibility. +- Add constants `improveWorkspaceName = "Improve Kandev"` and + `improveWorkspaceDesc`. +- Add `ensureImproveWorkspace(ctx) (*taskmodels.Workspace, error)`, mirroring + the existing `ensureWorkflow` idempotency pattern: + 1. `taskSvc.ListWorkspaces(ctx)` → match by exact `Name == "Improve Kandev"`. + 2. Miss → `taskSvc.CreateWorkspace(ctx, &taskservice.CreateWorkspaceRequest{ + Name: improveWorkspaceName, Description: improveWorkspaceDesc, + BootstrapKanbanWorkflow: true })`. + 3. Create failure → re-list and match by name (concurrent-bootstrap race); + still missing → return the error. +- `httpBootstrap`: + - Call `ensureImproveWorkspace` first; use its ID everywhere the old + `workspaceID` was used (`resolveOrCloneRepo`, `ListWorkflows`, + `ensureWorkflow` ×2). + - Add `WorkspaceID string \`json:"workspace_id"\`` to `BootstrapResponse`, + set to the dedicated workspace's ID. + +### Tests +- `internal/improvekandev/handler_test.go`: remove `TestCanonicalWorkspaceID` + (function deleted). +- `internal/integration/improve_kandev_test.go`: + - Update `TestImproveKandevBootstrapCreatesBothHiddenWorkflowsIdempotently`: + drop the pre-created workspace; bootstrap with an empty + `WorkspaceID`; assert the response `WorkspaceID` is non-empty, a workspace + named `Improve Kandev` exists, both hidden workflows live in it, and a + second bootstrap returns the same workspace + workflow IDs. + - Add `TestImproveKandevBootstrapReusesExistingImproveWorkspace`: pre-create + a workspace named `Improve Kandev`, bootstrap with a *different* request + `workspace_id`, assert the response's workspace is the pre-created one. + +--- + +## Frontend + +### `lib/api/domains/improve-kandev-api.ts` +- Add `workspace_id: string` to `ImproveKandevBootstrapResponse`. Keep the + request `workspaceId` parameter (still sent; backend ignores it). + +### `components/improve-kandev-dialog.tsx` +- `useBootstrapKandev`: after bootstrap, call `listRepositories` and + `setRepositories` with `data.workspace_id` instead of the active + `workspaceId` so the locked-repo chip resolves a label for the dedicated + workspace's repo. + +### `components/improve-kandev-dialog-create.tsx` +- `CreateModeView`: pass `workspaceId={ready ? ready.data.workspace_id : + props.workspaceId}` to `TaskCreateDialog`. Submit stays blocked until + bootstrap is ready, so no task can be created in the wrong workspace. + The sidebar `workspaceId` prop remains the fallback while loading and is + still used by `useGitHubAuthCheck` for the fix URL. + +--- + +## Tests + +- **What:** bootstrap creates the dedicated workspace on first use + (spec scenario). **File:** `internal/integration/improve_kandev_test.go`. + **How:** integration test through the real handler + task service. +- **What:** bootstrap reuses the existing workspace and workflow IDs + (spec scenario). **File:** same. **How:** second bootstrap call, compare IDs. +- **What:** a different request `workspace_id` is ignored. + **File:** same. **How:** pre-create the dedicated workspace, pass another ID. +- **What:** frontend uses the bootstrap's `workspace_id` for repo listing and + task creation. **File:** `apps/web/components/*` + E2E. **How:** E2E test + seeds a real dedicated workspace and asserts the task lands there. +- **What:** E2E mocks stay contract-complete (`workspace_id` present). + **File:** `apps/web/e2e/tests/improve-kandev.spec.ts`, + `mobile-improve-kandev.spec.ts`. **How:** update mock bodies. + +--- + +## E2E Tests + +- **Scenario:** GIVEN the user's active workspace is not the dedicated + workspace, WHEN the dialog submits a task, THEN the task appears in the + dedicated workspace and not the active one. + **File:** `apps/web/e2e/tests/improve-kandev.spec.ts`. + **What to verify:** `apiClient.listTasks(dedicatedWorkspaceId)` contains the + task; `apiClient.listTasks(seedData.workspaceId)` does not. + Seed the dedicated workspace with `apiClient.createWorkspace("Improve + Kandev")`, a workflow via `createWorkflow(workspace.id, ...)`, and a + repository via `createRepository(workspace.id, )`; mock + bootstrap to return those IDs. + +--- + +## Verification Results + +Completed for all 7 tasks (see each task's `## Results`). Summary of the final +verification run on the merged branch (`68b8a57a4`, PR #2347): + +- Backend: `go test -tags fts5 ./internal/improvekandev/... ./internal/integration/...` + pass; full backend suite passes with `KANDEV_*` vars unset and `umask 022`. +- Frontend: `tsc --noEmit` and `eslint --max-warnings 0` clean on all touched + files; unit tests pass (improve-kandev dialog, repository-card). +- E2E: `playwright test --config e2e/playwright.config.ts improve-kandev.spec` → + 14 passed (13 desktop + 1 mobile). Required rebuilding the stale + `apps/backend/bin/kandev` e2e binary (missing upstream `agent_generated_task_titles`) + and seeding `agent_generated_task_titles: false` in the submit-flow tests. +- CI on PR #2347: all checks green (`mergeStateStatus: CLEAN`); CodeRabbit + threads resolved. +- Demo instance on ubu4.in.fiere.fr (backend :25208, vite :58449) rebuilt with + the merged code: bootstrap with `create_workspace:true` created workspace + `0dfe5db8-c82d-4c6e-803a-2eec41bcb3fc` and carried the Default workspace's + mock GitHub connection; 409s and read-only settings pages verified. + +Artifacts: `docs/specs/improve-kandev/spec.md` (spec amendment for Phase 2), +this plan, and `docs/plans/improve-kandev-workspace/task-*.md`. +Cleanup/teardown: no temporary artifacts shipped; e2e DIAG probes removed before +committing. + +--- + +## Implementation Waves And Parallel Candidates + +Wave 1 (sequential): +- [x] [task-01-backend-dedicated-workspace](task-01-backend-dedicated-workspace.md) + +Wave 2 (depends on 01): +- [x] [task-02-frontend-bootstrap-workspace](task-02-frontend-bootstrap-workspace.md) + +Wave 3 (depends on 02): +- [x] [task-03-e2e-workspace-isolation](task-03-e2e-workspace-isolation.md) + +## Phase 2 — Dedicated workspace immutability + GitHub carry-over + +Follow-up requirements: the dedicated workspace is configuration-immutable +(workflows and repositories read-only) and, on first creation only, inherits +the GitHub workspace connection from the user's default workspace — nothing +else (no other integrations, no automations). + +### Waves + +Wave 4 (backend guards — sequential): +- [x] [task-04-backend-workspace-guards](task-04-backend-workspace-guards.md) + +Wave 5 (depends on 04): +- [x] [task-05-backend-github-carryover](task-05-backend-github-carryover.md) + +Wave 6 (depends on 04, 05): +- [x] [task-06-frontend-settings-readonly](task-06-frontend-settings-readonly.md) + +Wave 7 (depends on 06): +- [x] [task-07-e2e-settings-guards](task-07-e2e-settings-guards.md) + +The default is sequential execution in the primary conversation. No subagents +unless the user explicitly asks after selecting the implementation model. + +--- + +## Open Questions + +None. diff --git a/docs/plans/improve-kandev-workspace/task-01-backend-dedicated-workspace.md b/docs/plans/improve-kandev-workspace/task-01-backend-dedicated-workspace.md new file mode 100644 index 0000000000..c7ae075267 --- /dev/null +++ b/docs/plans/improve-kandev-workspace/task-01-backend-dedicated-workspace.md @@ -0,0 +1,84 @@ +--- +id: "01-backend-dedicated-workspace" +title: "Backend: dedicated Improve Kandev workspace" +status: completed +wave: 1 +depends_on: [] +plan: "plan.md" +spec: "../../specs/improve-kandev/spec.md" +--- + +# Task 01: Backend — dedicated Improve Kandev workspace + +Make the improve-kandev bootstrap endpoint find-or-create a dedicated +"Improve Kandev" workspace, scope repository + hidden workflows to it, and +return its ID. + +## Acceptance + +1. `POST /api/v1/system/improve-kandev/bootstrap` with an empty (or any) + `workspace_id` finds or creates a workspace named `Improve Kandev` + (kanban-bootstrapped), returns its ID as `workspace_id`, and registers the + kandev repository and both hidden workflows (`improve-kandev`, + `report-kandev-issue`) in that workspace. +2. A second bootstrap reuses the same workspace and the same workflow IDs. +3. `BootstrapRequest.WorkspaceID` is optional and ignored; + `canonicalWorkspaceID` is deleted along with `TestCanonicalWorkspaceID`. + +## Verification + +```sh +cd apps/backend && go test ./internal/improvekandev/... ./internal/integration/... +``` + +## Files likely touched + +- `apps/backend/internal/improvekandev/handler.go` +- `apps/backend/internal/improvekandev/handler_test.go` +- `apps/backend/internal/integration/improve_kandev_test.go` + +## Dependencies + +None. + +## Parallelism + +Sequential (wave 1). + +## Inputs + +- Spec: "API surface" and "Scenarios" (workspace creation/reuse) in + `docs/specs/improve-kandev/spec.md`. +- Plan: `docs/plans/improve-kandev-workspace/plan.md` Backend section. +- Patterns: `ensureWorkflow`'s find-then-create-then-re-read race handling in + `handler.go`; `taskSvc.ListWorkspaces` / `taskSvc.CreateWorkspace` + (`internal/task/service/service_resources.go`), `CreateWorkspaceRequest` + with `BootstrapKanbanWorkflow: true` (same as + `internal/task/handlers/workspace_handlers.go`). + +## Output contract + +Summary, files changed, exact test command + result, blockers, risks, and +task/plan status update in the same conversation. + +## Risks + +- First bootstrap on an existing install clones `kdlbs/kandev` into the new + workspace's isolated managed path (`~/.kandev/repos/workspaces//...`) — + one-time network cost, expected. +- Concurrent bootstraps may race workspace creation; the re-list-on-failure + path (same pattern as `ensureWorkflow`) converges on one row. + +## Results + +Shipped in `26e16a3d2` (PR #2347, branch `feature/improve-kandev-works-af0`). +`POST /api/v1/system/improve-kandev/bootstrap` find-or-creates a kanban-bootstrapped +workspace named `"Improve Kandev"` (exact-name match via +`task/models.WorkspaceNameImproveKandev`), scopes the hidden report workflow and +repository to it, and returns `{ workspace_id, ... }`; the request's `workspace_id` +is accepted for backward-compatible single-user flows. Concurrent bootstraps +converge on one workspace via the deterministic re-read after create +(`TestImproveKandevBootstrapConvergesOnSingleWorkspace`). No global unique-name +constraint was added (workspace names are not unique in the product). +Verification: `go test -tags fts5 ./internal/improvekandev/... ./internal/integration/...` +pass; e2e `improve-kandev.spec` covers the find-or-create + isolation path. diff --git a/docs/plans/improve-kandev-workspace/task-02-frontend-bootstrap-workspace.md b/docs/plans/improve-kandev-workspace/task-02-frontend-bootstrap-workspace.md new file mode 100644 index 0000000000..94502ae19d --- /dev/null +++ b/docs/plans/improve-kandev-workspace/task-02-frontend-bootstrap-workspace.md @@ -0,0 +1,88 @@ +--- +id: "02-frontend-bootstrap-workspace" +title: "Frontend: use the bootstrap workspace" +status: completed +wave: 2 +depends_on: ["01-backend-dedicated-workspace"] +plan: "plan.md" +spec: "../../specs/improve-kandev/spec.md" +--- + +# Task 02: Frontend — create tasks in the bootstrap workspace + +The Improve Kandev dialog must create tasks in the dedicated workspace the +bootstrap response returns, not in the user's active workspace. + +## Acceptance + +1. `ImproveKandevBootstrapResponse` includes `workspace_id: string`. +2. `useBootstrapKandev` lists repositories and populates the store for + `data.workspace_id` (not the active workspace), so the locked repo chip + resolves a label for the dedicated workspace's repository. +3. `CreateModeView` passes `ready.data.workspace_id` to `TaskCreateDialog` + when bootstrap is ready, so the created task lands in the dedicated + workspace. While loading/error the active workspace id remains the fallback + and submit stays blocked. + +## Verification + +```sh +cd apps && pnpm --filter @kandev/web typecheck +cd apps/web && pnpm vitest run components/improve-kandev-dialog.test.tsx +``` + +Unit coverage (added with the change): `components/improve-kandev-dialog.test.tsx` +asserts bootstrap is called with the workspace-choice flag, repositories are +listed and stored for the bootstrap's `workspace_id` (not the active one), and +the workspace-creation choice gates bootstrap when the dedicated workspace is +missing. The task-landing-in-the-dedicated-workspace behavior itself is covered +by the E2E isolation test in task 03. + +## Files likely touched + +- `apps/web/lib/api/domains/improve-kandev-api.ts` +- `apps/web/components/improve-kandev-dialog.tsx` +- `apps/web/components/improve-kandev-dialog-create.tsx` + +## Dependencies + +Task 01 (response contract: `workspace_id`). + +## Parallelism + +Sequential (wave 2). + +## Inputs + +- Spec: "API surface" (`workspace_id` in the bootstrap response) and + "Scenarios" (task lands in the dedicated workspace). +- Plan: `docs/plans/improve-kandev-workspace/plan.md` Frontend section. +- Existing wiring: `useBootstrapKandev` in `improve-kandev-dialog.tsx` + (currently `listRepositories(workspaceId)` + `setRepositories(workspaceId, + ...)`), `CreateModeView` in `improve-kandev-dialog-create.tsx` (currently + passes `props.workspaceId` to `TaskCreateDialog`). + +## Output contract + +Summary, files changed, typecheck result, blockers, risks, and task/plan +status update in the same conversation. + +## Risks + +- The dialog's `useGitHubAuthCheck` keeps using the active workspace for the + fix URL — intentional; do not switch it to the dedicated workspace. +- If `data.workspace_id` is missing (stale backend), `listRepositories(undefined)` + would 400 — the E2E mocks and the real backend both return it after task 01; + treat a missing field as a bootstrap error surfaced by the existing catch. + +## Results + +Shipped in `09733d2f2`, `cc7b66550` (PR #2347). The app boot payload's +`workspace_id`/`workspaces` now drive the Improve Kandev dialog; the dialog's +`WorkspaceChoicePanel` + `CreateWorkspaceCheckbox` opt into workspace creation +(default checked) when the dedicated workspace does not exist, and +`useBootstrapKandev` sends `create_workspace` accordingly. "New Task" in the +dedicated workspace opens the Improve Kandev dialog via the shared +`appSidebar.improveDialogOpen` store flag. Unit coverage: +`components/improve-kandev-dialog.test.tsx` (bootstrap wiring + copy), all pass +with `pnpm vitest run components/improve-kandev-dialog.test.tsx`. diff --git a/docs/plans/improve-kandev-workspace/task-03-e2e-workspace-isolation.md b/docs/plans/improve-kandev-workspace/task-03-e2e-workspace-isolation.md new file mode 100644 index 0000000000..8fbfa1fb58 --- /dev/null +++ b/docs/plans/improve-kandev-workspace/task-03-e2e-workspace-isolation.md @@ -0,0 +1,89 @@ +--- +id: "03-e2e-workspace-isolation" +title: "E2E: workspace isolation coverage" +status: completed +wave: 3 +depends_on: ["02-frontend-bootstrap-workspace"] +plan: "plan.md" +spec: "../../specs/improve-kandev/spec.md" +--- + +# Task 03: E2E — improve tasks land in the dedicated workspace + +Prove via Playwright that a task submitted through the Improve Kandev dialog +lands in the dedicated workspace, not the active one. + +## Acceptance + +1. Both bootstrap mocks (`improve-kandev.spec.ts`, `mobile-improve-kandev.spec.ts`) + include `workspace_id` in the mocked response (default: `seedData.workspaceId` + for existing tests; overridable). +2. New test "improve task lands in the dedicated workspace": + - Seed a real dedicated workspace: `apiClient.createWorkspace("Improve + Kandev")`, a workflow in it, and a repository + (`apiClient.createRepository(dedicated.id, )`). + - Mock bootstrap to return `workspace_id: dedicated.id`, + `workflow_id: `, + `repository_id: `. + - Submit a task through the dialog; assert + `apiClient.listTasks(dedicated.id)` contains it and + `apiClient.listTasks(seedData.workspaceId)` does not. + +## Verification + +```sh +cd apps && pnpm install --frozen-lockfile # fresh worktree bootstrap, if needed +cd apps/web && pnpm e2e improve-kandev +``` + +(The full E2E suite runs in the final verification phase, not here.) + +## Files likely touched + +- `apps/web/e2e/tests/improve-kandev.spec.ts` +- `apps/web/e2e/tests/mobile-improve-kandev.spec.ts` + +## Dependencies + +Task 01 (response contract) and task 02 (frontend uses the response +workspace id). The E2E fixtures (`test-base.ts` `seedData`) already expose +`workspaceId`, `workflowId`, `repositoryId`, and the seeded repo directory; +`ApiClient` has `createWorkspace`, `createWorkflow`, `createRepository`, +`createTask`, `listTasks`. + +## Parallelism + +Sequential (wave 3). + +## Inputs + +- Spec: "Scenarios" — task lands in the dedicated workspace; active workspace + untouched. +- Plan: `docs/plans/improve-kandev-workspace/plan.md` E2E Tests section. +- Existing patterns: `mockImproveKandevApis` helper in + `improve-kandev.spec.ts`; the "Open issue creates a task" test's + `apiClient.listTasks` assertion. + +## Output contract + +Summary, files changed, exact e2e command + result (test count/pass), +blockers, risks, and task/plan status update in the same conversation. + +## Risks + +- The mocked `workspace_id` must reference a workspace that exists in the + seeded backend, else `listRepositories` 404s and the dialog shows a + bootstrap error. The new test seeds the dedicated workspace for this reason. +- The create-task endpoint validates workflow/workspace consistency; the + mocked `workflow_id` must belong to the dedicated workspace (seeded via + `createWorkflow(dedicated.id, ...)`). + +## Results + +E2E `apps/web/e2e/tests/improve-kandev.spec.ts` (13 desktop + 1 mobile) all pass: +`playwright test --config e2e/playwright.config.ts improve-kandev.spec` → 14 passed. +The 4 submit-flow tests needed `agent_generated_task_titles: false` in the seed +(after upstream main merged the auto-title setting, whose default hides the title +field); the earlier 4 failures were caused by a stale `apps/backend/bin/kandev` +e2e binary missing upstream's `agent_generated_task_titles` backend field — +rebuilt via `go build -o bin/kandev ./cmd/kandev`. diff --git a/docs/plans/improve-kandev-workspace/task-04-backend-workspace-guards.md b/docs/plans/improve-kandev-workspace/task-04-backend-workspace-guards.md new file mode 100644 index 0000000000..02142d07b7 --- /dev/null +++ b/docs/plans/improve-kandev-workspace/task-04-backend-workspace-guards.md @@ -0,0 +1,87 @@ +# task-04: Backend workspace guards (read-only Improve Kandev workspace) + +Spec: `docs/specs/improve-kandev/spec.md` — "Dedicated workspace immutability" +Plan: `docs/plans/improve-kandev-workspace/plan.md` — Phase 2, Wave 4. + +## Goal + +The dedicated `Improve Kandev` workspace is configuration-immutable: workflow +mutations (create/update/delete/reorder and step mutations) and repository +mutations (create/update/delete/initialize-local) scoped to it are rejected +with HTTP 409 before any write. Listing/reading stays available. + +## Target + +- `apps/backend/internal/improvekandev/handler.go` — export the improve + workspace name check used by guards. +- `apps/backend/internal/task/service/service_resources.go` — workflow CRUD + + repository mutation guards. +- `apps/backend/internal/task/handlers/*` — wire the guard error to 409. +- `apps/backend/internal/workflow/service/readonly.go` + + `apps/backend/internal/workflow/controller/controller.go` — step-mutation + guard. +- `apps/backend/internal/backendapp` — wire a workspace-name provider into the + workflow service (only if the workflow service cannot resolve the workspace + itself). + +## Change + +1. In `internal/improvekandev`, add an exported predicate + `IsImproveWorkspaceName(name string) bool` (exact match against + `improveWorkspaceName`). Keep the unexported const private; export only the + predicate + a doc comment. +2. Task service: + - Add `ErrWorkspaceReadOnly = errors.New("workspace is managed by Improve + Kandev and is read-only")` (mirror `workflow/service.ErrWorkflowReadOnly` + wording style). + - Add a private helper `ensureWorkspaceMutable(ctx, workspaceID)` that + resolves the workspace (reusing the existing workspace resolver path used + by `authorizeWorkspaceID`) and returns `ErrWorkspaceReadOnly` when + `IsImproveWorkspaceName(workspace.Name)`. + - Call it at the top of: `CreateWorkflow`, `UpdateWorkflow`, `DeleteWorkflow` + (and any reorder method the service exposes), and the repository mutation + methods (`CreateRepository`, `UpdateRepository`, `DeleteRepository`, + `InitializeLocalRepository` — exact names per the actual service). +3. Handlers: map `ErrWorkspaceReadOnly` → HTTP 409 with a clear message + (mirror how `rejectReadOnlyWorkflowHTTP` / `writeStepMutationError` map + `ErrWorkflowReadOnly`). Find all workflow/repo handler mutation paths and + ensure they surface the 409 (WS paths included if they mutate). +4. Workflow steps: extend `workflow/service.EnsureWorkflowMutable` so that, + in addition to the GitHub-source check, it resolves the workflow's + workspace and rejects when `IsImproveWorkspaceName(workspace.Name)`. The + service needs a workspace lookup — add a minimal `workspaceProvider` + interface (GetWorkspace) to the workflow service if it doesn't already have + one, wire it in `backendapp`, keep the guard fail-open on resolution errors + (same policy as today). +5. Do NOT guard: workspace rename/delete, task creation, kanban board, hidden + workflow healing by the improve bootstrap itself (the bootstrap's + `ensureWorkflow` upsert must keep working — it writes through the same + service; ensure the guard doesn't break the bootstrap path. If + `ensureWorkflow` uses taskSvc.UpdateWorkflow, either exclude the + improvekandev caller or guard at the HTTP/controller layer only — decide + and document in the code). + +## Acceptance + +- Unit tests in `internal/task/service` asserting create/update/delete workflow + and repository mutations return `ErrWorkspaceReadOnly` for the improve + workspace and succeed for a normal workspace. +- Unit tests in `internal/workflow` asserting step mutations reject for a + workflow in the improve workspace (workflow's workspace resolved by name). +- Integration test: HTTP mutations against the improve workspace return 409; + the same mutations on a normal workspace succeed. The bootstrap still works + after the guards (existing integration tests stay green). +- `go test -tags fts5 ./internal/task/... ./internal/workflow/... ./internal/improvekandev/... ./internal/integration/...` and `golangci-lint run ./...` pass. + +## Results + +Shipped in `37597867d` + merge `68b8a57a4` (PR #2347). Guards at the HTTP/WS +handler layer reject mutations in the "Improve Kandev" workspace with HTTP 409 +(`workspaceReadOnlyMsg`); workflow step mutations go through +`workflow/service.EnsureWorkflowMutable` (`ErrWorkflowWorkspaceReadOnly` → 409) +and task mutations via `task.Service.ErrWorkspaceReadOnly`. Identity is name-based +(`(*Workspace).IsImproveKandev()`), so the bootstrap's internal service calls keep +working. Verified by `TestImproveKandevBootstrap*` in +`internal/integration/improve_kandev_test.go` (synthetic-identity router) and by +the read-only settings e2e tests; full backend suite passes with +`KANDEV_*` vars unset and `umask 022`. diff --git a/docs/plans/improve-kandev-workspace/task-05-backend-github-carryover.md b/docs/plans/improve-kandev-workspace/task-05-backend-github-carryover.md new file mode 100644 index 0000000000..5df8aaf0ac --- /dev/null +++ b/docs/plans/improve-kandev-workspace/task-05-backend-github-carryover.md @@ -0,0 +1,81 @@ +# task-05: Backend GitHub carry-over on Improve Kandev workspace creation + +Spec: `docs/specs/improve-kandev/spec.md` — "Workspace creation semantics" +Plan: `docs/plans/improve-kandev-workspace/plan.md` — Phase 2, Wave 5. +Depends on: task-04. + +## Goal + +When bootstrap creates the `Improve Kandev` workspace for the **first time** +only, copy the GitHub workspace connection (and its PAT secret where +applicable) from the user's default workspace. Copy nothing else: no other +integration configs, no automations, no extra workflows/repos. + +## Target + +- `apps/backend/internal/github/service_connections.go` (or a new + `copy_connection.go`) — new `CopyWorkspaceConnectionToWorkspace`. +- `apps/backend/internal/github/store.go` — any needed read/write helper. +- `apps/backend/internal/improvekandev/handler.go` — creation-path hook. +- `apps/backend/internal/backendapp` — wire the copier + default-workspace + resolver into the improvekandev handler. + +## Change + +1. GitHub service: add + `CopyWorkspaceConnectionToWorkspace(ctx, srcWorkspaceID, dstWorkspaceID) error`: + - Read the source `github_workspace_connections` row; if none, return nil + (no-op). + - For `pat` sources: also copy the PAT secret (stored under the + workspace-scoped secret key `WorkspacePATSecretKey(src)` → write under + `WorkspacePATSecretKey(dst)`); increment/recompute nothing — the copied + row keeps its `credential_generation`/status as-is. + - For `gh_cli` sources: the CLI account is host-global; copy the row + (source/login/host) without a secret. + - For app-installation sources: copy the row (installation id/account/app + registration reference). + - Upsert into `github_workspace_connections` for the destination + (ON CONFLICT(workspace_id) — same as `SetWorkspaceConnection`). + - Use the store's transaction surface if one exists; keep it best-effort: + a copy failure must not fail bootstrap (log + continue) — decide and + document. +2. Default workspace resolution: reuse + `integrations/workspacescope.DefaultResolver.Resolve(ctx)` (active + workspace in user settings → first by created_at → literal `default`). + Wire it in `backendapp` where the improvekandev handler is constructed. +3. Improve handler: add a small interface to the handler (mirroring the + `Cloner` pattern), e.g. + `GitHubWorkspaceCopier interface { CopyWorkspaceConnectionToWorkspace(ctx, src, dst string) error }`, + and a `DefaultWorkspaceResolver func(ctx) (string, error)` (or interface). + In `ensureImproveWorkspace`, after a successful **create** (miss path + only), resolve the default workspace and copy the GitHub connection into + the new workspace. The reuse path must NOT copy. +4. `NewHandler` signature grows by the copier + resolver; update + `cmd/kandev` wiring and the test constructors (`handler_test.go`, + `internal/integration/improve_kandev_test.go`) with fakes. + +## Acceptance + +- Unit test (`internal/github`): copying a `pat` connection duplicates the row + and the secret under the destination key; `gh_cli`/app rows copy without a + secret; no source row → nil. +- Integration test: bootstrap on a fresh DB where the default workspace has a + GitHub connection (seed via the github service or store) → the new Improve + Kandev workspace has the same connection; a second bootstrap does not change + it. Bootstrap with no source connection → no connection row. +- Existing improve-kandev integration tests stay green (constructors updated + with fakes). +- `go test -tags fts5 ./internal/github/... ./internal/improvekandev/... ./internal/integration/...` and `golangci-lint run ./...` pass. + +## Results + +Shipped in `37597867d` (PR #2347). `github.Service.CopyWorkspaceConnectionToWorkspace` +copies the default workspace's GitHub connection row + PAT secret at workspace +creation only; `gh_cli`/app rows without secrets are copied as rows. +Wired via `improvekandev.GitHubWorkspaceCopier` / `DefaultWorkspaceResolver` +(uses `workspacescope.ResolveMigrationTarget`); `dbPool` threaded through +`buildHTTPServer` + `routeParams`. Best-effort — failures are logged and never +fail bootstrap. Verified by integration tests and on the ubu4 demo instance +(workspace `0dfe5db8-...` received the Default workspace's mock GitHub +connection; re-seed needed after restart since mock connections are in-memory: +`PUT /api/v1/github/mock/workspace-connections/`). diff --git a/docs/plans/improve-kandev-workspace/task-06-frontend-settings-readonly.md b/docs/plans/improve-kandev-workspace/task-06-frontend-settings-readonly.md new file mode 100644 index 0000000000..c55b30374e --- /dev/null +++ b/docs/plans/improve-kandev-workspace/task-06-frontend-settings-readonly.md @@ -0,0 +1,69 @@ +# task-06: Frontend read-only settings for the dedicated workspace + +Spec: `docs/specs/improve-kandev/spec.md` — "Dedicated workspace immutability" +Plan: `docs/plans/improve-kandev-workspace/plan.md` — Phase 2, Wave 6. +Depends on: task-04, task-05. + +## Goal + +The workspace settings pages for the dedicated `Improve Kandev` workspace are +read-only: the workflows page lists the hidden `improve-kandev` (Improve → +Test → PR) and `report-kandev-issue` workflows with no create/edit/delete/ +import/export/reorder controls; the repositories page lists the kandev repo +with no add/edit/delete controls. Other workspaces keep the current UI. + +## Target + +- `apps/web/app/settings/workspace/workspace-workflows-client.tsx` (+ its + dialogs `workspace-workflows-dialogs.tsx` and any actions file). +- `apps/web/app/settings/workspace/workspace-repositories-client.tsx`. +- `apps/web/src/settings-routes.tsx` (route loaders pass workspace name). +- `apps/web/app/actions/workspaces.ts` — `listWorkflowsAction` gains an + `include_hidden` option (the backend endpoint already supports + `?include_hidden=true`). + +## Change + +1. Determine the improve workspace client-side by exact name + `IMPROVE_KANDEV_WORKSPACE_NAME` (already exported from + `components/improve-kandev-dialog-model.ts`). The route loaders already + fetch the workspace (`getWorkspaceAction`) — thread `isImproveWorkspace` + into the client components (route-loader → component props, mirroring how + the workspace name is already passed). +2. Workflows page in improve mode: + - Fetch workflows with `include_hidden=true` so the hidden improve + workflows appear (verify the list response includes steps or fetch steps + per workflow with the existing steps action so the card can show + Improve → Test → PR). + - Hide the Add/Import/Export/GitHub-sync actions and the reorder + affordances; render cards non-interactive (no edit/delete). + - Show a short read-only notice ("This workspace's workflows are managed by + Improve Kandev and cannot be changed."). +3. Repositories page in improve mode: hide Add/Discover; render repository + cards non-interactive (no edit/delete); same notice style. +4. Keep the generic task-create dialog behavior unchanged (the standard New + Task flow in the improve workspace routes to the Improve Kandev dialog per + the earlier change — this task only touches settings pages). + +## Acceptance + +- Unit tests for the read-only rendering (component tests in the settings + workspace dir; follow existing test conventions for these pages — if none + exist, add at least a render-mode test for the workflows page: improve + workspace hides the Add control and lists the hidden workflow; normal + workspace unchanged). +- `cd apps/web && pnpm typecheck && pnpm lint` and the settings-related + vitest suites pass. + +## Results + +Shipped in `cc7b66550` (PR #2347). `WorkspaceWorkflowsClient`/`WorkspaceRepositoriesClient` +render read-only when `isImproveWorkspace` (`WorkflowCard readOnly`, +`RepositoryCard readOnly`), with a shared `WorkspaceSettingsHeader` and a badge +distinguishing "managed by Improve Kandev" from GitHub-sync managed; `include_hidden=true` +lists hidden workflows in settings. The merged upstream i18n pass replaced literals +with `t()` keys (`workflowsReadOnlyImprove`, `repositoriesReadOnlyImprove`, ...); +repository-card max-lines was fixed by extracting `RepositoryPreview` into +`components/settings/repository-card-preview.tsx`. Verified: `tsc --noEmit`, +`eslint --max-warnings 0`, `vitest run components/settings/repository-card.test.tsx` +(17 tests across the touched files). diff --git a/docs/plans/improve-kandev-workspace/task-07-e2e-settings-guards.md b/docs/plans/improve-kandev-workspace/task-07-e2e-settings-guards.md new file mode 100644 index 0000000000..b6fa6a9400 --- /dev/null +++ b/docs/plans/improve-kandev-workspace/task-07-e2e-settings-guards.md @@ -0,0 +1,60 @@ +# task-07: E2E settings guards for the dedicated workspace + +Spec: `docs/specs/improve-kandev/spec.md` — "Dedicated workspace immutability" +Plan: `docs/plans/improve-kandev-workspace/plan.md` — Phase 2, Wave 7. +Depends on: task-06. + +## Goal + +Playwright evidence that the dedicated workspace's settings pages are +read-only and the backend rejects mutations, while a normal workspace stays +editable. + +## Target + +- `apps/web/e2e/tests/improve-kandev.spec.ts` (desktop; extend the existing + improve-kandev suite). + +## Change + +Add tests (desktop chromium): + +1. **Workflows settings read-only**: seed the dedicated workspace + (`apiClient.createWorkspace("Improve Kandev")` + workflow via + `createWorkflow`); `goto("/settings/workspace//workflows")`; assert: + - The `improve-kandev` workflow card is listed with steps Improve → Test → + PR (locate by card title / step text). + - No "Add workflow" / "New workflow" control is present (assert the create + control testid count is 0). + - A read-only notice is visible. + - (Optional) attempt a backend mutation via `apiClient` (e.g. create a + workflow in the dedicated workspace) and assert it 409s — put the API + rejection assertion here if the api client has a workflow-create helper, + else rely on the integration tests. +2. **Repositories settings read-only**: with the dedicated workspace seeded + (repo via `apiClient.createRepository`), `goto` the repositories settings + page; assert the kandev repo card is listed and no add/delete controls are + present. +3. **Sanity contrast**: the seed workspace's workflows page still shows the + Add control (guards are workspace-scoped, not global). + +## Acceptance + +- `cd apps/web && pnpm build:vite && playwright test --config e2e/playwright.config.ts improve-kandev.spec` — all pass (desktop + mobile suites). +- No changes to unrelated e2e specs. + +## Results + +Covered by `improve-kandev.spec` tests "workflows settings are read-only in the +dedicated workspace" and "repositories settings are read-only in the dedicated +workspace": they seed workflows/repos under a temp workspace name, rename it to +"Improve Kandev" (rename is unguarded), then assert the settings pages render +read-only and that mutating API calls (create workflow, create repository) 409. +All pass in the 14/14 `improve-kandev.spec` run (see task-03). + +> TODO(guards): workspace rename is intentionally unguarded (task-04 excludes +> it), so a user who can rename workspaces can bypass the immutability guard by +> renaming the dedicated workspace away, or trigger it by renaming any other +> workspace to "Improve Kandev". Track this gap when workspace-rename access is +> revisited; the name-based identity (`WorkspaceNameImproveKandev`) is the +> seam that would need to change (e.g. a dedicated flag column on the row). diff --git a/docs/specs/improve-kandev/spec.md b/docs/specs/improve-kandev/spec.md index a16318c3f0..fd409a8c9f 100644 --- a/docs/specs/improve-kandev/spec.md +++ b/docs/specs/improve-kandev/spec.md @@ -39,8 +39,13 @@ the user's own agent picks up immediately — turning every report into a contri task: recent backend logs, frontend logs, and a metadata snapshot. The bundle lives in a temporary folder and is referenced by file path in the task description so the agent can read it on demand. -- Submitting the dialog creates the task in the user's active workspace, clones - the kandev repo if needed, and starts the agent on the first step. +- Submitting the dialog creates the task in the dedicated **Improve Kandev** + workspace, clones the kandev repo if needed, and starts the agent on the + first step. +- The dedicated workspace is created automatically on first bootstrap and + reused on every later use, keeping improve tasks isolated and segregated + from the user's regular work. It is named `Improve Kandev`, is a normal + visible workspace (with a kanban workflow), and persists across restarts. - The `improve-kandev` workflow has three manually-advanced steps: - **Improve** — agent implements the change with TDD; adds E2E tests when the change touches user-facing flows. @@ -50,7 +55,9 @@ the user's own agent picks up immediately — turning every report into a contri request against `main` in `kdlbs/kandev`. - The `improve-kandev` workflow is hidden from the workflow management page in workspace settings and from the workflow picker in the standard task-create - dialog. It is reachable only through the Improve Kandev entry point. + dialog, except in the dedicated `Improve Kandev` workspace itself where the + workflows settings page lists it (and `report-kandev-issue`) **read-only**. + It is reachable through the Improve Kandev entry point. - Hidden workflows do not count as choices in the standard task-create dialog. When the active workspace has exactly one visible workflow, the dialog uses that workflow implicitly and omits the redundant workflow selector. This @@ -71,15 +78,22 @@ the user's own agent picks up immediately — turning every report into a contri ## API surface -- `POST /api/v1/system/improve-kandev/bootstrap` continues to accept - `{ "workspace_id": string }`. Its success response includes the existing - repository, branch, context-bundle, GitHub-login, write-access, and - fork-status fields plus: +- `POST /api/v1/system/improve-kandev/bootstrap` accepts an optional + `{ "workspace_id": string, "create_workspace": boolean }`. When the + dedicated `Improve Kandev` workspace exists, both fields are ignored and + everything is scoped to it. When it is missing, `create_workspace: true` + creates it (with the GitHub connection carried over from the user's default + workspace); `create_workspace: false` falls back to `workspace_id` (the + user's active workspace, legacy behavior). Its success response includes + the existing repository, branch, context-bundle, GitHub-login, write-access, + and fork-status fields plus: + - `workspace_id: string` — the dedicated Improve Kandev workspace the task + must be created in. - `workflow_id: string` — the workspace instance of `improve-kandev`. - `issue_workflow_id: string` — the workspace instance of `report-kandev-issue`. -- Both workflow IDs refer to hidden, workspace-scoped workflow instances and - are safe to request repeatedly. +- Both workflow IDs refer to hidden, workspace-scoped workflow instances in + the returned workspace and are safe to request repeatedly. ## Persistence guarantees @@ -87,8 +101,11 @@ the user's own agent picks up immediately — turning every report into a contri `kandev.improveKandev.skipIntro = "true"` in browser local storage. It survives reloads and Kandev restarts for that browser profile, but is not synchronized between browsers or users. -- The two hidden workflow instances are workspace-scoped and remain idempotent: - opening the dialog again reuses the existing workflow for each template. +- The dedicated `Improve Kandev` workspace is a normal persisted workspace + row created on first bootstrap and reused thereafter; it survives restarts. +- The two hidden workflow instances live in the dedicated workspace and remain + idempotent: opening the dialog again reuses the existing workflow for each + template. ## Failure modes @@ -97,6 +114,11 @@ the user's own agent picks up immediately — turning every report into a contri - If the saved preference skips the intro but GitHub authentication is missing, the GitHub-auth recovery explanation takes precedence over the direct-open preference. +- If the dedicated workspace cannot be created or resolved, bootstrap fails + and the dialog surfaces the error with the task form blocked. +- Concurrent bootstrap calls that race the workspace creation converge on a + single workspace: a creation failure re-reads the workspace list and reuses + an existing `Improve Kandev` row. - If bootstrap cannot create or resolve either hidden workflow, the task form remains blocked and surfaces the bootstrap error. - A fork restriction blocks only **Bug fix** and **Feature request** submission. @@ -107,9 +129,23 @@ the user's own agent picks up immediately — turning every report into a contri - **GIVEN** the user opens the Improve Kandev dialog with the logs checkbox on, **WHEN** they submit a title and description, **THEN** a task is created in - their active workspace, the description references three files in a temp - folder (`metadata.json`, `backend.log`, `frontend.log`), and the agent starts - on the **Improve** step. + the dedicated `Improve Kandev` workspace (created automatically on first + use), the description references three files in a temp folder + (`metadata.json`, `backend.log`, `frontend.log`), and the agent starts on + the **Improve** step. + +- **GIVEN** no `Improve Kandev` workspace exists, **WHEN** bootstrap is called, + **THEN** a workspace named `Improve Kandev` is created, the kandev + repository and both hidden workflows live in it, and the response includes + its `workspace_id`. + +- **GIVEN** an `Improve Kandev` workspace already exists, **WHEN** bootstrap is + called again, **THEN** the same workspace (and the same hidden workflow + instances) are reused and the response's `workspace_id` is unchanged. + +- **GIVEN** the user's active workspace is not the dedicated workspace, + **WHEN** the dialog submits a task, **THEN** the task appears in the + dedicated workspace and no task is created in the active workspace. - **GIVEN** the agent reports the implementation is complete on the **Improve** step, **WHEN** the user moves the task to **Test**, **THEN** the agent @@ -156,6 +192,93 @@ the user's own agent picks up immediately — turning every report into a contri Improve Kandev dialog, **THEN** the dialog shows a blocking error referencing the health-check result and disables the submit button. +- **GIVEN** the user opens the dedicated workspace's workflows settings page, + **WHEN** the page loads, **THEN** it lists `improve-kandev` with steps + Improve → Test → PR and `report-kandev-issue` read-only, and no + create/edit/delete/import/export controls are available. + +- **GIVEN** the user opens the dedicated workspace's repositories settings + page, **WHEN** the page loads, **THEN** the registered kandev repository is + listed read-only and no add/edit/delete controls are available. + +- **GIVEN** a mutation request (workflow create/update/delete/reorder/step + mutation or repository create/update/delete/initialize) is scoped to the + dedicated workspace, **WHEN** it reaches the backend, **THEN** it is + rejected with HTTP 409 before any write. + +- **GIVEN** bootstrap creates the `Improve Kandev` workspace for the first + time and the user's default workspace has a GitHub connection, **WHEN** the + workspace is created, **THEN** the new workspace carries the same GitHub + connection (and PAT secret where applicable), and no other integration + configurations, automations, workflows, or repositories beyond the bootstrap + defaults. + +- **GIVEN** bootstrap creates the `Improve Kandev` workspace for the first + time and the user's default workspace has **no** GitHub connection, **WHEN** + the workspace is created, **THEN** no connection is copied and the workspace + starts without a GitHub connection. + +- **GIVEN** the `Improve Kandev` workspace already exists, **WHEN** bootstrap + is called again, **THEN** the workspace's configuration (including its + GitHub connection) is untouched — nothing is re-copied. + +- **GIVEN** the dedicated workspace does not exist, **WHEN** the user opens + the Improve Kandev dialog, **THEN** the dialog offers a "Create a dedicated + Improve Kandev workspace" checkbox (default checked) — in the intro, or as a + gate before the create form when the intro was dismissed. + +- **GIVEN** the dedicated workspace does not exist and the user unchecks the + creation checkbox, **WHEN** they proceed, **THEN** bootstrap falls back to + the active workspace: the hidden workflows and kandev repo are scoped there + and the task lands in it (legacy behavior). + +## Dedicated workspace immutability + +- The dedicated `Improve Kandev` workspace is configuration-immutable for the + surfaces that define how tasks run there: + - **Workflows**: the settings page + (`/settings/workspace//workflows`) lists the workspace's workflows — + including the hidden `improve-kandev` (Improve → Test → PR) and + `report-kandev-issue` instances — read-only. Creating, editing, deleting, + reordering, importing, exporting, and GitHub-syncing workflows is not + possible; no workflow may be added. Step mutations are equally rejected. + - **Repositories**: the settings page lists the workspace's repositories + (the registered kandev repo) read-only. Creating, initializing, editing, + and deleting repositories is not possible. +- Enforcement is backend-side: the workflow and repository mutation endpoints + reject requests scoped to the dedicated workspace (HTTP 409) before any + write. The settings pages additionally hide/disable the mutation controls so + the state is visible up front. +- Task creation, agent runs, step advancement, and the kanban board are + unaffected — only configuration mutations are restricted. + +## Workspace creation semantics + +- Creating the dedicated `Improve Kandev` workspace is an **opt-in checkbox** + in the dialog, offered whenever the workspace does not exist yet: in the + intro screen, and as a gate before the create form for users who dismissed + the intro. It defaults to checked. +- When bootstrap creates the `Improve Kandev` workspace for the **first time** + (the find-or-create miss path with `create_workspace: true`), it + additionally: + - **Copies the GitHub workspace connection** (source, login, installation + metadata, and the underlying PAT secret where applicable) from the user's + **default workspace** — resolved the same way legacy integrations resolve + it: the active workspace recorded in the user's settings, else the + workspace created first, else the literal `default` id. If the source + workspace has no GitHub connection, nothing is copied. + - **Copies nothing else**: no other integration configurations + (Jira/Linear/GitLab/Azure DevOps/Sentry stay unconfigured in the new + workspace; they remain manually configurable), no automations, no + workflow/repository rows beyond the bootstrap defaults. +- When the workspace does not exist and the checkbox is unchecked + (`create_workspace: false`), bootstrap falls back to the request's + `workspace_id` (the user's active workspace) and scopes the repo and hidden + workflows there — the legacy behavior. +- Reuse path (workspace already exists): bootstrap makes no further changes — + the GitHub connection and configuration are never re-copied or synced, and + new improve tasks land in the dedicated workspace systematically. + ## Out of scope - Automatic transitions between workflow steps (user moves manually). @@ -170,3 +293,7 @@ the user's own agent picks up immediately — turning every report into a contri not stored reports. - Cleanup of the temporary log bundle directory; left to OS/temp policy. - Windows-specific considerations for `make install` / `make dev`. +- Migrating pre-existing improve tasks out of the workspace they were created + in before this feature shipped; old tasks stay where they are. +- Hiding the dedicated workspace from the workspace switcher; it appears as a + normal workspace.