Self-hosted workflows for coding-agent delivery. Orchestrate CodeBuddy, Codex and Claude Code with scripts and human approval gates. Includes Local workflows for coding assistants.
JavaScript agent-orchestrationagentic-workflowai-agentsai-codingclaude-codecode-reviewcodebuddycodexcoding-agentscursordeveloper-toolshuman-on-the-loopllmmcpmulti-agentsdlcself-hostedsopworkflow-automationworkflow-engine
fix(sop): provide a default sandbox and validate sandbox selection (#176)
Robert0622e83d9c8f40fc
diff --git a/docs/deployment.md b/docs/deployment.mdindex 383b159f..676d3961 100644--- a/docs/deployment.md+++ b/docs/deployment.md@@ -49,6 +49,8 @@ The platform listens on `LOOPFORGE_BIND`, `0.0.0.0` by default, without promptin### Docker sandboxes+The platform exposes a built-in default sandbox (`local`) even when the catalog SQL has not been installed. It is an in-memory fallback and does not insert database rows. An existing saved `local` profile takes priority, including its configured driver and environment. The default cannot be deleted; edit its configuration or create another profile to change how tasks run. The full installer still imports starter SOPs and the welcome project.+For native services running as an ordinary host user, default/root Docker images run with that service user's UID/GID so private workspaces remain accessible without relaxing their permissions or adding capabilities. Images that explicitly select a non-root user retain that identity; operators must arrange compatible bind-mount ownership for those images.The Compose deployment mounts the host Docker socket into the platform container so built-in AI SOPs run out of the box. `AGENTFLOW_ISOLATED_IMAGE` points to the installed platform image: default sandboxes start separate sibling containers from that same image, with no second CLI download or image build. They do not mount the Docker socket. Custom Dockerfiles still build and cache their own images. The run workspace is mounted at `/workspace` on the Compose network. Because bind mounts are resolved by the host Docker daemon, `LOOPFORGE_DATA_DIR` (written to `.env` by `scripts/configure.sh`, default `./.data`) is mounted into the platform container at the same absolute path; workspaces and CLI state live under it.diff --git a/internal/httpapi/catalog.go b/internal/httpapi/catalog.goindex 4ef925ea..bcca7a9c 100644--- a/internal/httpapi/catalog.go+++ b/internal/httpapi/catalog.go@@ -855,7 +855,7 @@ func filterEnvironmentAssets[T any](items []T, projectID string, scope func(T) (out := make([]T, 0, len(items))for _, item := range items {owner, shared := scope(item)- if owner == projectID || (owner != "" && shared) {+ if owner == projectID || shared {out = append(out, item)}}diff --git a/internal/httpapi/default_sandbox_test.go b/internal/httpapi/default_sandbox_test.gonew file mode 100644index 00000000..dad480d3--- /dev/null+++ b/internal/httpapi/default_sandbox_test.go@@ -0,0 +1,64 @@+package httpapi++import (+ "encoding/json"+ "net/http"+ "reflect"+ "testing"++ "agentflow/internal/domain"+)++func TestProjectEnvironmentAssetsIncludeSharedGlobalDefaults(t *testing.T) {+ profiles := []domain.SandboxProfile{+ {ID: "own", ProjectID: "project"},+ {ID: "foreign-shared", ProjectID: "other", Shared: true},+ {ID: "foreign-private", ProjectID: "other"},+ {ID: "global-shared", Shared: true},+ {ID: "global-private"},+ }+ visible := filterEnvironmentAssets(profiles, "project", func(profile domain.SandboxProfile) (string, bool) {+ return profile.ProjectID, profile.Shared+ })+ var ids []string+ for _, profile := range visible {+ ids = append(ids, profile.ID)+ }+ if !reflect.DeepEqual(ids, []string{"own", "foreign-shared", "global-shared"}) {+ t.Fatalf("incorrect project visibility: %v", ids)+ }+}++func TestDefaultSandboxWithoutCatalogRowsSupportsSOPCreation(t *testing.T) {+ f := cvBNewHTTPFixture(t)+ if err := f.s.DB.Exec("DELETE FROM sandboxes").Error; err != nil {+ t.Fatal(err)+ }+ const projectID = "builtin-default-project"+ if err := f.s.PutProject(domain.Project{ID: projectID, Name: "Default sandbox check", OwnerID: f.user.ID}); err != nil {+ t.Fatal(err)+ }+ bootstrap := cvBRequest(t, f, http.MethodGet, "/api/bootstrap", nil, true)+ var catalog struct {+ Sandboxes []domain.SandboxProfile `json:"sandboxes"`+ }+ if bootstrap.Code != http.StatusOK || json.Unmarshal(bootstrap.Body.Bytes(), &catalog) != nil || len(catalog.Sandboxes) != 1 || catalog.Sandboxes[0].ID != "local" {+ t.Fatalf("bootstrap does not expose the default: %d %s", bootstrap.Code, bootstrap.Body.String())+ }+ listed := cvBRequest(t, f, http.MethodGet, "/api/sandboxes?projectId="+projectID, nil, true)+ var profiles []domain.SandboxProfile+ if listed.Code != http.StatusOK || json.Unmarshal(listed.Body.Bytes(), &profiles) != nil || len(profiles) != 1 || profiles[0].ID != "local" {+ t.Fatalf("project cannot select the default: %d %s", listed.Code, listed.Body.String())+ }+ created := cvBRequest(t, f, http.MethodPut, "/api/workflows", map[string]any{+ "id": "builtin-default-sop", "name": "Blank SOP", "projectId": projectID,+ "status": "draft", "sandboxProfileId": "local", "nodes": []any{}, "edges": []any{},+ }, true)+ if created.Code != http.StatusOK {+ t.Fatalf("blank SOP creation failed: %d %s", created.Code, created.Body.String())+ }+ var count int64+ if err := f.s.DB.Table("sandboxes").Count(&count).Error; err != nil || count != 0 {+ t.Fatalf("API requests seeded rows: rows=%d err=%v", count, err)+ }+}diff --git a/internal/repo/catalog.go b/internal/repo/catalog.goindex 6f80eed3..3ae2c08a 100644--- a/internal/repo/catalog.go+++ b/internal/repo/catalog.go@@ -318,11 +318,31 @@ func (r *CatalogRepo) DeleteEnvironment(id string) error {}func (r *CatalogRepo) Sandboxes() []domain.SandboxProfile {- return payloadList[domain.SandboxProfile](r.DB, "sandboxes", "")+ profiles := payloadList[domain.SandboxProfile](r.DB, "sandboxes", "")+ for _, profile := range profiles {+ if profile.ID == DefaultSandboxProfileID {+ return profiles+ }+ }+ if profile, ok := r.Sandbox(DefaultSandboxProfileID); ok {+ profiles = append(profiles, profile)+ }+ return profiles}func (r *CatalogRepo) Sandbox(id string) (domain.SandboxProfile, bool) {- return payloadOne[domain.SandboxProfile](r.DB, "sandboxes", id)+ var profile domain.SandboxProfile+ var row payloadRow+ err := r.DB.Table("sandboxes").Where("id = ?", id).Take(&row).Error+ // A missing row may use the built-in default. Database failures or invalid+ // stored configuration must not silently switch a run's execution policy.+ if errors.Is(err, gorm.ErrRecordNotFound) && id == DefaultSandboxProfileID {+ return DefaultSandboxProfile(), true+ }+ if err != nil || json.Unmarshal(row.Payload, &profile) != nil {+ return domain.SandboxProfile{}, false+ }+ return profile, true}func (r *CatalogRepo) PutSandbox(v domain.SandboxProfile) error {@@ -357,6 +377,9 @@ func (r *CatalogRepo) PutSandbox(v domain.SandboxProfile) error {}func (r *CatalogRepo) DeleteSandbox(id string) error {+ if id == DefaultSandboxProfileID {+ return errors.New("默认运行沙箱不能删除;可编辑配置或新建其他沙箱")+ }if _, ok := r.Sandbox(id); !ok {return fmt.Errorf("sandbox not found")}diff --git a/internal/repo/sandbox_defaults.go b/internal/repo/sandbox_defaults.gonew file mode 100644index 00000000..072caec1--- /dev/null+++ b/internal/repo/sandbox_defaults.go@@ -0,0 +1,18 @@+package repo++import "agentflow/internal/domain"++const DefaultSandboxProfileID = "local"++// DefaultSandboxProfile is available without catalog initialization. It is a+// read-only fallback, not a seed row. Operator-persisted profiles take priority.+// The runtime applies AGENTFLOW_LOCAL_SANDBOX=docker in Compose deployments;+// native installations retain their explicitly configured execution policy.+func DefaultSandboxProfile() domain.SandboxProfile {+ return domain.SandboxProfile{+ ID: DefaultSandboxProfileID,+ Name: "默认运行沙箱",+ Shared: true,+ Driver: domain.SandboxDriverLocal,+ }+}diff --git a/internal/repo/sandbox_defaults_test.go b/internal/repo/sandbox_defaults_test.gonew file mode 100644index 00000000..a8bdc6aa--- /dev/null+++ b/internal/repo/sandbox_defaults_test.go@@ -0,0 +1,94 @@+package repo++import (+ "reflect"+ "strings"+ "testing"++ "agentflow/internal/domain"+)++func TestDefaultSandboxWithoutSeedDoesNotWriteRows(t *testing.T) {+ s, err := OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { s.Close() })+ if err := s.DB.Exec("DELETE FROM sandboxes").Error; err != nil {+ t.Fatal(err)+ }+ profile, ok := s.Sandbox(DefaultSandboxProfileID)+ if !ok || profile.ID != "local" || profile.Driver != domain.SandboxDriverLocal || !profile.Shared || profile.ProjectID != "" {+ t.Fatalf("missing shared default: %+v, found=%v", profile, ok)+ }+ profiles := s.Sandboxes()+ if len(profiles) != 1 || !reflect.DeepEqual(profiles[0], profile) {+ t.Fatalf("list and lookup disagree: %+v / %+v", profiles, profile)+ }+ var count int64+ if err := s.DB.Table("sandboxes").Count(&count).Error; err != nil || count != 0 {+ t.Fatalf("default lookup wrote catalog data: rows=%d, err=%v", count, err)+ }+ if _, ok := s.Sandbox("not-configured"); ok {+ t.Fatal("an unknown sandbox must not use the default")+ }+}++func TestStoredDefaultSandboxWinsWithoutDuplicatesAndCannotBeDeleted(t *testing.T) {+ s, err := OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { s.Close() })+ configured := domain.SandboxProfile{ID: "local", Name: "Operator configured", ProjectID: "platform", Shared: true, Driver: "native", Environment: map[string]string{"PRESERVE": "yes"}}+ if err := s.PutSandbox(configured); err != nil {+ t.Fatal(err)+ }+ profile, ok := s.Sandbox(configured.ID)+ if !ok || !reflect.DeepEqual(profile, configured) {+ t.Fatalf("operator configuration changed: %+v", profile)+ }+ count := 0+ for _, candidate := range s.Sandboxes() {+ if candidate.ID == configured.ID {+ count+++ if !reflect.DeepEqual(candidate, configured) {+ t.Fatalf("list replaced operator configuration: %+v", candidate)+ }+ }+ }+ if count != 1 {+ t.Fatalf("default appears %d times", count)+ }+ if err := s.DeleteSandbox(configured.ID); err == nil || !strings.Contains(err.Error(), "不能删除") {+ t.Fatalf("default deletion must be explicit: %v", err)+ }+ profile, _ = s.Sandbox(configured.ID)+ if !reflect.DeepEqual(profile, configured) {+ t.Fatal("rejected deletion changed the configured execution policy")+ }+}++func TestDefaultSandboxDoesNotMaskCorruptConfigurationOrDatabaseFailure(t *testing.T) {+ s, err := OpenTest()+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() { s.Close() })+ if err := s.DB.Table("sandboxes").Where("id = ?", DefaultSandboxProfileID).Update("payload", `"invalid profile"`).Error; err != nil {+ t.Fatal(err)+ }+ if _, ok := s.Sandbox(DefaultSandboxProfileID); ok {+ t.Fatal("invalid stored configuration must not fall back to local execution")+ }+ if err := s.DB.Exec("DELETE FROM sandboxes").Error; err != nil {+ t.Fatal(err)+ }+ s.Close()+ if _, ok := s.Sandbox(DefaultSandboxProfileID); ok {+ t.Fatal("database failure must not fall back to local execution")+ }+ if profiles := s.Sandboxes(); len(profiles) != 0 {+ t.Fatalf("database failure reported available sandboxes: %+v", profiles)+ }+}diff --git a/web/app/flows.js b/web/app/flows.jsindex da7fe6a1..9b3fb6a1 100644--- a/web/app/flows.js+++ b/web/app/flows.js@@ -1098,22 +1098,68 @@ async function saveWorkflow(){if(catalogGeneric(state.workflow)&&!isPlatformAdmin()){toast('通用模板为只读,请先「复制到本项目」再修改');throw new Error('generic sop is read-only')}if(catalogForeign(state.workflow?.projectId)){toast('这是其他项目的共享 SOP,请先复制到本项目再改');throw new Error('shared sop is read-only')}try{const saved=await api('/api/workflows',{method:'PUT',body:JSON.stringify(state.workflow)});state.workflow=clone(saved);const i=state.data.workflows.findIndex(w=>w.id===saved.id);if(i>=0)state.data.workflows[i]=clone(saved);else state.data.workflows.unshift(clone(saved));markWorkflowClean();renderWorkflowMeta();renderSOPCatalog();renderCanvas();renderProperties();toast('SOP 草稿已保存');return saved}catch(e){if(e.message.includes('revision conflict')){toast('保存冲突:其他人已更新该 SOP,请重新选择后合并')}else if(e.message!=='shared sop is read-only'&&e.message!=='generic sop is read-only')toast(e.message);throw e}}-function newWorkflow(){state.workflow={id:uid('sop'),name:'未命名 SOP',version:1,revision:0,status:'draft',projectId:state.projectFilter||'',shared:false,owner:'',tags:[],description:'',sandboxProfileId:'local',nodes:[],edges:[]};state.selectedNode=null;rememberOpenWorkflow();renderAll();dirty()}+function sopSandboxChoices(){+ return (state.data.sandboxes||[]).filter(s=>s.id&&catalogVisible(s.projectId,s.shared));+}+function defaultSOPSandbox(choices=sopSandboxChoices()){+ return choices.find(s=>s.id==='local')||choices.find(s=>catalogOwned(s.projectId)&&s.driver==='docker')||choices.find(s=>s.driver==='docker')||choices[0];+}+function syncSOPSandboxSelection(){+ const select=$('#sopCreateSandbox'),template=(state.data.workflows||[]).find(w=>w.id===state.sopTemplate);+ const choices=sopSandboxChoices(),sameSource=select.dataset.source===state.sopTemplate&&select.dataset.project===state.projectFilter;+ const preferred=sameSource?select.value:(template?.sandboxProfileId||defaultSOPSandbox(choices)?.id||'');+ // Generic adoption already selects a project/shared fallback on the server.+ const selected=catalogGeneric(template)+ ?choices.find(s=>s.id===template.sandboxProfileId)||choices.find(s=>catalogOwned(s.projectId))||choices[0]+ :choices.find(s=>s.id===preferred);+ select.innerHTML=`<option value="">${escapeHTML(lfT('请选择运行沙箱','Select a sandbox'))}</option>`+choices.map(s=>`<option value="${escapeHTML(s.id)}">${escapeHTML(s.name||s.id)}${catalogForeign(s.projectId)?lfT(' · 共享',' · Shared'):''}</option>`).join('');+ select.value=selected?.id||'';+ select.dataset.source=state.sopTemplate;select.dataset.project=state.projectFilter;+ select.disabled=catalogGeneric(template)||!choices.length;+ select.onchange=()=>syncSOPSandboxSelection();+ $('#sopFinish').disabled=!selected;+ $('#sopSandboxHint').textContent=!choices.length+ ?lfT('当前项目没有可用的运行沙箱,请先配置或请管理员共享一个沙箱,再点击「刷新沙箱」。','No sandbox is available for this project. Configure one or ask an administrator to share one, then refresh sandboxes.')+ :!selected?lfT('模板原有沙箱不可用,请重新选择运行沙箱。','The template sandbox is unavailable. Select a replacement sandbox.')+ :catalogGeneric(template)?lfT('通用模板优先使用原有沙箱,不可用时自动选择本项目可用沙箱。复制后可在流程设置中修改。','Starter templates prefer their original sandbox and otherwise use an available project sandbox. You can change it in SOP settings after copying.')+ :lfT('选择此 SOP 使用的运行环境,创建后仍可在流程设置中修改。','Choose the execution environment for this SOP. You can change it in SOP settings later.');+}+async function refreshSOPSandboxes(){+ const button=$('#sopRefreshSandboxes');button.disabled=true;+ try{+ state.data.sandboxes=await api('/api/sandboxes');+ // Empty installations can acquire a first sandbox without losing form input.+ const select=$('#sopCreateSandbox');+ if(!select.value&&!state.data.workflows.some(w=>w.id===state.sopTemplate))delete select.dataset.source;+ syncSOPSandboxSelection();+ }catch(err){toast(err.message)}finally{button.disabled=false}+}+function newWorkflow(){+ const sandbox=defaultSOPSandbox();+ if(!sandbox)return toast(lfT('当前项目没有可用的运行沙箱,请先到「设置 → 沙箱」配置。','No sandbox is available for this project. Configure one in Settings → Sandboxes first.'));+ state.workflow={id:uid('sop'),name:'未命名 SOP',version:1,revision:0,status:'draft',projectId:state.projectFilter||'',shared:false,owner:'',tags:[],description:'',sandboxProfileId:sandbox.id,nodes:[],edges:[]};state.selectedNode=null;rememberOpenWorkflow();renderAll();dirty();+}function openSOPWizard(){- const f=$('#sopCreateForm');f.reset();+ const f=$('#sopCreateForm');f.reset();delete $('#sopCreateSandbox').dataset.source;+ $('#sopRefreshSandboxes').onclick=refreshSOPSandboxes;const generic=(state.data.workflows||[]).filter(w=>catalogGeneric(w));const recommended=(state.data.workflows||[]).filter(w=>!catalogGeneric(w)&&['issue-fix-production','requirement-development-production'].includes(w.id));const fallback=(state.data.workflows||[]).find(w=>!catalogGeneric(w)&&w.status==='published');const choices=[...generic,...recommended,...(fallback&&!recommended.some(w=>w.id===fallback.id)?[fallback]:[])];state.sopTemplate=choices[0]?.id||'blank';$('#sopTemplateChoices').innerHTML=choices.map((w,index)=>`<label class="template-choice ${index===0?'active':''}"><input type="radio" name="template" value="${escapeHTML(w.id)}" ${index===0?'checked':''}><span class="template-icon">${catalogGeneric(w)?'通':w.id.includes('issue')?'修':w.id.includes('requirement')?'需':'▤'}</span><div><b>${escapeHTML(w.name)}</b><p>${escapeHTML(w.description||'复制生产模板')}</p><small>${catalogGeneric(w)?'通用 · 所有项目可用 · ':''}推荐 · ${w.nodes?.length||0} 个节点</small></div></label>`).join('')+`<label class="template-choice ${choices.length?'':'active'}"><input type="radio" name="template" value="blank" ${choices.length?'':'checked'}><span class="template-icon blank">+</span><div><b>从空白开始</b><p>仅适合需要完全自定义的流程</p><small>高级方式 · 0 个节点</small></div></label>`;- $('#sopTemplateChoices').querySelectorAll('input').forEach(input=>input.onchange=()=>{$$('#sopTemplateChoices .template-choice').forEach(x=>x.classList.toggle('active',x.contains(input)));state.sopTemplate=input.value});+ $('#sopTemplateChoices').querySelectorAll('input').forEach(input=>input.onchange=()=>{$$('#sopTemplateChoices .template-choice').forEach(x=>x.classList.toggle('active',x.contains(input)));state.sopTemplate=input.value;syncSOPSandboxSelection()});setSOPWizardStep(1);$('#sopCreateModal').classList.add('open');setTimeout(()=>f.elements.name.focus(),0)}-function setSOPWizardStep(step){const f=$('#sopCreateForm');if(step>1&&state.sopWizardStep===1&&!f.elements.name.value.trim())return toast('先填写一个便于团队识别的流程名称');state.sopWizardStep=Math.max(1,Math.min(3,step));f.querySelectorAll('.wizard-pane').forEach(p=>p.classList.toggle('active',Number(p.dataset.step)===state.sopWizardStep));f.querySelectorAll('[data-step-target]').forEach(b=>b.classList.toggle('active',Number(b.dataset.stepTarget)<=state.sopWizardStep));$('#sopPrev').disabled=state.sopWizardStep===1;$('#sopNext').hidden=state.sopWizardStep===3;$('#sopNext').textContent=state.sopWizardStep===1?'选择流程模板':'查看创建摘要';$('#sopFinish').hidden=state.sopWizardStep===1;$('#sopFinish').textContent=state.sopWizardStep===2?'使用此模板创建':'创建并进入设计器';$('#sopStepHint').textContent=state.sopWizardStep===1?'填写基本信息即可开始':state.sopWizardStep===2?'选择最接近的模板,后续仍可修改':'确认后进入可视化设计器';if(state.sopWizardStep===3){const template=state.data.workflows.find(w=>w.id===state.sopTemplate);$('#sopCreateSummary').innerHTML=`<div><span>流程名称</span><b>${escapeHTML(f.elements.name.value)}</b></div><div><span>负责人</span><b>${escapeHTML(f.elements.owner.value||'暂未指定')}</b></div><div><span>创建方式</span><b>${template?`基于「${escapeHTML(template.name)}」`:'空白流程'}</b></div><div><span>初始结构</span><b>${template?.nodes?.length||0} 个节点 · ${template?.edges?.length||0} 条依赖</b></div>`}}+function setSOPWizardStep(step){const f=$('#sopCreateForm');syncSOPSandboxSelection();if(step>1&&state.sopWizardStep===1&&!f.elements.name.value.trim())return toast('先填写一个便于团队识别的流程名称');state.sopWizardStep=Math.max(1,Math.min(3,step));f.querySelectorAll('.wizard-pane').forEach(p=>p.classList.toggle('active',Number(p.dataset.step)===state.sopWizardStep));f.querySelectorAll('[data-step-target]').forEach(b=>b.classList.toggle('active',Number(b.dataset.stepTarget)<=state.sopWizardStep));$('#sopPrev').disabled=state.sopWizardStep===1;$('#sopNext').hidden=state.sopWizardStep===3;$('#sopNext').textContent=state.sopWizardStep===1?'选择流程模板':'查看创建摘要';$('#sopFinish').hidden=state.sopWizardStep===1;$('#sopFinish').textContent=state.sopWizardStep===2?'使用此模板创建':'创建并进入设计器';$('#sopStepHint').textContent=state.sopWizardStep===1?'填写基本信息即可开始':state.sopWizardStep===2?'选择最接近的模板,后续仍可修改':'确认后进入可视化设计器';if(state.sopWizardStep===3){const template=state.data.workflows.find(w=>w.id===state.sopTemplate);$('#sopCreateSummary').innerHTML=`<div><span>流程名称</span><b>${escapeHTML(f.elements.name.value)}</b></div><div><span>负责人</span><b>${escapeHTML(f.elements.owner.value||'暂未指定')}</b></div><div><span>创建方式</span><b>${template?`基于「${escapeHTML(template.name)}」`:'空白流程'}</b></div><div><span>${escapeHTML(lfT('运行沙箱','Run sandbox'))}</span><b>${escapeHTML(sopSandboxChoices().find(s=>s.id===f.elements.sandboxProfileId.value)?.name||lfT('未选择','Not selected'))}</b></div><div><span>初始结构</span><b>${template?.nodes?.length||0} 个节点 · ${template?.edges?.length||0} 条依赖</b></div>`}}async function createSOPFromWizard(e){e.preventDefault();const f=e.currentTarget,template=(state.data.workflows||[]).find(w=>w.id===state.sopTemplate);const name=f.elements.name.value.trim(),description=f.elements.description.value.trim(),owner=f.elements.owner.value.trim(),tags=f.elements.tags.value.split(',').map(x=>x.trim()).filter(Boolean);+ const sandboxId=f.elements.sandboxProfileId.value;+ if(!sopSandboxChoices().some(s=>s.id===sandboxId)){+ syncSOPSandboxSelection();+ return toast($('#sopSandboxHint').textContent);+ }try{let saved;if(catalogGeneric(template)){@@ -1125,7 +1171,7 @@ async function createSOPFromWizard(e){}else{const workflow=template?clone(template):{nodes:[],edges:[]};Object.assign(workflow,{id:uid('sop'),name,description,owner,tags,status:'draft',version:1,revision:0,projectId:state.projectFilter||'',shared:false});- workflow.sandboxProfileId=workflow.sandboxProfileId||'local';+ workflow.sandboxProfileId=sandboxId;delete workflow.createdAt;delete workflow.updatedAt;saved=await api('/api/workflows',{method:'PUT',body:JSON.stringify(workflow)});}@@ -1133,7 +1179,11 @@ async function createSOPFromWizard(e){$('#sopCreateModal').classList.remove('open');renderAll();switchView('flow');const missing=catalogGeneric(template)?genericRequirementRows(saved).filter(r=>!r.ok):[];toast(missing.length?`SOP 草稿已创建;${missing.length} 项运行依赖未配置(${missing.map(r=>r.label).join('、')})`:'SOP 草稿已创建,请继续设计节点',missing.length?'':'ok')- }catch(err){toast(err.message)}}+ }catch(err){+ toast(/sandbox profile.*not found/i.test(err.message)+ ?lfT('所选运行沙箱已不可用,请点击「刷新沙箱」后重新选择。','The selected sandbox is no longer available. Refresh sandboxes and select another one.')+ :err.message);+ }}async function cloneWorkflow(id){const src=id?(state.data.workflows||[]).find(w=>w.id===id):state.workflow;if(!src?.id)return toast('先选择一条 SOP');const name=await afPrompt({title:'复制 SOP',message:'请输入复制后的 SOP 名称:',defaultValue:`${src.name} - 副本`});if(!name)return;const owner=await afPrompt({title:'SOP 负责人',message:'请输入负责人(可留空):',defaultValue:src.owner||''})??'';try{const copied=await api(`/api/workflows/${encodeURIComponent(src.id)}/clone`,{method:'POST',body:JSON.stringify({id:uid('sop'),name,owner,projectId:state.projectFilter||''})});state.data.workflows.unshift(copied);state.workflow=clone(copied);state.selectedNode=null;state.sopScope='project';markWorkflowClean();renderAll();toast('已复制到本项目')}catch(e){toast(e.message)}}async function deleteWorkflow(id){diff --git a/web/i18n-en.js b/web/i18n-en.jsindex 1c295b9b..354d4556 100644--- a/web/i18n-en.js+++ b/web/i18n-en.js@@ -115,6 +115,10 @@ Object.assign(window.LF_I18N_EN,{"当前列表":"In this list,","项不可删除,查看原因":"cannot be deleted. Show why","选择此需求":"Select this requirement",-"选择需求":"Select requirement"+"选择需求":"Select requirement",+"配置沙箱":"Configure sandbox",+"刷新沙箱":"Refresh sandboxes",+"默认运行沙箱":"Default sandbox",+"默认运行沙箱不能删除;可编辑配置或新建其他沙箱":"The default sandbox cannot be deleted; edit its settings or create another sandbox."});Object.assign(window.LF_I18N_EN,{"平台目录":"Platform catalog","通用模板按名称绑定这些 MCP,添加到本项目后即可使用。":"Generic templates bind these MCPs by name. Add one to this project to use it.","已添加到当前项目":"Added to this project","添加中…":"Adding…"});diff --git a/web/index.html b/web/index.htmlindex 49e2fdea..7650e24f 100644--- a/web/index.html+++ b/web/index.html@@ -891,7 +891,7 @@</form></div>- <div id="sopCreateModal" class="modal"><form id="sopCreateForm" class="modal-card definition-wizard-card sop-wizard-card"><button type="button" class="modal-close sop-create-close">×</button><div class="wizard-head"><div><p class="eyebrow">新建 SOP</p><h2>创建 SOP 流程</h2><p>先确定用途和起点,再进入可视化流程设计器完善节点。</p></div><span class="pill">草稿</span></div><div class="wizard-steps" data-wizard-steps="sop"><button type="button" class="active" data-step-target="1"><i>1</i><span>流程信息</span></button><button type="button" data-step-target="2"><i>2</i><span>选择起点</span></button><button type="button" data-step-target="3"><i>3</i><span>确认创建</span></button></div><div class="wizard-body"><section class="wizard-pane active" data-step="1"><div class="wizard-intro"><b>这条 SOP 解决什么问题?</b><p>清晰的用途能帮助团队快速选择正确流程。</p></div><div class="wizard-grid"><label class="wide">流程名称<input name="name" required placeholder="例如:服务端需求交付流程"></label><label>负责人<input name="owner" placeholder="团队或姓名"></label><label>标签<input name="tags" placeholder="需求, 后端, 生产"></label><label class="wide">流程说明<textarea name="description" rows="4" placeholder="适用范围、入口条件和预期交付"></textarea></label></div></section><section class="wizard-pane" data-step="2"><div class="wizard-intro"><b>选择一个流程起点</b><p>复制模板会保留节点、门禁和返工策略,之后仍可自由编辑。</p></div><div id="sopTemplateChoices" class="template-choice-grid"></div></section><section class="wizard-pane" data-step="3"><div class="wizard-intro"><b>准备创建</b><p>创建后将进入流程设计器:绑定角色、连线、配置打回。任务书和门禁在角色定义里改。</p></div><div id="sopCreateSummary" class="create-summary"></div></section></div><div class="wizard-actions"><button id="sopPrev" type="button" class="button ghost" disabled>上一步</button><span id="sopStepHint">第 1 步,共 3 步</span><button id="sopNext" type="button" class="button primary">下一步</button><button id="sopFinish" type="submit" class="button primary" hidden>创建并设计流程</button></div></form></div>+ <div id="sopCreateModal" class="modal"><form id="sopCreateForm" class="modal-card definition-wizard-card sop-wizard-card"><button type="button" class="modal-close sop-create-close">×</button><div class="wizard-head"><div><p class="eyebrow">新建 SOP</p><h2>创建 SOP 流程</h2><p>先确定用途和起点,再进入可视化流程设计器完善节点。</p></div><span class="pill">草稿</span></div><div class="wizard-steps" data-wizard-steps="sop"><button type="button" class="active" data-step-target="1"><i>1</i><span>流程信息</span></button><button type="button" data-step-target="2"><i>2</i><span>选择起点</span></button><button type="button" data-step-target="3"><i>3</i><span>确认创建</span></button></div><div class="wizard-body"><section class="wizard-pane active" data-step="1"><div class="wizard-intro"><b>这条 SOP 解决什么问题?</b><p>清晰的用途能帮助团队快速选择正确流程。</p></div><div class="wizard-grid"><label class="wide">流程名称<input name="name" required placeholder="例如:服务端需求交付流程"></label><label>负责人<input name="owner" placeholder="团队或姓名"></label><label>标签<input name="tags" placeholder="需求, 后端, 生产"></label><label class="wide">流程说明<textarea name="description" rows="4" placeholder="适用范围、入口条件和预期交付"></textarea></label></div></section><section class="wizard-pane" data-step="2"><div class="wizard-intro"><b>选择一个流程起点</b><p>复制模板会保留节点、门禁和返工策略,之后仍可自由编辑。</p></div><div id="sopTemplateChoices" class="template-choice-grid"></div><div class="wizard-grid sop-sandbox-settings"><label class="wide" for="sopCreateSandbox">运行沙箱<select class="select" id="sopCreateSandbox" name="sandboxProfileId" aria-describedby="sopSandboxHint"></select></label><p id="sopSandboxHint" class="wide" role="status"></p><div class="wide sop-sandbox-actions"><a class="button ghost small" href="/#/sandboxes" target="_blank" rel="noopener">配置沙箱</a><button id="sopRefreshSandboxes" type="button" class="button ghost small">刷新沙箱</button></div></div></section><section class="wizard-pane" data-step="3"><div class="wizard-intro"><b>准备创建</b><p>创建后将进入流程设计器:绑定角色、连线、配置打回。任务书和门禁在角色定义里改。</p></div><div id="sopCreateSummary" class="create-summary"></div></section></div><div class="wizard-actions"><button id="sopPrev" type="button" class="button ghost" disabled>上一步</button><span id="sopStepHint">第 1 步,共 3 步</span><button id="sopNext" type="button" class="button primary">下一步</button><button id="sopFinish" type="submit" class="button primary" hidden>创建并设计流程</button></div></form></div><div id="requirementModal" class="modal"><div class="modal-card req-composer req-wizard" role="dialog" aria-modal="true" aria-labelledby="reqWizardTitle">diff --git a/web/sops.css b/web/sops.cssindex d7f888bf..b1ea60ea 100644--- a/web/sops.css+++ b/web/sops.css@@ -47,6 +47,11 @@/* SOP 创建向导起点选择 */.template-choice-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(240px,1fr));gap:10px}+.sop-sandbox-settings{margin-top:20px}+.sop-sandbox-settings>.wide{grid-column:1/-1}+.sop-sandbox-settings select{width:100%;margin-top:6px}+.sop-sandbox-settings p{margin:0;color:var(--hui-secondary);font-size:12px;line-height:1.6}+.sop-sandbox-actions{display:flex;flex-wrap:wrap;gap:8px}.template-choice{display:flex;align-items:center;gap:11px;padding:12px;border:1px solid var(--line-strong);border-radius:11px;cursor:pointer;transition:all .14s ease;background:var(--bg-soft)}.template-choice:hover{border-color:rgba(91,140,255,.4)}.template-choice.active{border-color:var(--blue);background:var(--blue-soft)}diff --git a/webtest/tests/sop-sandbox-selection.test.mjs b/webtest/tests/sop-sandbox-selection.test.mjsnew file mode 100644index 00000000..4d501dc7--- /dev/null+++ b/webtest/tests/sop-sandbox-selection.test.mjs@@ -0,0 +1,115 @@+import test from 'node:test';+import assert from 'node:assert/strict';+import {loadApp} from '../lib/load-app.mjs';++async function submit(app) {+ await app.evaluate('createSOPFromWizard').call(null, {+ preventDefault() {}, currentTarget: app.document.querySelector('#sopCreateForm'),+ });+}++function openBlank(app, sandboxes) {+ app.evaluate(`state.data.workflows=[];state.data.sandboxes=${JSON.stringify(sandboxes)};openSOPWizard()`);+ const form=app.document.querySelector('#sopCreateForm');+ form.elements.name.value='Custom SOP';+ form.elements.description.value='Keep this draft';+ app.evaluate('setSOPWizardStep(2)');+ return form;+}++test('blank SOP uses an existing project sandbox when local is absent and respects the selected environment', async t=>{+ const app=await loadApp();t.after(app.close);+ openBlank(app,[+ {id:'foreign-private',name:'Other project',projectId:'other',driver:'local'},+ {id:'project-docker',name:'Project Docker',projectId:'project-1',driver:'docker'},+ {id:'shared-docker',name:'Shared Docker',projectId:'other',shared:true,driver:'docker'},+ ]);+ const select=app.document.querySelector('#sopCreateSandbox');+ assert.equal(select.value,'project-docker');+ assert.deepEqual([...select.options].filter(o=>o.value).map(o=>o.value),['project-docker','shared-docker']);+ select.value='shared-docker';select.dispatchEvent(new app.window.Event('change',{bubbles:true}));+ app.evaluate('setSOPWizardStep(3)');+ assert.match(app.document.querySelector('#sopCreateSummary').textContent,/Shared Docker/);+ app.router.put('/api/workflows',call=>({status:200,body:{...call.body,revision:1}}));+ await submit(app);+ const call=app.router.calls.find(c=>c.path==='/api/workflows'&&c.method==='PUT');+ assert.equal(call.body.sandboxProfileId,'shared-docker');+ assert.equal(app.evaluate('state.workflow.sandboxProfileId'),'shared-docker');+});++test('missing sandboxes block submission and refresh keeps the entered SOP fields', async t=>{+ const app=await loadApp();t.after(app.close);+ const form=openBlank(app,[{id:'foreign-private',projectId:'other',name:'Private',driver:'docker'}]);+ assert.equal(app.document.querySelector('#sopFinish').disabled,true);+ assert.match(app.document.querySelector('#sopSandboxHint').textContent,/没有可用.*沙箱/);+ await submit(app);+ assert.equal(app.router.calls.some(c=>c.path==='/api/workflows'&&c.method==='PUT'),false);+ assert.equal(form.elements.name.value,'Custom SOP');+ assert.equal(app.document.querySelector('#sopCreateModal').classList.contains('open'),true);+ app.router.get('/api/sandboxes',[{id:'installed-docker',name:'Installed Docker',driver:'docker'}]);+ await app.evaluate('refreshSOPSandboxes()');+ assert.equal(form.elements.name.value,'Custom SOP');+ assert.equal(form.elements.description.value,'Keep this draft');+ assert.equal(app.document.querySelector('#sopCreateSandbox').value,'installed-docker');+ assert.equal(app.document.querySelector('#sopFinish').disabled,false);+ app.router.put('/api/workflows',call=>({status:200,body:{...call.body,revision:1}}));+ await submit(app);+ assert.equal(app.evaluate('state.workflow.sandboxProfileId'),'installed-docker');+});++test('template sandbox is preserved and a missing template sandbox requires an explicit replacement', async t=>{+ const app=await loadApp();t.after(app.close);+ app.evaluate(`state.data.workflows=[{id:'template',name:'Template',status:'published',sandboxProfileId:'template-box',nodes:[],edges:[]}];+ state.data.sandboxes=[{id:'local',name:'Local'},{id:'template-box',name:'Template Box'}];openSOPWizard()`);+ const form=app.document.querySelector('#sopCreateForm');form.elements.name.value='Copied SOP';+ assert.equal(app.document.querySelector('#sopCreateSandbox').value,'template-box');+ app.evaluate(`state.data.sandboxes=state.data.sandboxes.filter(s=>s.id!=='template-box');setSOPWizardStep(2)`);+ assert.equal(app.document.querySelector('#sopCreateSandbox').value,'');+ assert.equal(app.document.querySelector('#sopFinish').disabled,true);+ await submit(app);+ assert.equal(app.router.calls.some(c=>c.path==='/api/workflows'&&c.method==='PUT'),false);+ const select=app.document.querySelector('#sopCreateSandbox');select.value='local';+ select.dispatchEvent(new app.window.Event('change',{bubbles:true}));+ app.router.put('/api/workflows',call=>({status:200,body:{...call.body,revision:1}}));+ await submit(app);+ assert.equal(app.evaluate('state.workflow.sandboxProfileId'),'local');+});++test('generic templates keep their sandbox and continue through the clone endpoint', async t=>{+ const app=await loadApp();t.after(app.close);+ app.evaluate(`state.data.workflows=[{id:'generic-template',name:'Generic',generic:true,sandboxProfileId:'generic-docker',nodes:[],edges:[]}];+ state.data.sandboxes=[];openSOPWizard()`);+ const form=app.document.querySelector('#sopCreateForm');form.elements.name.value='Generic copy';+ await submit(app);+ assert.equal(app.router.calls.some(c=>c.method==='POST'&&c.path.endsWith('/clone')),false);+ assert.equal(app.document.querySelector('#sopFinish').disabled,true);+ app.router.get('/api/sandboxes',[{id:'generic-docker',name:'Docker',driver:'docker'}]);+ await app.evaluate('refreshSOPSandboxes()');+ assert.equal(app.document.querySelector('#sopCreateSandbox').disabled,true);+ app.router.post('/api/workflows/generic-template/clone',call=>({status:200,body:{...call.body,id:'generic-copy',sandboxProfileId:'generic-docker',nodes:[],edges:[]}}));+ await submit(app);+ assert.equal(app.router.calls.some(c=>c.path==='/api/workflows/generic-template/clone'&&c.method==='POST'),true);+ assert.equal(app.evaluate('state.workflow.sandboxProfileId'),'generic-docker');+});++test('generic adoption retains its existing server fallback when the original sandbox is absent', async t=>{+ const app=await loadApp();t.after(app.close);+ app.evaluate(`state.data.workflows=[{id:'generic-template',name:'Generic',generic:true,sandboxProfileId:'missing-box',nodes:[],edges:[]}];+ state.data.sandboxes=[{id:'project-box',name:'Project Sandbox',projectId:'project-1'}];openSOPWizard()`);+ app.document.querySelector('#sopCreateForm').elements.name.value='Fallback copy';+ assert.equal(app.document.querySelector('#sopFinish').disabled,false);+ assert.equal(app.document.querySelector('#sopCreateSandbox').value,'project-box');+ app.router.post('/api/workflows/generic-template/clone',call=>({status:201,body:{...call.body,id:'fallback-copy',sandboxProfileId:'project-box',nodes:[],edges:[]}}));+ await submit(app);+ assert.equal(app.evaluate('state.workflow.sandboxProfileId'),'project-box');+ assert.equal(app.router.calls.some(c=>c.path==='/api/workflows/generic-template/clone'&&c.method==='POST'),true);+});++test('direct blank drafts choose an existing sandbox and stay unchanged when none is available', async t=>{+ const app=await loadApp();t.after(app.close);+ app.evaluate(`state.data.sandboxes=[{id:'project-native',name:'Native',projectId:'project-1',driver:'native'}];newWorkflow()`);+ assert.equal(app.evaluate('state.workflow.sandboxProfileId'),'project-native');+ const id=app.evaluate('state.workflow.id');+ app.evaluate('state.data.sandboxes=[];newWorkflow()');+ assert.equal(app.evaluate('state.workflow.id'),id);+});