Skip to content

The Unified and Autonomous Development Platform

feat: Enable AI users to work on assigned issues via workspace

Robin Shende7fa764f8b7
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
index 7f2c3a79ff..5e906166cf 100644
--- 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
@@ -24,6 +24,8 @@ public class TaskAutomation implements Serializable {
private List<String> applicableAis = new ArrayList<>();
+ private boolean deleteWorkspaceIfSucceeded = true;
+
@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>$TASK_PROMPT</code>
@@ -49,6 +51,18 @@ public class TaskAutomation implements Serializable {
this.applicableAis = applicableAis;
}
+ @Editable(order = 300, description = """
+ Whether or not to delete workspace if task command completes successfully. Uncheck this if
+ you want to check how the prompt is processed by coding agent after task command completes
+ successfully. Note that workspace will not be deleted automatically if task command fails.""")
+ public boolean isDeleteWorkspaceIfSucceeded() {
+ return deleteWorkspaceIfSucceeded;
+ }
+
+ public void setDeleteWorkspaceIfSucceeded(boolean deleteWorkspaceIfSucceeded) {
+ this.deleteWorkspaceIfSucceeded = deleteWorkspaceIfSucceeded;
+ }
+
@SuppressWarnings("unused")
private static List<User> getAiUsers() {
var cache = OneDev.getInstance(UserService.class).cloneCache();
diff --git a/server-core/src/main/java/io/onedev/server/notification/BuildNotificationManager.java b/server-core/src/main/java/io/onedev/server/notification/BuildNotificationManager.java
index 25901e2f85..bbe7caee53 100644
--- a/server-core/src/main/java/io/onedev/server/notification/BuildNotificationManager.java
+++ b/server-core/src/main/java/io/onedev/server/notification/BuildNotificationManager.java
@@ -1,40 +1,49 @@
package io.onedev.server.notification;
+import static io.onedev.server.notification.NotificationUtils.getEmailBody;
+import static java.lang.String.format;
+import static java.util.stream.Collectors.toList;
+
+import java.io.ObjectStreamException;
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+
+import javax.inject.Inject;
+import javax.inject.Singleton;
+
+import org.apache.shiro.authz.Permission;
+import org.jspecify.annotations.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import com.google.common.collect.Lists;
+
+import io.onedev.commons.loader.ManagedSerializedForm;
import io.onedev.commons.utils.StringUtils;
-import io.onedev.server.service.SettingService;
-import io.onedev.server.service.UrlService;
-import io.onedev.server.service.UserService;
import io.onedev.server.event.Listen;
import io.onedev.server.event.project.build.BuildEvent;
import io.onedev.server.event.project.build.BuildUpdated;
import io.onedev.server.mail.MailService;
-import io.onedev.server.model.*;
+import io.onedev.server.model.Build;
+import io.onedev.server.model.BuildQueryPersonalization;
+import io.onedev.server.model.EmailAddress;
+import io.onedev.server.model.Project;
+import io.onedev.server.model.User;
import io.onedev.server.model.support.NamedQuery;
import io.onedev.server.persistence.annotation.Sessional;
import io.onedev.server.search.entity.build.BuildQuery;
import io.onedev.server.security.permission.AccessBuild;
import io.onedev.server.security.permission.JobPermission;
import io.onedev.server.security.permission.ProjectPermission;
-
-import org.apache.shiro.authz.Permission;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import org.jspecify.annotations.Nullable;
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import java.util.Collection;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Map;
-
-import static io.onedev.server.notification.NotificationUtils.getEmailBody;
-import static java.lang.String.format;
-import static java.util.stream.Collectors.toList;
+import io.onedev.server.service.SettingService;
+import io.onedev.server.service.UrlService;
+import io.onedev.server.service.UserService;
@Singleton
-public class BuildNotificationManager {
+public class BuildNotificationManager implements Serializable {
private static final Logger logger = LoggerFactory.getLogger(BuildNotificationManager.class);
@@ -210,4 +219,8 @@ public class BuildNotificationManager {
}
}
+ public Object writeReplace() throws ObjectStreamException {
+ return new ManagedSerializedForm(BuildNotificationManager.class);
+ }
+
}
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 8571cd8d29..789a78eea5 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
@@ -3,6 +3,8 @@ package io.onedev.server.notification;
import static io.onedev.server.notification.NotificationUtils.getEmailBody;
import static java.util.stream.Collectors.toSet;
+import java.io.ObjectStreamException;
+import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
@@ -13,6 +15,7 @@ import javax.inject.Singleton;
import com.google.common.collect.Lists;
+import io.onedev.commons.loader.ManagedSerializedForm;
import io.onedev.commons.utils.StringUtils;
import io.onedev.server.ai.AiTask;
import io.onedev.server.ai.responsehandlers.AddCodeCommentReply;
@@ -34,7 +37,7 @@ import io.onedev.server.service.UserService;
import io.onedev.server.util.commenttext.MarkdownText;
@Singleton
-public class CodeCommentNotificationManager {
+public class CodeCommentNotificationManager implements Serializable {
@Inject
private MailService mailService;
@@ -129,4 +132,8 @@ public class CodeCommentNotificationManager {
}
}
+ public Object writeReplace() throws ObjectStreamException {
+ return new ManagedSerializedForm(CodeCommentNotificationManager.class);
+ }
+
}
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 481b0d9fc1..05a3047717 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
@@ -5,9 +5,12 @@ import static io.onedev.server.notification.NotificationUtils.isNotified;
import static io.onedev.server.util.EmailAddressUtils.describe;
import static org.unbescape.html.HtmlEscape.escapeHtml5;
+import java.io.ObjectStreamException;
+import java.io.Serializable;
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;
@@ -24,7 +27,13 @@ import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
+import io.onedev.commons.loader.ManagedSerializedForm;
import io.onedev.commons.utils.ExplicitException;
+import io.onedev.server.ai.AiTask;
+import io.onedev.server.ai.ResponseHandler;
+import io.onedev.server.ai.taskchecker.NoopTaskChecker;
+import io.onedev.server.ai.tools.issue.GetIssue;
+import io.onedev.server.ai.tools.issue.GetIssueComments;
import io.onedev.server.buildspecmodel.inputspec.InputSpec;
import io.onedev.server.event.Listen;
import io.onedev.server.event.project.issue.IssueCommentCreated;
@@ -61,11 +70,12 @@ 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.TaskFailedCallback;
import io.onedev.server.workspace.WorkspaceService;
import io.onedev.server.xodus.VisitInfoService;
@Singleton
-public class IssueNotificationManager {
+public class IssueNotificationManager implements Serializable {
private static final Logger logger = LoggerFactory.getLogger(IssueNotificationManager.class);
@@ -215,7 +225,7 @@ public class IssueNotificationManager {
if (user != null) {
if (!user.isNotifyOwnEvents() || isNotified(notifiedEmailAddresses, user))
notifiedUsers.add(user);
- if (!user.isSystem() && user.getType() != User.Type.AI)
+ if (!user.isSystem())
watchService.watch(issue, user, true);
}
@@ -243,18 +253,19 @@ public class IssueNotificationManager {
getEmailBody(false, event, summary, event.getTextBody(), url, replyable, null),
replyAddress, senderName, threadingReferences);
}
- } else if (isAiEntitled(issue, member) && canCreateWorkspace(member, issue)) {
- handleFieldAssignment(member, issue, entry.getKey());
+ watchService.watch(issue, member, true);
+ authorizationService.authorize(issue, member);
+ } else if (isAiEntitled(issue, member)) {
+ if (canCreateWorkspace(member, issue))
+ handleFieldAssignment(member, issue, entry.getKey());
+ watchService.watch(issue, member, true);
+ authorizationService.authorize(issue, member);
+ } else {
+ authorizationService.authorize(issue, member);
}
}
}
- for (User member: entry.getValue().getMembers()) {
- if (member.getType() != User.Type.AI)
- watchService.watch(issue, member, true);
- authorizationService.authorize(issue, member);
- }
-
notifiedUsers.addAll(entry.getValue().getMembers());
}
@@ -265,10 +276,10 @@ public class IssueNotificationManager {
entry.getKey(),
emojis.apply(issue.getTitle()));
String threadingReferences = String.format("<you-in-field-%s-%s@onedev>", entry.getKey(), issue.getUUID());
- for (User member: entry.getValue()) {
- if (!member.equals(user)) {
- if (member.getType() != User.Type.AI) {
- EmailAddress emailAddress = member.getPrimaryEmailAddress();
+ for (User assignedUser: entry.getValue()) {
+ if (!assignedUser.equals(user)) {
+ if (assignedUser.getType() != User.Type.AI) {
+ EmailAddress emailAddress = assignedUser.getPrimaryEmailAddress();
if (emailAddress != null && emailAddress.isVerified()) {
mailService.sendMailAsync(Sets.newHashSet(emailAddress.getValue()),
Lists.newArrayList(), Lists.newArrayList(), subject,
@@ -276,17 +287,19 @@ public class IssueNotificationManager {
getEmailBody(false, event, summary, event.getTextBody(), url, replyable, null),
replyAddress, senderName, threadingReferences);
}
- } else if (isAiEntitled(issue, member) && canCreateWorkspace(member, issue)) {
- handleFieldAssignment(member, issue, entry.getKey());
+ watchService.watch(issue, assignedUser, true);
+ authorizationService.authorize(issue, assignedUser);
+ } else if (isAiEntitled(issue, assignedUser)) {
+ if (canCreateWorkspace(assignedUser, issue))
+ handleFieldAssignment(assignedUser, issue, entry.getKey());
+ watchService.watch(issue, assignedUser, true);
+ authorizationService.authorize(issue, assignedUser);
+ } else {
+ authorizationService.authorize(issue, assignedUser);
}
}
}
- for (User each: entry.getValue()) {
- if (each.getType() != User.Type.AI)
- watchService.watch(issue, each, true);
- authorizationService.authorize(issue, each);
- }
notifiedUsers.addAll(entry.getValue());
}
@@ -297,10 +310,9 @@ public class IssueNotificationManager {
if (mentionedUser != null) {
mentionService.mention(issue, mentionedUser);
authorizationService.authorize(issue, mentionedUser);
- if (mentionedUser.getType() != User.Type.AI)
- watchService.watch(issue, mentionedUser, true);
if (!isNotified(notifiedEmailAddresses, mentionedUser)) {
if (mentionedUser.getType() != User.Type.AI) {
+ watchService.watch(issue, mentionedUser, true);
String subject = String.format(
"[Issue %s] (Mentioned You) %s",
issue.getReference(),
@@ -315,41 +327,17 @@ public class IssueNotificationManager {
getEmailBody(false, event, summary, event.getTextBody(), url, replyable, null),
replyAddress, senderName, threadingReferences);
}
- } 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());
- }
- 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");
- }
- }
- }
+ } else if (isAiEntitled(issue, mentionedUser)
+ && user != null
+ && user.getId() > 0
+ && !user.equals(mentionedUser)
+ && canCreateWorkspace(mentionedUser, issue)) {
+ watchService.watch(issue, mentionedUser, true);
+ addressConcern(user, mentionedUser, issue);
}
notifiedUsers.add(mentionedUser);
+ } else {
+ watchService.watch(issue, mentionedUser, true);
}
}
}
@@ -366,13 +354,39 @@ public class IssueNotificationManager {
for (IssueWatch watch: issue.getWatches()) {
Date visitDate = userInfoManager.getIssueVisitDate(watch.getUser(), issue);
if (watch.isWatching()
- && (visitDate == null || visitDate.before(event.getDate()))
- && !notifiedUsers.contains(watch.getUser())
- && !isNotified(notifiedEmailAddresses, watch.getUser())
- && SecurityUtils.canAccessIssue(watch.getUser().asSubject(), issue)) {
- EmailAddress emailAddress = watch.getUser().getPrimaryEmailAddress();
- if (emailAddress != null && emailAddress.isVerified())
- bccEmailAddresses.add(emailAddress.getValue());
+ && (visitDate == null || visitDate.before(event.getDate()))
+ && !notifiedUsers.contains(watch.getUser())
+ && !isNotified(notifiedEmailAddresses, watch.getUser())
+ && SecurityUtils.canAccessIssue(watch.getUser().asSubject(), issue)) {
+ if (watch.getUser().getType() != User.Type.AI) {
+ EmailAddress emailAddress = watch.getUser().getPrimaryEmailAddress();
+ if (emailAddress != null && emailAddress.isVerified())
+ bccEmailAddresses.add(emailAddress.getValue());
+ } else if (event.getCommentText() instanceof MarkdownText
+ && user != null
+ && user.getId() > 0
+ && !user.equals(watch.getUser())) {
+ var issueId = issue.getId();
+ var task = new AiTask(
+ null,
+ "Check issue and comments to see if you should respond to %s's latest comment. If you think you should, reply with 'yes', otherwise reply with 'no'. No any explanation should be included in your response".formatted(event.getUser().getName()),
+ List.of(new GetIssue(issue.getId()), new GetIssueComments(issue.getId())),
+ new NoopTaskChecker(),
+ new ResponseHandler() {
+
+ @Override
+ public void onResponse(User ai, String response) {
+ var issue = issueService.load(issueId);
+ if (response.equalsIgnoreCase("yes")
+ && isAiEntitled(issue, ai)
+ && canCreateWorkspace(ai, issue)) {
+ addressConcern(user, ai, issue);
+ }
+ }
+
+ });
+ userService.execute(watch.getUser(), task);
+ }
}
}
@@ -405,6 +419,47 @@ public class IssueNotificationManager {
}
}
+ private void addressConcern(User commenter, User ai, Issue issue) {
+ try {
+ String branch = issue.getBranch();
+ var assignedFields = getAssignedFields(ai, 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(ai.getName(), commenter.getName(), issue.getReference().toString(issue.getProject()));
+ } else {
+ if (branch == null)
+ branch = issueService.ensureBranch(ai.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, ", "), commenter.getName());
+ }
+ var taskFailedCallback = newTaskFailedCallback(ai.getId(), issue.getId());
+ workspaceService.runPrompt(ai, issue.getProject(), branch, prompt, taskFailedCallback);
+ } catch (Throwable t) {
+ var explicitException = ExceptionUtils.find(t, ExplicitException.class);
+ if (explicitException != null) {
+ createComment(ai, issue, explicitException.getMessage());
+ } else {
+ logger.error("Error doing job via AI user", t);
+ createComment(ai, issue, "Failed to do the job, check server log for details");
+ }
+ }
+ }
+
+ private void createComment(User ai, Issue issue, String comment) {
+ if (SecurityUtils.canAccessIssue(ai.asSubject(), issue)) {
+ issueCommentService.create(ai, issue, comment);
+ } else {
+ issueCommentService.create(userService.getSystem(), issue, "_Commenting on behalf of **%s** as the user does not even have permission to post here._\n\n%s".formatted(ai.getName(), comment));
+ }
+ }
+
private Set<String> getAssignedFields(User ai, Issue issue) {
var assignedFieldNames = new HashSet<String>();
for (var field: issue.getFields()) {
@@ -429,19 +484,30 @@ public class IssueNotificationManager {
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));
+ var taskFailedCallback = newTaskFailedCallback(ai.getId(), issue.getId());
+ workspaceService.runPrompt(ai, issue.getProject(), branch, "Work on current issue as role '%s'. Submit work afterwards if code is modified".formatted(field), taskFailedCallback);
} 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");
+ createComment(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));
+ createComment(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));
+ createComment(ai, issue, "I don't know how to work as '%s' since it is not defined".formatted(field));
}
}
+ private TaskFailedCallback newTaskFailedCallback(Long aiId, Long issueId) {
+ return new TaskFailedCallback() {
+
+ public void onTaskFailed(String workspaceReference) {
+ createComment(userService.load(aiId), issueService.load(issueId), "Failed to do the job, please open workspace %s for details".formatted(workspaceReference));
+ }
+
+ };
+ }
+
@Transactional
@Listen
public void on(IssuesMoved event) {
@@ -509,12 +575,12 @@ public class IssueNotificationManager {
}
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");
+ if (!SecurityUtils.canCreateWorkspaces(ai.asSubject(), issue.getProject())) {
+ createComment(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");
+ createComment(ai, issue, "I need to create workspace to do the job, but the project doesn't have code yet");
return false;
}
return true;
@@ -524,9 +590,13 @@ public class IssueNotificationManager {
if (issue.getProject().isEntitledToAi(ai)) {
return true;
} else {
- issueCommentService.create(ai, issue, "Sorry but this project is not entitled to access me");
+ createComment(ai, issue, "Sorry but this project is not entitled to access me");
return false;
}
}
+ public Object writeReplace() throws ObjectStreamException {
+ return new ManagedSerializedForm(IssueNotificationManager.class);
+ }
+
}
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 6c52c8ef8c..dc1739425c 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
@@ -3,6 +3,8 @@ package io.onedev.server.notification;
import static io.onedev.server.notification.NotificationUtils.getEmailBody;
import static io.onedev.server.notification.NotificationUtils.isNotified;
+import java.io.ObjectStreamException;
+import java.io.Serializable;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
@@ -23,6 +25,7 @@ import org.eclipse.jgit.lib.ObjectId;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
+import io.onedev.commons.loader.ManagedSerializedForm;
import io.onedev.server.ai.AiTask;
import io.onedev.server.ai.TaskTool;
import io.onedev.server.ai.ToolUtils;
@@ -79,7 +82,7 @@ import io.onedev.server.web.asset.emoji.Emojis;
import io.onedev.server.xodus.VisitInfoService;
@Singleton
-public class PullRequestNotificationManager {
+public class PullRequestNotificationManager implements Serializable {
private static final String AI_REVIEW_DECISION_TOOLS = """
one of these tools, and call it only once: `{0}` if you are satisfied with the change, or `{1}` if you \
@@ -514,4 +517,8 @@ public class PullRequestNotificationManager {
}
}
+ public Object writeReplace() throws ObjectStreamException {
+ return new ManagedSerializedForm(PullRequestNotificationManager.class);
+ }
+
}
diff --git a/server-core/src/main/java/io/onedev/server/web/component/entity/watches/EntityWatchesPanel.java b/server-core/src/main/java/io/onedev/server/web/component/entity/watches/EntityWatchesPanel.java
index 4417ed6f1c..86ac210081 100644
--- a/server-core/src/main/java/io/onedev/server/web/component/entity/watches/EntityWatchesPanel.java
+++ b/server-core/src/main/java/io/onedev/server/web/component/entity/watches/EntityWatchesPanel.java
@@ -1,6 +1,6 @@
package io.onedev.server.web.component.entity.watches;
-import static io.onedev.server.model.User.Type.ORDINARY;
+import static io.onedev.server.model.User.Type.SERVICE;
import static io.onedev.server.web.translation.Translation._T;
import java.util.ArrayList;
@@ -110,7 +110,7 @@ public abstract class EntityWatchesPanel extends Panel {
@Override
protected void onConfigure() {
super.onConfigure();
- setVisible(SecurityUtils.getAuthUser() != null && SecurityUtils.getAuthUser().getType() == ORDINARY);
+ setVisible(SecurityUtils.getAuthUser() != null && SecurityUtils.getAuthUser().getType() != SERVICE);
}
@Override
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/terminal/TerminalTab.java b/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/terminal/TerminalTab.java
index bbc0d1d702..710c956e8b 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/terminal/TerminalTab.java
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/terminal/TerminalTab.java
@@ -6,6 +6,7 @@ import org.apache.wicket.model.Model;
import io.onedev.server.model.Workspace;
import io.onedev.server.web.page.project.workspaces.detail.WorkspaceTab;
+import io.onedev.server.web.util.WicketUtils;
public class TerminalTab extends WorkspaceTab {
@@ -21,6 +22,11 @@ public class TerminalTab extends WorkspaceTab {
return new TerminalTabHead(componentId, this, shellId);
}
+ @Override
+ protected Component renderOptions(String componentId) {
+ return ((WorkspaceTerminalPage) WicketUtils.getPage()).renderOptions(componentId);
+ }
+
@Override
public boolean isActive(Page currentPage) {
if (super.isActive(currentPage)) {
diff --git a/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/terminal/WorkspaceTerminalPage.html b/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/terminal/WorkspaceTerminalPage.html
index a8fb32dcfd..99a7d597e3 100644
--- a/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/terminal/WorkspaceTerminalPage.html
+++ b/server-core/src/main/java/io/onedev/server/web/page/project/workspaces/detail/terminal/WorkspaceTerminalPage.html
@@ -1,3 +1,8 @@
<wicket:extend>
<div wicket:id="terminal" class="d-flex flex-column flex-grow-1 p-2 bg-black"></div>
+ <wicket:fragment wicket:id="optionsFrag">
+ <span class="px-3" t:data-tippy-content="To scroll in this terminal, press ctrl+b then [, and use arrow keys or page up/down. Press q to exit.">
+ <wicket:svg href="bulb" class="icon"/>
+ </span>
+ </wicket:fragment>
</wicket:extend>
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 317c1d1986..97878e9f1f 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
@@ -2,8 +2,10 @@ package io.onedev.server.web.page.project.workspaces.detail.terminal;
import javax.inject.Inject;
+import org.apache.wicket.Component;
import org.apache.wicket.RestartResponseException;
import org.apache.wicket.core.request.handler.IPartialPageRequestHandler;
+import org.apache.wicket.markup.html.panel.Fragment;
import org.apache.wicket.protocol.ws.api.IWebSocketConnection;
import org.apache.wicket.request.mapper.parameter.PageParameters;
@@ -75,6 +77,10 @@ public class WorkspaceTerminalPage extends WorkspaceDetailPage {
});
}
+
+ public Component renderOptions(String componentId) {
+ return new Fragment(componentId, "optionsFrag", this);
+ }
public static PageParameters paramsOf(Workspace workspace, String shellId) {
var params = WorkspaceDetailPage.paramsOf(workspace);
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 ce67a846ae..57ce83965b 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
@@ -1102,7 +1102,7 @@ public class DefaultWorkspaceService extends BaseEntityService<Workspace>
@Transactional
@Override
- public void runPrompt(User ai, Project project, String branch, String prompt) {
+ public void runPrompt(User ai, Project project, String branch, String prompt, TaskFailedCallback taskFailedCallback) {
WorkspaceSpec applicableSpec = null;
for (var spec : project.getWorkspaceSpecs()) {
if (spec.getTaskAutomation() != null) {
@@ -1126,38 +1126,48 @@ public class DefaultWorkspaceService extends BaseEntityService<Workspace>
}
if (sessionService.call(() -> {
var workspace = get(workspaceId);
- if (workspace == null) {
+ if (workspace == null) {
logger.warn("AI task ignored as task workspace no longer exists");
return true;
}
+ var workspaceReference = workspace.getReference().toString(project);
if (workspace.getStatus() == Workspace.Status.ACTIVE) {
String fullPrompt;
if (ai.getAiSetting().getSystemPrompt() != null)
fullPrompt = "Rules:\n" + ai.getAiSetting().getSystemPrompt() + "\n\nUser:\n" + prompt;
else
fullPrompt = prompt;
-
+
var command = finalApplicableSpec.getShell().decorateRunPromptCommand(
finalApplicableSpec.getTaskAutomation().getRunTaskCmd(), fullPrompt,
RUN_PROMPT_SUCCESS_MARKER, RUN_PROMPT_FAILURE_MARKER);
var buffer = new StringBuilder();
+ var commandCompleted = new AtomicBoolean(false);
openShell(workspace, "Terminal", command, base64Data -> {
- synchronized (buffer) {
+ if (!commandCompleted.get()) synchronized (buffer) {
try {
buffer.append(new String(Base64.getDecoder().decode(base64Data), UTF_8));
} catch (IllegalArgumentException e) {
logger.warn("Unable to decode shell output", e);
return;
}
- if (buffer.indexOf(RUN_PROMPT_SUCCESS_MARKER) != -1) {
- delete(load(workspaceId));
+ if (buffer.indexOf(RUN_PROMPT_SUCCESS_MARKER) != -1) {
+ commandCompleted.set(true);
+ if (finalApplicableSpec.getTaskAutomation().isDeleteWorkspaceIfSucceeded())
+ delete(load(workspaceId));
+ } else if (buffer.indexOf(RUN_PROMPT_FAILURE_MARKER) != -1) {
+ commandCompleted.set(true);
+ taskFailedCallback.onTaskFailed(workspaceReference);
} else if (buffer.length() > 1024) {
buffer.delete(0, buffer.length() - 1024);
}
}
});
return true;
+ } else if (workspace.getStatus() == Workspace.Status.INACTIVE) {
+ taskFailedCallback.onTaskFailed(workspaceReference);
+ return true;
} else {
return false;
}
diff --git a/server-core/src/main/java/io/onedev/server/workspace/TaskFailedCallback.java b/server-core/src/main/java/io/onedev/server/workspace/TaskFailedCallback.java
new file mode 100644
index 0000000000..143e61c080
--- /dev/null
+++ b/server-core/src/main/java/io/onedev/server/workspace/TaskFailedCallback.java
@@ -0,0 +1,9 @@
+package io.onedev.server.workspace;
+
+import java.io.Serializable;
+
+public interface TaskFailedCallback extends Serializable {
+
+ void onTaskFailed(String workspaceReference);
+
+}
\ No newline at end of file
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 133bc0a1e4..ebd7479bdd 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
@@ -68,7 +68,6 @@ public interface WorkspaceService extends EntityService<Workspace> {
void onMessage(Workspace workspace, String shellId, String message);
-
@Nullable
WorkspaceContext getWorkspaceContext(String token, boolean mustExist);
@@ -77,6 +76,6 @@ public interface WorkspaceService extends EntityService<Workspace> {
@Nullable
FileData readFileData(Workspace workspace, String path);
- void runPrompt(User ai, Project project, String branch, String prompt);
+ void runPrompt(User ai, Project project, String branch, String prompt, TaskFailedCallback taskFailedCallback);
}