Skip to content

The Unified and Autonomous Development Platform

feat: Run AI tasks via workspace automation

Robin Shen0131f242b4cd
diff --git a/run.sh b/rundev.sh
similarity index 100%
rename from run.sh
rename to rundev.sh
diff --git a/server-core/src/main/java/io/onedev/server/ai/responsehandlers/AddIssueComment.java b/server-core/src/main/java/io/onedev/server/ai/responsehandlers/AddIssueComment.java
deleted file mode 100644
index c516cac168..0000000000
--- a/server-core/src/main/java/io/onedev/server/ai/responsehandlers/AddIssueComment.java
+++ /dev/null
@@ -1,31 +0,0 @@
-package io.onedev.server.ai.responsehandlers;
-
-import java.util.Date;
-
-import io.onedev.server.OneDev;
-import io.onedev.server.ai.ResponseHandler;
-import io.onedev.server.model.IssueComment;
-import io.onedev.server.model.User;
-import io.onedev.server.service.IssueCommentService;
-import io.onedev.server.service.IssueService;
-
-public class AddIssueComment implements ResponseHandler {
-
- private final Long issueId;
-
- public AddIssueComment(Long issueId) {
- this.issueId = issueId;
- }
-
- @Override
- public void onResponse(User ai, String response) {
- var issue = OneDev.getInstance(IssueService.class).load(issueId);
- var comment = new IssueComment();
- comment.setIssue(issue);
- comment.setContent(response);
- comment.setUser(ai);
- comment.setDate(new Date());
- OneDev.getInstance(IssueCommentService.class).create(comment);
- }
-
-}
\ No newline at end of file
diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/TaskAutomation.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/TaskAutomation.java
new file mode 100644
index 0000000000..eee1f589d1
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/TaskAutomation.java
@@ -0,0 +1,67 @@
+package io.onedev.server.model.support.workspace.spec;
+
+import static io.onedev.server.model.User.Type.AI;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import javax.validation.constraints.NotEmpty;
+
+import io.onedev.server.OneDev;
+import io.onedev.server.annotation.Editable;
+import io.onedev.server.annotation.UserChoice;
+import io.onedev.server.model.User;
+import io.onedev.server.service.UserService;
+
+@Editable
+public class TaskAutomation implements Serializable {
+
+ private static final long serialVersionUID = 1L;
+
+ private String runTaskCmd;
+
+ private List<String> applicableAis = new ArrayList<>();
+
+ @Editable(order = 100, name="Command to Run Task", description = """
+ Specify command to launch coding agent in headless mode to run assigned task in form of
+ prompt. The prompt is stored in environment variable <code>$PROMPT</code>
+ """)
+ @NotEmpty
+ public String getRunTaskCmd() {
+ return runTaskCmd;
+ }
+
+ public void setRunTaskCmd(String runTaskCmd) {
+ this.runTaskCmd = runTaskCmd;
+ }
+
+ @Editable(order = 200, name = "Applicable AI Users for Task Automation", placeholder = "All AI users", description = """
+ Optionally specify applicable AI users to use this workspace spec for task automation. Leave empty to allow all AI users.
+ When a AI user creates workspace to do its job, the first applicable spec will be used.""")
+ @UserChoice("getAiUsers")
+ public List<String> getApplicableAis() {
+ return applicableAis;
+ }
+
+ public void setApplicableAis(List<String> applicableAis) {
+ this.applicableAis = applicableAis;
+ }
+
+ @SuppressWarnings("unused")
+ private static List<User> getAiUsers() {
+ var cache = OneDev.getInstance(UserService.class).cloneCache();
+ return cache.getUsers(it -> !it.isDisabled() && it.getType() == AI)
+ .stream()
+ .sorted(cache.comparingDisplayName())
+ .collect(Collectors.toList());
+ }
+
+ public void onRenameUser(String oldName, String newName) {
+ var index = applicableAis.indexOf(oldName);
+ if (index != -1)
+ applicableAis.set(index, newName);
+ }
+
+}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/WorkspaceSpec.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/WorkspaceSpec.java
index 78d82b52c8..911b8903ed 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/WorkspaceSpec.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/WorkspaceSpec.java
@@ -29,6 +29,7 @@ import io.onedev.server.model.support.administration.workspaceprovisioner.Worksp
import io.onedev.server.model.support.workspace.spec.shell.DefaultShell;
import io.onedev.server.model.support.workspace.spec.shell.WorkspaceShell;
import io.onedev.server.service.SettingService;
+import io.onedev.server.util.usage.Usage;
import io.onedev.server.validation.Validatable;
import io.onedev.server.web.util.SuggestionUtils;
@@ -76,6 +77,8 @@ public class WorkspaceSpec implements Serializable, Validatable {
private List<RegistryLogin> registryLogins = new ArrayList<>();
+ private TaskAutomation taskAutomation;
+
@Editable(order = 50, description = "Specify a name to identify this workspace spec")
@SuggestionProvider("getNameSuggestions")
@NotEmpty
@@ -229,6 +232,17 @@ public class WorkspaceSpec implements Serializable, Validatable {
public void setShortcutConfigs(List<ShortcutConfig> shortcutConfigs) {
this.shortcutConfigs = shortcutConfigs;
}
+
+ @Editable(order = 650, placeholder = "Not configured", description = """
+ Enable this if the spec can be used by AI user to create workspaces to run assigned tasks""")
+ @Valid
+ public TaskAutomation getTaskAutomation() {
+ return taskAutomation;
+ }
+
+ public void setTaskAutomation(TaskAutomation taskAutomation) {
+ this.taskAutomation = taskAutomation;
+ }
@Editable(order = 1100, name = "Retrieve LFS Files", group = "More Settings", description = "Enable this to retrieve Git LFS files")
public boolean isRetrieveLfs() {
@@ -354,4 +368,19 @@ public class WorkspaceSpec implements Serializable, Validatable {
return SuggestionUtils.suggestWorkspaceVariables(matchWith);
}
+ public void onRenameUser(String oldName, String newName) {
+ if (taskAutomation != null)
+ taskAutomation.onRenameUser(oldName, newName);
+ }
+
+ public Usage onDeleteUser(String userName) {
+ if (taskAutomation != null) {
+ if (taskAutomation.getApplicableAis().removeIf(userName::equals)
+ && taskAutomation.getApplicableAis().isEmpty()) {
+ taskAutomation = null;
+ }
+ }
+ return new Usage();
+ }
+
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/ClaudeCodeInContainer.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/ClaudeCodeInContainer.java
index 7020afaf2e..5008f11a63 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/ClaudeCodeInContainer.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/ClaudeCodeInContainer.java
@@ -22,7 +22,6 @@ public class ClaudeCodeInContainer extends WorkspaceSpecTemplate {
workspaceSpec.setName(getName());
workspaceSpec.setRunInContainer(true);
- workspaceSpec.setDescription("Claude Code, tod CLI, and companion skills are installed and accessible");
workspaceSpec.setImage("1dev/claudecode");
workspaceSpec.setShell(new CustomLinuxShell());
workspaceSpec.setRunAs("1001:1001");
@@ -41,6 +40,8 @@ public class ClaudeCodeInContainer extends WorkspaceSpecTemplate {
userData.getPaths().add("/home/claude/.local/state");
workspaceSpec.getUserDatas().add(userData);
+ configureTaskAutomation(workspaceSpec, "claude --dangerously-skip-permissions -p --verbose \"$PROMPT\"");
+
return workspaceSpec;
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/ClaudeCodeInShell.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/ClaudeCodeInShell.java
index 921e143f7c..8fd0287dfc 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/ClaudeCodeInShell.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/ClaudeCodeInShell.java
@@ -24,12 +24,13 @@ public class ClaudeCodeInShell extends WorkspaceSpecTemplate {
var workspaceSpec = new WorkspaceSpec();
workspaceSpec.setName(getName());
- workspaceSpec.setDescription("Claude Code, tod CLI, and companion skills are installed and accessible");
var shortcutConfig = new ShortcutConfig();
shortcutConfig.setName("Claude Code");
shortcutConfig.setCommand("claude");
workspaceSpec.getShortcutConfigs().add(shortcutConfig);
+ configureTaskAutomation(workspaceSpec, "claude --dangerously-skip-permissions -p --verbose \"$PROMPT\"");
+
return workspaceSpec;
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CodexInContainer.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CodexInContainer.java
index 6af0def847..ad78888d59 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CodexInContainer.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CodexInContainer.java
@@ -21,7 +21,6 @@ public class CodexInContainer extends WorkspaceSpecTemplate {
var workspaceSpec = new WorkspaceSpec();
workspaceSpec.setName(getName());
- workspaceSpec.setDescription("Codex, tod CLI, and companion skills are installed and accessible");
workspaceSpec.setRunInContainer(true);
workspaceSpec.setImage("1dev/codex");
workspaceSpec.setShell(new CustomLinuxShell());
@@ -39,6 +38,8 @@ public class CodexInContainer extends WorkspaceSpecTemplate {
userData.getPaths().add("/home/codex/.profile");
workspaceSpec.getUserDatas().add(userData);
+ configureTaskAutomation(workspaceSpec, "codex exec --dangerously-bypass-approvals-and-sandbox \"$PROMPT\"");
+
return workspaceSpec;
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CodexInShell.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CodexInShell.java
index f2988e0176..bb482f92de 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CodexInShell.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CodexInShell.java
@@ -24,12 +24,13 @@ public class CodexInShell extends WorkspaceSpecTemplate {
var workspaceSpec = new WorkspaceSpec();
workspaceSpec.setName(getName());
- workspaceSpec.setDescription("Codex, tod CLI, and companion skills are installed and accessible");
var shortcutConfig = new ShortcutConfig();
shortcutConfig.setName("Codex");
shortcutConfig.setCommand("codex");
workspaceSpec.getShortcutConfigs().add(shortcutConfig);
+ configureTaskAutomation(workspaceSpec, "codex exec --dangerously-bypass-approvals-and-sandbox \"$PROMPT\"");
+
return workspaceSpec;
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CursorInContainer.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CursorInContainer.java
index 13c66d8f1e..86b0c6e519 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CursorInContainer.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CursorInContainer.java
@@ -21,7 +21,6 @@ public class CursorInContainer extends WorkspaceSpecTemplate {
var workspaceSpec = new WorkspaceSpec();
workspaceSpec.setName(getName());
- workspaceSpec.setDescription("Cursor CLI, tod CLI, and companion skills are installed and accessible");
workspaceSpec.setRunInContainer(true);
workspaceSpec.setImage("1dev/cursor");
workspaceSpec.setShell(new CustomLinuxShell());
@@ -40,6 +39,8 @@ public class CursorInContainer extends WorkspaceSpecTemplate {
userData.getPaths().add("/home/cursor/.config/cursor");
workspaceSpec.getUserDatas().add(userData);
+ configureTaskAutomation(workspaceSpec, "agent -p --force --approve-mcps --trust \"$PROMPT\"");
+
return workspaceSpec;
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CursorInShell.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CursorInShell.java
index 782f8a5be3..8c9c326a87 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CursorInShell.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/CursorInShell.java
@@ -24,12 +24,13 @@ public class CursorInShell extends WorkspaceSpecTemplate {
var workspaceSpec = new WorkspaceSpec();
workspaceSpec.setName(getName());
- workspaceSpec.setDescription("Cursor CLI, tod CLI, and companion skills are installed and accessible");
var shortcutConfig = new ShortcutConfig();
shortcutConfig.setName("Cursor CLI");
shortcutConfig.setCommand("agent");
workspaceSpec.getShortcutConfigs().add(shortcutConfig);
+ configureTaskAutomation(workspaceSpec, "agent -p --force --approve-mcps --trust \"$PROMPT\"");
+
return workspaceSpec;
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/OpenCodeInContainer.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/OpenCodeInContainer.java
index 041b0d5ac0..97350aceb6 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/OpenCodeInContainer.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/OpenCodeInContainer.java
@@ -21,7 +21,6 @@ public class OpenCodeInContainer extends WorkspaceSpecTemplate {
var workspaceSpec = new WorkspaceSpec();
workspaceSpec.setName(getName());
- workspaceSpec.setDescription("Open Code, tod CLI, and companion skills are installed and accessible");
workspaceSpec.setRunInContainer(true);
workspaceSpec.setImage("1dev/opencode");
workspaceSpec.setRunAs("1001:1001");
@@ -41,6 +40,8 @@ public class OpenCodeInContainer extends WorkspaceSpecTemplate {
userData.getPaths().add("/home/opencode/.local/state");
workspaceSpec.getUserDatas().add(userData);
+ configureTaskAutomation(workspaceSpec, "opencode run --dangerously-skip-permissions \"$PROMPT\"");
+
return workspaceSpec;
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/OpenCodeInShell.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/OpenCodeInShell.java
index c8a4f8618c..fedded4d7c 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/OpenCodeInShell.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/OpenCodeInShell.java
@@ -24,13 +24,14 @@ public class OpenCodeInShell extends WorkspaceSpecTemplate {
var workspaceSpec = new WorkspaceSpec();
workspaceSpec.setName(getName());
- workspaceSpec.setDescription("Open Code, tod CLI, and companion skills are installed and accessible");
var shortcutConfig = new ShortcutConfig();
shortcutConfig.setName("Open Code");
shortcutConfig.setCommand("opencode");
workspaceSpec.getShortcutConfigs().add(shortcutConfig);
+ configureTaskAutomation(workspaceSpec, "opencode run --dangerously-skip-permissions \"$PROMPT\"");
+
return workspaceSpec;
}
diff --git a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/WorkspaceSpecTemplate.java b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/WorkspaceSpecTemplate.java
index 1708a983f6..9a4307b717 100644
--- a/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/WorkspaceSpecTemplate.java
+++ b/server-core/src/main/java/io/onedev/server/model/support/workspace/spec/template/WorkspaceSpecTemplate.java
@@ -5,6 +5,7 @@ import java.io.Serializable;
import javax.validation.constraints.NotEmpty;
import io.onedev.server.annotation.Editable;
+import io.onedev.server.model.support.workspace.spec.TaskAutomation;
import io.onedev.server.model.support.workspace.spec.WorkspaceSpec;
@Editable
@@ -24,4 +25,10 @@ public abstract class WorkspaceSpecTemplate implements Serializable {
public abstract WorkspaceSpec createWorkspaceSpec();
+ protected void configureTaskAutomation(WorkspaceSpec workspaceSpec, String runPromptCmd) {
+ var taskAutomation = new TaskAutomation();
+ taskAutomation.setRunTaskCmd(runPromptCmd);
+ workspaceSpec.setTaskAutomation(taskAutomation);
+ }
+
}
diff --git a/server-core/src/main/java/io/onedev/server/notification/CodeCommentNotificationManager.java b/server-core/src/main/java/io/onedev/server/notification/CodeCommentNotificationManager.java
index 45e9801e06..8571cd8d29 100644
--- a/server-core/src/main/java/io/onedev/server/notification/CodeCommentNotificationManager.java
+++ b/server-core/src/main/java/io/onedev/server/notification/CodeCommentNotificationManager.java
@@ -11,16 +11,14 @@ import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
-import org.jspecify.annotations.Nullable;
-
import com.google.common.collect.Lists;
import io.onedev.commons.utils.StringUtils;
import io.onedev.server.ai.AiTask;
import io.onedev.server.ai.responsehandlers.AddCodeCommentReply;
import io.onedev.server.ai.taskchecker.NoopTaskChecker;
-import io.onedev.server.ai.tools.codecomment.GetCodeCommentReplies;
import io.onedev.server.ai.tools.codecomment.GetCodeComment;
+import io.onedev.server.ai.tools.codecomment.GetCodeCommentReplies;
import io.onedev.server.event.Listen;
import io.onedev.server.event.project.codecomment.CodeCommentEdited;
import io.onedev.server.event.project.codecomment.CodeCommentEvent;
@@ -67,7 +65,7 @@ public class CodeCommentNotificationManager {
if (mentionedUser != null) {
mentionService.mention(comment, mentionedUser);
if (mentionedUser.getType() == User.Type.AI) {
- if (!(event instanceof CodeCommentEdited) && isAiEntitled(event.getUser(), comment, mentionedUser)) {
+ if (!(event instanceof CodeCommentEdited) && isAiEntitled(comment, mentionedUser)) {
String systemPrompt = """
You are mentioned in a code comment. The content mentioning you is presented as user prompt. \
Use existing replies as conversation context. Call relevant tools to get information about \
@@ -122,21 +120,12 @@ public class CodeCommentNotificationManager {
}
}
- private boolean isAiEntitled(@Nullable User user, CodeComment comment, User ai) {
- if (user != null && user.getId() > 0) {
- if (user.isEntitledToAi(ai)) {
- return true;
- } else {
- new AddCodeCommentReply(comment.getId()).onResponse(user, "@%s sorry but you are not entitled to access me".formatted(user.getName()));
- return false;
- }
+ private boolean isAiEntitled(CodeComment comment, User ai) {
+ if (comment.getProject().isEntitledToAi(ai)) {
+ return true;
} else {
- if (comment.getProject().isEntitledToAi(ai)) {
- return true;
- } else {
- new AddCodeCommentReply(comment.getId()).onResponse(ai, "Sorry but this project is not entitled to access me");
- return false;
- }
+ new AddCodeCommentReply(comment.getId()).onResponse(ai, "Sorry but this project is not entitled to access me");
+ return false;
}
}
diff --git a/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.java b/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.java
index 2522d48e43..1db00dde66 100644
--- a/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.java
+++ b/server-core/src/main/java/io/onedev/server/notification/IssueNotificationManager.java
@@ -8,8 +8,8 @@ import static org.unbescape.html.HtmlEscape.escapeHtml5;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
-import java.util.List;
import java.util.Map;
+import java.util.Set;
import java.util.stream.Collectors;
import javax.inject.Inject;
@@ -17,21 +17,21 @@ import javax.inject.Singleton;
import javax.mail.internet.InternetAddress;
import org.apache.commons.lang3.StringUtils;
-import org.jspecify.annotations.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
-import io.onedev.server.ai.AiTask;
-import io.onedev.server.ai.tools.issue.GetIssueComments;
-import io.onedev.server.ai.tools.issue.GetIssue;
-import io.onedev.server.ai.responsehandlers.AddIssueComment;
-import io.onedev.server.ai.taskchecker.NoopTaskChecker;
+import io.onedev.commons.utils.ExplicitException;
+import io.onedev.server.buildspecmodel.inputspec.InputSpec;
import io.onedev.server.event.Listen;
import io.onedev.server.event.project.issue.IssueCommentCreated;
import io.onedev.server.event.project.issue.IssueEvent;
import io.onedev.server.event.project.issue.IssueOpened;
import io.onedev.server.event.project.issue.IssuesMoved;
+import io.onedev.server.exception.ExceptionUtils;
import io.onedev.server.mail.MailService;
import io.onedev.server.markdown.MentionParser;
import io.onedev.server.model.EmailAddress;
@@ -48,7 +48,9 @@ import io.onedev.server.search.entity.QueryWatchBuilder;
import io.onedev.server.search.entity.issue.IssueQuery;
import io.onedev.server.search.entity.issue.IssueQueryParseOption;
import io.onedev.server.security.SecurityUtils;
+import io.onedev.server.service.GroupService;
import io.onedev.server.service.IssueAuthorizationService;
+import io.onedev.server.service.IssueCommentService;
import io.onedev.server.service.IssueMentionService;
import io.onedev.server.service.IssueQueryPersonalizationService;
import io.onedev.server.service.IssueService;
@@ -59,11 +61,14 @@ import io.onedev.server.service.UserService;
import io.onedev.server.util.ProjectScope;
import io.onedev.server.util.commenttext.MarkdownText;
import io.onedev.server.web.asset.emoji.Emojis;
+import io.onedev.server.workspace.WorkspaceService;
import io.onedev.server.xodus.VisitInfoService;
@Singleton
public class IssueNotificationManager {
+ private static final Logger logger = LoggerFactory.getLogger(IssueNotificationManager.class);
+
@Inject
private MailService mailService;
@@ -76,6 +81,9 @@ public class IssueNotificationManager {
@Inject
private UserService userService;
+ @Inject
+ private GroupService groupService;
+
@Inject
private VisitInfoService userInfoManager;
@@ -88,6 +96,12 @@ public class IssueNotificationManager {
@Inject
private IssueService issueService;
+ @Inject
+ private IssueCommentService issueCommentService;
+
+ @Inject
+ private WorkspaceService workspaceService;
+
@Inject
private UrlService urlService;
@@ -229,8 +243,8 @@ public class IssueNotificationManager {
getEmailBody(false, event, summary, event.getTextBody(), url, replyable, null),
replyAddress, senderName, threadingReferences);
}
- } else if (isAiEntitled(user, issue, member)) {
- new AddIssueComment(issue.getId()).onResponse(member, "I don't know how to work as role '%s' yet".formatted(entry.getKey()));
+ } else if (isAiEntitled(issue, member) && canCreateWorkspace(member, issue)) {
+ handleFieldAssignment(member, issue, entry.getKey());
}
}
}
@@ -262,8 +276,8 @@ public class IssueNotificationManager {
getEmailBody(false, event, summary, event.getTextBody(), url, replyable, null),
replyAddress, senderName, threadingReferences);
}
- } else if (isAiEntitled(user, issue, member)) {
- new AddIssueComment(issue.getId()).onResponse(member, "I don't know how to work as role '%s' yet".formatted(entry.getKey()));
+ } else if (isAiEntitled(issue, member) && canCreateWorkspace(member, issue)) {
+ handleFieldAssignment(member, issue, entry.getKey());
}
}
}
@@ -301,21 +315,41 @@ public class IssueNotificationManager {
getEmailBody(false, event, summary, event.getTextBody(), url, replyable, null),
replyAddress, senderName, threadingReferences);
}
- } else if (isAiEntitled(user, issue, mentionedUser)) {
- if (event instanceof IssueOpened || event instanceof IssueCommentCreated) {
- var systemPrompt = """
- You are mentioned in an issue. The content mentioning you is presented as user prompt. \
- Use existing comments as conversation context. Call relevant tools to get information \
- about the issue if necessary""";
- var task = new AiTask(
- systemPrompt.formatted(mentionedUser.getName()),
- event.getTextBody(),
- List.of(
- new GetIssue(issue.getId()),
- new GetIssueComments(issue.getId())),
- new NoopTaskChecker(),
- new AddIssueComment(issue.getId()));
- userService.execute(mentionedUser, task);
+ } else if (isAiEntitled(issue, mentionedUser)) {
+ if ((event instanceof IssueOpened || event instanceof IssueCommentCreated)
+ && canCreateWorkspace(mentionedUser, issue)) {
+ try {
+ String branch = issue.getBranch();
+ var assignedFields = getAssignedFields(mentionedUser, issue);
+ String prompt;
+ if (assignedFields.isEmpty()) {
+ if (branch == null)
+ branch = Preconditions.checkNotNull(issue.getProject().getDefaultBranch());
+ prompt = """
+ You are %s. Address %s's concern in issue %s. \
+ Examine code in workspace if necessary. \
+ Do not switch branch or modify code.\
+ """.formatted(mentionedUser.getName(), user.getName(), issue.getReference().toString(issue.getProject()));
+ } else {
+ if (branch == null)
+ branch = issueService.ensureBranch(mentionedUser.asSubject(), issue);
+ prompt = """
+ Work on current issue as roles [%s] to address %s's concern. Submit work afterwards if code is modified.
+ """.formatted(StringUtils.join(assignedFields, ", "), user.getName());
+ }
+ if (mentionedUser.getAiSetting().getSystemPrompt() != null)
+ prompt = "Rules:\n" + mentionedUser.getAiSetting().getSystemPrompt() + "\n\nUser:" + prompt;
+
+ workspaceService.runPrompt(mentionedUser, issue.getProject(), branch, prompt);
+ } catch (Throwable t) {
+ var explicitException = ExceptionUtils.find(t, ExplicitException.class);
+ if (explicitException != null) {
+ issueCommentService.create(mentionedUser, issue, explicitException.getMessage());
+ } else {
+ logger.error("Error doing job via AI user", t);
+ issueCommentService.create(mentionedUser, issue, "Failed to do the job, check server log for details");
+ }
+ }
}
}
notifiedUsers.add(mentionedUser);
@@ -374,6 +408,43 @@ public class IssueNotificationManager {
}
}
+ private Set<String> getAssignedFields(User ai, Issue issue) {
+ var assignedFieldNames = new HashSet<String>();
+ for (var field: issue.getFields()) {
+ if (field.getType().equals(InputSpec.USER) && field.getValue().equals(ai.getName()))
+ assignedFieldNames.add(field.getName());
+ if (field.getType().equals(InputSpec.GROUP)) {
+ var group = groupService.find(field.getValue());
+ if (group != null) {
+ for (var member: group.getMembers()) {
+ if (member.equals(ai))
+ assignedFieldNames.add(field.getName());
+ }
+ }
+ }
+ }
+ return assignedFieldNames;
+ }
+
+ private void handleFieldAssignment(User ai, Issue issue, String field) {
+ var fieldSpec = settingService.getIssueSetting().getFieldSpec(field);
+ if (fieldSpec != null) {
+ if (SecurityUtils.canWriteCode(ai.asSubject(), issue.getProject())) {
+ try {
+ var branch = issueService.ensureBranch(ai.asSubject(), issue);
+ workspaceService.runPrompt(ai, issue.getProject(), branch, "Work on current issue as role '%s'. Submit work afterwards if code is modified".formatted(field));
+ } catch (Throwable t) {
+ logger.error("Error doing job via AI user", t);
+ issueCommentService.create(ai, issue, "Failed to do the job, check server log for details");
+ }
+ } else {
+ issueCommentService.create(ai, issue, "I need write code permission to work as '%s' in this project".formatted(field));
+ }
+ } else {
+ issueCommentService.create(ai, issue, "I don't know how to work as '%s' since it is not defined".formatted(field));
+ }
+ }
+
@Transactional
@Listen
public void on(IssuesMoved event) {
@@ -440,21 +511,24 @@ public class IssueNotificationManager {
}
}
- private boolean isAiEntitled(@Nullable User user, Issue issue, User ai) {
- if (user != null && user.getId() > 0) {
- if (user.isEntitledToAi(ai)) {
- return true;
- } else {
- new AddIssueComment(issue.getId()).onResponse(user, "@%s sorry but you are not entitled to access me".formatted(user.getName()));
- return false;
- }
+ private boolean canCreateWorkspace(User ai, Issue issue) {
+ if (!SecurityUtils.canCreateWorkspaces(ai.asSubject(), issue.getProject())) {
+ issueCommentService.create(ai, issue, "I need to create workspace to do the job, but I don't have permission to create that");
+ return false;
+ }
+ if (issue.getProject().getDefaultBranch() == null) {
+ issueCommentService.create(ai, issue, "I need to create workspace to do the job, but the project doesn't have code yet");
+ return false;
+ }
+ return true;
+ }
+
+ private boolean isAiEntitled(Issue issue, User ai) {
+ if (issue.getProject().isEntitledToAi(ai)) {
+ return true;
} else {
- if (issue.getProject().isEntitledToAi(ai)) {
- return true;
- } else {
- new AddIssueComment(issue.getId()).onResponse(ai, "Sorry but this project is not entitled to access me");
- return false;
- }
+ issueCommentService.create(ai, issue, "Sorry but this project is not entitled to access me");
+ return false;
}
}
diff --git a/server-core/src/main/java/io/onedev/server/notification/PullRequestNotificationManager.java b/server-core/src/main/java/io/onedev/server/notification/PullRequestNotificationManager.java
index 471ef1513c..6c52c8ef8c 100644
--- a/server-core/src/main/java/io/onedev/server/notification/PullRequestNotificationManager.java
+++ b/server-core/src/main/java/io/onedev/server/notification/PullRequestNotificationManager.java
@@ -19,7 +19,6 @@ import org.apache.commons.lang3.StringUtils;
import org.apache.commons.text.WordUtils;
import org.apache.shiro.authz.Permission;
import org.eclipse.jgit.lib.ObjectId;
-import org.jspecify.annotations.Nullable;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
@@ -270,7 +269,7 @@ public class PullRequestNotificationManager {
replyAddress, senderName, threadingReferences);
}
} else if (changeData instanceof PullRequestRequestedForChangesData
- && isAiEntitled(user, request, request.getSubmitter())) {
+ && isAiEntitled(request, request.getSubmitter())) {
new AddPullRequestComment(request.getId()).onResponse(
request.getSubmitter(),
"I don't know how to improve the pull request yet");
@@ -306,7 +305,7 @@ public class PullRequestNotificationManager {
getEmailBody(false, event, assignmentSummary, event.getTextBody(), url, replyable, null),
replyAddress, senderName, threadingReferences);
}
- } else if (isAiEntitled(user, request, assignee)) {
+ } else if (isAiEntitled(request, assignee)) {
new AddPullRequestComment(request.getId()).onResponse(assignee, "I don't know how to work as assignee yet");
}
notifiedUsers.add(assignee);
@@ -337,7 +336,7 @@ public class PullRequestNotificationManager {
getEmailBody(false, event, reviewInvitationSummary, event.getTextBody(), url, replyable, null),
replyAddress, senderName, threadingReferences);
}
- } else if (isAiEntitled(null, request, reviewer)) {
+ } else if (isAiEntitled(request, reviewer)) {
var tools = new ArrayList<TaskTool>();
addPullRequestInspectionTools(tools, request, true, true);
var task = new AiTask(
@@ -376,7 +375,7 @@ public class PullRequestNotificationManager {
getEmailBody(false, event, summary, event.getTextBody(), url, replyable, null),
replyAddress, senderName, threadingReferences);
}
- } else if (isAiEntitled(user, request, mentionedUser)) {
+ } else if (isAiEntitled(request, mentionedUser)) {
if (event instanceof PullRequestOpened) {
var tools = new ArrayList<TaskTool>();
addPullRequestInspectionTools(tools, request, false, true);
@@ -506,21 +505,12 @@ public class PullRequestNotificationManager {
tools.addAll(ToolUtils.getDiffTools(projectId, oldCommitId, newCommitId, requestId));
}
- private boolean isAiEntitled(@Nullable User user, PullRequest request, User ai) {
- if (user != null && user.getId() > 0) {
- if (user.isEntitledToAi(ai)) {
- return true;
- } else {
- new AddPullRequestComment(request.getId()).onResponse(user, "@%s sorry but you are not entitled to access me".formatted(user.getName()));
- return false;
- }
+ private boolean isAiEntitled(PullRequest request, User ai) {
+ if (request.getProject().isEntitledToAi(ai)) {
+ return true;
} else {
- if (request.getProject().isEntitledToAi(ai)) {
- return true;
- } else {
- new AddPullRequestComment(request.getId()).onResponse(ai, "Sorry but this project is not entitled to access me");
- return false;
- }
+ new AddPullRequestComment(request.getId()).onResponse(ai, "Sorry but this project is not entitled to access me");
+ return false;
}
}
diff --git a/server-core/src/main/java/io/onedev/server/service/IssueCommentService.java b/server-core/src/main/java/io/onedev/server/service/IssueCommentService.java
index 38efc095bb..65598338cd 100644
--- a/server-core/src/main/java/io/onedev/server/service/IssueCommentService.java
+++ b/server-core/src/main/java/io/onedev/server/service/IssueCommentService.java
@@ -4,6 +4,7 @@ import java.util.Collection;
import java.util.Date;
import java.util.List;
+import io.onedev.server.model.Issue;
import io.onedev.server.model.IssueComment;
import io.onedev.server.model.User;
@@ -12,6 +13,8 @@ public interface IssueCommentService extends EntityService<IssueComment> {
void create(IssueComment comment);
void create(IssueComment comment, Collection<String> notifiedEmailAddresses);
+
+ void create(User user, Issue issue, String content);
void delete(User user, IssueComment comment);
diff --git a/server-core/src/main/java/io/onedev/server/service/impl/DefaultIssueCommentService.java b/server-core/src/main/java/io/onedev/server/service/impl/DefaultIssueCommentService.java
index 8a832c9a87..12e5dc492e 100644
--- a/server-core/src/main/java/io/onedev/server/service/impl/DefaultIssueCommentService.java
+++ b/server-core/src/main/java/io/onedev/server/service/impl/DefaultIssueCommentService.java
@@ -17,6 +17,7 @@ import com.google.common.base.Preconditions;
import io.onedev.server.event.ListenerRegistry;
import io.onedev.server.event.project.issue.IssueCommentCreated;
import io.onedev.server.event.project.issue.IssueCommentEdited;
+import io.onedev.server.model.Issue;
import io.onedev.server.model.IssueChange;
import io.onedev.server.model.IssueComment;
import io.onedev.server.model.User;
@@ -59,6 +60,17 @@ public class DefaultIssueCommentService extends BaseEntityService<IssueComment>
public void create(IssueComment comment) {
create(comment, new ArrayList<>());
}
+
+ @Transactional
+ @Override
+ public void create(User user, Issue issue, String content) {
+ var comment = new IssueComment();
+ comment.setIssue(issue);
+ comment.setContent(content);
+ comment.setUser(user);
+ comment.setDate(new Date());
+ create(comment);
+ }
@Transactional
@Override
diff --git a/server-core/src/main/java/io/onedev/server/service/impl/DefaultUserService.java b/server-core/src/main/java/io/onedev/server/service/impl/DefaultUserService.java
index bd1c02dd14..7184f55cea 100644
--- a/server-core/src/main/java/io/onedev/server/service/impl/DefaultUserService.java
+++ b/server-core/src/main/java/io/onedev/server/service/impl/DefaultUserService.java
@@ -194,6 +194,8 @@ public class DefaultUserService extends BaseEntityService<User> implements UserS
protection.onRenameUser(oldName, user.getName());
project.getIssueSetting().onRenameUser(oldName, user.getName());
project.getPullRequestSetting().onRenameUser(oldName, user.getName());
+ for (var spec : project.getWorkspaceSpecs())
+ spec.onRenameUser(oldName, user.getName());
} catch (Exception e) {
throw new RuntimeException("Error checking user reference in project '" + project.getPath() + "'", e);
}
@@ -359,6 +361,8 @@ public class DefaultUserService extends BaseEntityService<User> implements UserS
usageInProject.add(protection.onDeleteUser(user.getName()));
usageInProject.add(project.getIssueSetting().onDeleteUser(user.getName()));
usageInProject.add(project.getPullRequestSetting().onDeleteUser(user.getName()));
+ for (var spec : project.getWorkspaceSpecs())
+ spec.onDeleteUser(user.getName());
usageInProject.prefix("project '" + project.getPath() + "': settings");
usage.add(usageInProject);
} catch (Exception e) {
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/WorkspaceDetailPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/WorkspaceDetailPage.java
index e7c449043f..7dea038b7d 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/WorkspaceDetailPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/WorkspaceDetailPage.java
@@ -193,7 +193,7 @@ public abstract class WorkspaceDetailPage extends ProjectPage {
return new Link<Void>(id) {
@Override
public void onClick() {
- var shellId = workspaceService.openShell(getWorkspace(), name, command);
+ var shellId = workspaceService.openShell(getWorkspace(), name, command, null);
setResponsePage(WorkspaceTerminalPage.class, WorkspaceTerminalPage.paramsOf(getWorkspace(), shellId));
}
};
@@ -219,7 +219,7 @@ public abstract class WorkspaceDetailPage extends ProjectPage {
@Override
public void onClick() {
- var shellId = workspaceService.openShell(getWorkspace(), _T("Terminal"), null);
+ var shellId = workspaceService.openShell(getWorkspace(), _T("Terminal"), null, null);
setResponsePage(WorkspaceTerminalPage.class, WorkspaceTerminalPage.paramsOf(getWorkspace(), shellId));
}
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/terminal/WorkspaceTerminalPage.java b/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/terminal/WorkspaceTerminalPage.java
index 060a512972..317c1d1986 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/terminal/WorkspaceTerminalPage.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/terminal/WorkspaceTerminalPage.java
@@ -55,13 +55,12 @@ public class WorkspaceTerminalPage extends WorkspaceDetailPage {
@Override
protected void writeToStdin(IWebSocketConnection connection, String data) {
- workspaceService.onMessage(connection, getWorkspace(), shellId, "SHELL_INPUT:" + data);
+ workspaceService.onMessage(getWorkspace(), shellId, "SHELL_INPUT:" + data);
}
@Override
protected void onResized(IWebSocketConnection connection, int rows, int cols) {
- workspaceService.onMessage(connection, getWorkspace(), shellId,
- "TERMINAL_RESIZE:" + rows + "," + cols);
+ workspaceService.onMessage(getWorkspace(), shellId, "TERMINAL_RESIZE:" + rows + "," + cols);
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/workspace/DefaultWorkspaceService.java b/server-core/src/main/java/io/onedev/server/workspace/DefaultWorkspaceService.java
index 2d74f42b08..6209a15209 100644
--- a/server-core/src/main/java/io/onedev/server/workspace/DefaultWorkspaceService.java
+++ b/server-core/src/main/java/io/onedev/server/workspace/DefaultWorkspaceService.java
@@ -8,6 +8,7 @@ import java.io.ObjectStreamException;
import java.io.Serializable;
import java.util.ArrayDeque;
import java.util.ArrayList;
+import java.util.Base64;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
@@ -20,9 +21,11 @@ import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CancellationException;
+import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
+import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
@@ -124,6 +127,10 @@ public class DefaultWorkspaceService extends BaseEntityService<Workspace>
private static final String AUTO_DISCOVERED_PROVISIONER_NAME = "auto-discovered";
+ private static final String RUN_PROMPT_SUCCESS_MARKER = "__ONEDEV_RUN_PROMPT_SUCCESS__";
+
+ private static final String RUN_PROMPT_FAILURE_MARKER = "__ONEDEV_RUN_PROMPT_FAILURE__";
+
@Inject
private ProjectService projectService;
@@ -826,7 +833,8 @@ public class DefaultWorkspaceService extends BaseEntityService<Workspace>
@Sessional
@Override
- public String openShell(Workspace workspace, String label, String command) {
+ public String openShell(Workspace workspace, String label, @Nullable String command,
+ @Nullable ShellOutputCallback outputCallback) {
var workspaceId = workspace.getId();
var server = workspaceServers.get(workspaceId);
if (server == null)
@@ -839,10 +847,10 @@ public class DefaultWorkspaceService extends BaseEntityService<Workspace>
if (runtime == null)
throw new ExplicitException("Workspace runtime not found");
var shellIdRef = new AtomicReference<String>(null);
+ var shellReady = new CompletableFuture<String>();
+ var firstOutputSeen = new AtomicBoolean(false);
shellIdRef.set(runtime.openShell(new Terminal() {
- private boolean firstOutput = true;
-
@Override
public void onShellOutput(String base64Data) {
var shellId = shellIdRef.get();
@@ -850,9 +858,24 @@ public class DefaultWorkspaceService extends BaseEntityService<Workspace>
// Use runOnAllServers instead of submitToAllServers to preserve output order
clusterService.runOnAllServers(newHandleShellOutputTask(workspaceId, shellId, base64Data));
}
- if (command != null && firstOutput)
- runtime.writeShellStdin(shellId, command + "\n");
- firstOutput = false;
+ if (outputCallback != null) {
+ try {
+ outputCallback.onOutput(base64Data);
+ } catch (Throwable e) {
+ logger.error("Error calling shell output callback", e);
+ }
+ }
+
+ if (command != null && firstOutputSeen.compareAndSet(false, true)) {
+ shellReady.thenAccept(it -> {
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ throw new RuntimeException(e);
+ }
+ runtime.writeShellStdin(it, command + "\n");
+ });
+ }
}
@Override
@@ -863,7 +886,9 @@ public class DefaultWorkspaceService extends BaseEntityService<Workspace>
}
}, label));
- return shellIdRef.get();
+ var shellId = shellIdRef.get();
+ shellReady.complete(shellId);
+ return shellId;
}
});
@@ -908,8 +933,7 @@ public class DefaultWorkspaceService extends BaseEntityService<Workspace>
@Sessional
@Override
- public void onMessage(IWebSocketConnection connection, Workspace workspace,
- String shellId, String message) {
+ public void onMessage(Workspace workspace, String shellId, String message) {
if (message.startsWith("SHELL_INPUT:") || message.startsWith("TERMINAL_RESIZE:")) {
var workspaceId = workspace.getId();
var server = workspaceServers.get(workspaceId);
@@ -1076,6 +1100,91 @@ public class DefaultWorkspaceService extends BaseEntityService<Workspace>
return activeWorkspaceIds;
}
+ @Transactional
+ @Override
+ public void runPrompt(User ai, Project project, String branch, String prompt) {
+ WorkspaceSpec applicableSpec = null;
+ for (var spec : project.getWorkspaceSpecs()) {
+ if (spec.getTaskAutomation() != null) {
+ var applicableUsers = spec.getTaskAutomation().getApplicableAis();
+ if (applicableUsers.isEmpty() || applicableUsers.contains(ai.getName())) {
+ applicableSpec = spec;
+ break;
+ }
+ }
+ }
+ if (applicableSpec != null) {
+ final WorkspaceSpec finalApplicableSpec = applicableSpec;
+ var workspaceId = create(ai, project, project.getObjectId(branch, true), branch, applicableSpec.getName()).getId();
+
+ transactionService.runAfterCommit(() -> {
+ executorService.execute(() -> {
+ while (true) {
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ }
+ if (sessionService.call(() -> {
+ var workspace = get(workspaceId);
+ if (workspace == null) {
+ logger.warn("AI task ignored as task workspace no longer exists");
+ return true;
+ }
+
+ if (workspace.getStatus() == Workspace.Status.ACTIVE) {
+ var command = decorateRunPromptCommand(finalApplicableSpec.getTaskAutomation().getRunTaskCmd(), prompt);
+ var buffer = new StringBuilder();
+ openShell(workspace, "Terminal", command, base64Data -> {
+ synchronized (buffer) {
+ try {
+ buffer.append(new String(Base64.getDecoder().decode(base64Data), UTF_8));
+ } catch (IllegalArgumentException e) {
+ logger.debug("Unable to decode shell output", e);
+ return;
+ }
+ if (buffer.indexOf(RUN_PROMPT_SUCCESS_MARKER) != -1) {
+ delete(load(workspaceId));
+ } else if (buffer.length() > 1024) {
+ buffer.delete(0, buffer.length() - 1024);
+ }
+ }
+ });
+ return true;
+ } else {
+ return false;
+ }
+ })) {
+ break;
+ }
+ }
+ });
+ });
+ } else {
+ throw new ExplicitException("I need to create workspace to do the job, but no applicable workspace spec found");
+ }
+ }
+
+ private String decorateRunPromptCommand(String command, String prompt) {
+ return "(\n"
+ + "\texport PROMPT=" + shellQuote(prompt) + "\n"
+ + command + "\n"
+ + ")\n"
+ + "if [ $? -eq 0 ]; then\n"
+ + "\t" + shellPrintMarker(RUN_PROMPT_SUCCESS_MARKER) + "\n"
+ + "else\n"
+ + "\t" + shellPrintMarker(RUN_PROMPT_FAILURE_MARKER) + "\n"
+ + "fi";
+ }
+
+ private String shellQuote(String value) {
+ return "'" + value.replace("'", "'\"'\"'") + "'";
+ }
+
+ private String shellPrintMarker(String marker) {
+ var splitIndex = marker.lastIndexOf('_', marker.length() - 3) + 1;
+ return "printf '%s\\n' " + shellQuote(marker.substring(0, splitIndex)) + shellQuote(marker.substring(splitIndex));
+ }
+
private ClusterTask<Void> newRunWorkspaceTask(WorkspaceContext context) {
return new ClusterTask<Void>() {
@@ -1096,11 +1205,13 @@ public class DefaultWorkspaceService extends BaseEntityService<Workspace>
var workspace = load(workspaceId);
workspace.setStatus(Workspace.Status.ACTIVE);
workspace.setActiveDate(new Date());
- var firstShortcut = context.getSpec().getShortcutConfigs().stream().findFirst().orElse(null);
- if (firstShortcut != null)
- openShell(workspace, firstShortcut.getName(), firstShortcut.getCommand());
- else
- openShell(workspace, "Terminal", null);
+ if (workspace.getUser().getType() != User.Type.AI) {
+ var firstShortcut = context.getSpec().getShortcutConfigs().stream().findFirst().orElse(null);
+ if (firstShortcut != null)
+ openShell(workspace, firstShortcut.getName(), firstShortcut.getCommand(), null);
+ else
+ openShell(workspace, "Terminal", null, null);
+ }
update(workspace);
listenerRegistry.post(new WorkspaceActive(workspace));
});
diff --git a/server-core/src/main/java/io/onedev/server/workspace/ShellOutputCallback.java b/server-core/src/main/java/io/onedev/server/workspace/ShellOutputCallback.java
new file mode 100644
index 0000000000..605f8b1c2d
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/workspace/ShellOutputCallback.java
@@ -0,0 +1,9 @@
+package io.onedev.server.workspace;
+
+import java.io.Serializable;
+
+public interface ShellOutputCallback extends Serializable {
+
+ void onOutput(String base64Data);
+
+}
diff --git a/server-core/src/main/java/io/onedev/server/workspace/WorkspaceRuntime.java b/server-core/src/main/java/io/onedev/server/workspace/WorkspaceRuntime.java
index 59a4acdc52..30deece7bd 100644
--- a/server-core/src/main/java/io/onedev/server/workspace/WorkspaceRuntime.java
+++ b/server-core/src/main/java/io/onedev/server/workspace/WorkspaceRuntime.java
@@ -30,8 +30,10 @@ public abstract class WorkspaceRuntime {
@Override
public void onShellExit() {
- labels.remove(shellId);
- shells.remove(shellId);
+ synchronized (WorkspaceRuntime.this) {
+ labels.remove(shellId);
+ shells.remove(shellId);
+ }
terminal.onShellExit();
}
diff --git a/server-core/src/main/java/io/onedev/server/workspace/WorkspaceService.java b/server-core/src/main/java/io/onedev/server/workspace/WorkspaceService.java
index a94c24085a..133bc0a1e4 100644
--- a/server-core/src/main/java/io/onedev/server/workspace/WorkspaceService.java
+++ b/server-core/src/main/java/io/onedev/server/workspace/WorkspaceService.java
@@ -51,7 +51,8 @@ public interface WorkspaceService extends EntityService<Workspace> {
*/
File getLogFile(Long projectId, Long workspaceNumber);
- String openShell(Workspace workspace, String label, @Nullable String command);
+ String openShell(Workspace workspace, String label, @Nullable String command,
+ @Nullable ShellOutputCallback outputCallback);
Map<String, String> getShellLabels(Workspace workspace);
@@ -65,8 +66,8 @@ public interface WorkspaceService extends EntityService<Workspace> {
void onClose(IWebSocketConnection connection);
- void onMessage(IWebSocketConnection connection, Workspace workspace,
- String shellId, String message);
+ void onMessage(Workspace workspace, String shellId, String message);
+
@Nullable
WorkspaceContext getWorkspaceContext(String token, boolean mustExist);
@@ -76,4 +77,6 @@ public interface WorkspaceService extends EntityService<Workspace> {
@Nullable
FileData readFileData(Workspace workspace, String path);
+ void runPrompt(User ai, Project project, String branch, String prompt);
+
}