Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: add notification for task status#19965

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
ssncferreira merged 9 commits intomainfromssncferreira/feat-tasks-notifications
Sep 29, 2025
Merged
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 166 additions & 0 deletionscoderd/aitasks_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
package coderd_test

import (
"database/sql"
"fmt"
"io"
"net/http"
Expand All@@ -17,8 +18,12 @@ import (
"github.com/coder/coder/v2/coderd/coderdtest"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbauthz"
"github.com/coder/coder/v2/coderd/database/dbfake"
"github.com/coder/coder/v2/coderd/database/dbgen"
"github.com/coder/coder/v2/coderd/database/dbtestutil"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/coderd/notifications"
"github.com/coder/coder/v2/coderd/notifications/notificationstest"
"github.com/coder/coder/v2/coderd/util/slice"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/agentsdk"
Expand DownExpand Up@@ -961,3 +966,164 @@ func TestTasksCreate(t *testing.T) {
assert.Equal(t, http.StatusNotFound, sdkErr.StatusCode())
})
}

func TestTasksNotification(t *testing.T) {
t.Parallel()

for _, tc := range []struct {
name string
latestAppStatuses []codersdk.WorkspaceAppStatusState
newAppStatus codersdk.WorkspaceAppStatusState
isAITask bool
isNotificationSent bool
notificationTemplate uuid.UUID
}{
// Should not send a notification when the agent app is not an AI task.
{
name: "NoAITask",
latestAppStatuses: nil,
newAppStatus: codersdk.WorkspaceAppStatusStateWorking,
isAITask: false,
isNotificationSent: false,
},
// Should not send a notification when the new app status is neither 'Working' nor 'Idle'.
{
name: "NonNotifiedState",
latestAppStatuses: nil,
newAppStatus: codersdk.WorkspaceAppStatusStateComplete,
isAITask: true,
isNotificationSent: false,
},
// Should not send a notification when the new app status equals the latest status (Working).
{
name: "NonNotifiedTransition",
latestAppStatuses: []codersdk.WorkspaceAppStatusState{codersdk.WorkspaceAppStatusStateWorking},
newAppStatus: codersdk.WorkspaceAppStatusStateWorking,
isAITask: true,
isNotificationSent: false,
},
// Should send TemplateTaskWorking when the AI task transitions to 'Working'.
{
name: "TemplateTaskWorking",
latestAppStatuses: nil,
newAppStatus: codersdk.WorkspaceAppStatusStateWorking,
isAITask: true,
isNotificationSent: true,
notificationTemplate: notifications.TemplateTaskWorking,
},
// Should send TemplateTaskWorking when the AI task transitions to 'Working' from 'Idle'.
{
name: "TemplateTaskWorkingFromIdle",
latestAppStatuses: []codersdk.WorkspaceAppStatusState{
codersdk.WorkspaceAppStatusStateWorking,
codersdk.WorkspaceAppStatusStateIdle,
}, // latest
newAppStatus: codersdk.WorkspaceAppStatusStateWorking,
isAITask: true,
isNotificationSent: true,
notificationTemplate: notifications.TemplateTaskWorking,
},
// Should send TemplateTaskIdle when the AI task transitions to 'Idle'.
{
name: "TemplateTaskIdle",
latestAppStatuses: []codersdk.WorkspaceAppStatusState{codersdk.WorkspaceAppStatusStateWorking},
newAppStatus: codersdk.WorkspaceAppStatusStateIdle,
isAITask: true,
isNotificationSent: true,
notificationTemplate: notifications.TemplateTaskIdle,
},
} {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()

ctx := testutil.Context(t, testutil.WaitShort)
notifyEnq := &notificationstest.FakeEnqueuer{}
client, db := coderdtest.NewWithDatabase(t, &coderdtest.Options{
DeploymentValues: coderdtest.DeploymentValues(t),
NotificationsEnqueuer: notifyEnq,
})

// Given: a member user
ownerUser := coderdtest.CreateFirstUser(t, client)
client, memberUser := coderdtest.CreateAnotherUser(t, client, ownerUser.OrganizationID)

// Given: a workspace build with an agent containing an App
workspaceAgentAppID := uuid.New()
workspaceBuildID := uuid.New()
workspaceBuildSeed := database.WorkspaceBuild{
ID: workspaceBuildID,
}
if tc.isAITask {
workspaceBuildSeed = database.WorkspaceBuild{
ID: workspaceBuildID,
// AI Task configuration
HasAITask: sql.NullBool{Bool: true, Valid: true},
AITaskSidebarAppID: uuid.NullUUID{UUID: workspaceAgentAppID, Valid: true},
}
}
workspaceBuild := dbfake.WorkspaceBuild(t, db, database.WorkspaceTable{
OrganizationID: ownerUser.OrganizationID,
OwnerID: memberUser.ID,
}).Seed(workspaceBuildSeed).Params(database.WorkspaceBuildParameter{
WorkspaceBuildID: workspaceBuildID,
Name: codersdk.AITaskPromptParameterName,
Value: "task prompt",
}).WithAgent(func(agent []*proto.Agent) []*proto.Agent {
agent[0].Apps = []*proto.App{{
Id: workspaceAgentAppID.String(),
Slug: "ccw",
}}
return agent
}).Do()

// Given: the workspace agent app has previous statuses
agentClient := agentsdk.New(client.URL, agentsdk.WithFixedToken(workspaceBuild.AgentToken))
if len(tc.latestAppStatuses) > 0 {
workspace := coderdtest.MustWorkspace(t, client, workspaceBuild.Workspace.ID)
for _, appStatus := range tc.latestAppStatuses {
dbgen.WorkspaceAppStatus(t, db, database.WorkspaceAppStatus{
WorkspaceID: workspaceBuild.Workspace.ID,
AgentID: workspace.LatestBuild.Resources[0].Agents[0].ID,
AppID: workspaceAgentAppID,
State: database.WorkspaceAppStatusState(appStatus),
})
}
}

// When: the agent updates the app status
err := agentClient.PatchAppStatus(ctx, agentsdk.PatchAppStatus{
AppSlug: "ccw",
Message: "testing",
URI: "https://example.com",
State: tc.newAppStatus,
})
require.NoError(t, err)

// Then: The workspace app status transitions successfully
workspace, err := client.Workspace(ctx, workspaceBuild.Workspace.ID)
require.NoError(t, err)
workspaceAgent, err := client.WorkspaceAgent(ctx, workspace.LatestBuild.Resources[0].Agents[0].ID)
require.NoError(t, err)
require.Len(t, workspaceAgent.Apps, 1)
require.GreaterOrEqual(t, len(workspaceAgent.Apps[0].Statuses), 1)
latestStatusIndex := len(workspaceAgent.Apps[0].Statuses) - 1
require.Equal(t, tc.newAppStatus, workspaceAgent.Apps[0].Statuses[latestStatusIndex].State)

if tc.isNotificationSent {
// Then: A notification is sent to the workspace owner (memberUser)
sent := notifyEnq.Sent(notificationstest.WithTemplateID(tc.notificationTemplate))
require.Len(t, sent, 1)
require.Equal(t, memberUser.ID, sent[0].UserID)
require.Len(t, sent[0].Labels, 2)
require.Equal(t, "task prompt", sent[0].Labels["task"])
require.Equal(t, workspace.Name, sent[0].Labels["workspace"])
} else {
// Then: No notification is sent
sentWorking := notifyEnq.Sent(notificationstest.WithTemplateID(notifications.TemplateTaskWorking))
sentIdle := notifyEnq.Sent(notificationstest.WithTemplateID(notifications.TemplateTaskIdle))
require.Len(t, sentWorking, 0)
require.Len(t, sentIdle, 0)
}
})
}
}
7 changes: 7 additions & 0 deletionscoderd/database/dbauthz/dbauthz.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2313,6 +2313,13 @@ func (q *querier) GetLatestCryptoKeyByFeature(ctx context.Context, feature datab
return q.db.GetLatestCryptoKeyByFeature(ctx, feature)
}

func (q *querier) GetLatestWorkspaceAppStatusesByAppID(ctx context.Context, appID uuid.UUID) ([]database.WorkspaceAppStatus, error) {
if err := q.authorizeContext(ctx, policy.ActionRead, rbac.ResourceSystem); err != nil {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I realize the other functions around here do the same but I think we were wanting to stop introducing more uses ofResourceSystem

ssncferreira reacted with eyes emoji
Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

AFAIK, there isn’t a dedicated resource for workspace apps, so operations on them currently authorize againstrbac.ResourceSystem. I’m not sure what the best alternative is, skipping the authorization check would make this data accessible to anyone, which we don’t want.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

This is unfortunately a pre-existing issue from the introduction of app statuses. It may be worth addressing in a follow-up.

return nil, err
}
return q.db.GetLatestWorkspaceAppStatusesByAppID(ctx, appID)
}

func (q *querier) GetLatestWorkspaceAppStatusesByWorkspaceIDs(ctx context.Context, ids []uuid.UUID) ([]database.WorkspaceAppStatus, error) {
if err := q.authorizeContext(ctx, policy.ActionRead, rbac.ResourceSystem); err != nil {
return nil, err
Expand Down
5 changes: 5 additions & 0 deletionscoderd/database/dbauthz/dbauthz_test.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -2683,6 +2683,11 @@ func (s *MethodTestSuite) TestSystemFunctions() {
dbm.EXPECT().UpdateUserLinkedID(gomock.Any(), arg).Return(l, nil).AnyTimes()
check.Args(arg).Asserts(rbac.ResourceSystem, policy.ActionUpdate).Returns(l)
}))
s.Run("GetLatestWorkspaceAppStatusesByAppID", s.Mocked(func(dbm *dbmock.MockStore, _ *gofakeit.Faker, check *expects) {
appID := uuid.New()
dbm.EXPECT().GetLatestWorkspaceAppStatusesByAppID(gomock.Any(), appID).Return([]database.WorkspaceAppStatus{}, nil).AnyTimes()
check.Args(appID).Asserts(rbac.ResourceSystem, policy.ActionRead)
}))
s.Run("GetLatestWorkspaceAppStatusesByWorkspaceIDs", s.Mocked(func(dbm *dbmock.MockStore, _ *gofakeit.Faker, check *expects) {
ids := []uuid.UUID{uuid.New()}
dbm.EXPECT().GetLatestWorkspaceAppStatusesByWorkspaceIDs(gomock.Any(), ids).Return([]database.WorkspaceAppStatus{}, nil).AnyTimes()
Expand Down
15 changes: 15 additions & 0 deletionscoderd/database/dbgen/dbgen.go
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -905,6 +905,21 @@ func WorkspaceAppStat(t testing.TB, db database.Store, orig database.WorkspaceAp
return scheme
}

func WorkspaceAppStatus(t testing.TB, db database.Store, orig database.WorkspaceAppStatus) database.WorkspaceAppStatus {
appStatus, err := db.InsertWorkspaceAppStatus(genCtx, database.InsertWorkspaceAppStatusParams{
ID: takeFirst(orig.ID, uuid.New()),
CreatedAt: takeFirst(orig.CreatedAt, dbtime.Now()),
WorkspaceID: takeFirst(orig.WorkspaceID, uuid.New()),
AgentID: takeFirst(orig.AgentID, uuid.New()),
AppID: takeFirst(orig.AppID, uuid.New()),
State: takeFirst(orig.State, database.WorkspaceAppStatusStateWorking),
Message: takeFirst(orig.Message, ""),
Uri: takeFirst(orig.Uri, sql.NullString{}),
})
require.NoError(t, err, "insert workspace agent status")
return appStatus
}

func WorkspaceResource(t testing.TB, db database.Store, orig database.WorkspaceResource) database.WorkspaceResource {
resource, err := db.InsertWorkspaceResource(genCtx, database.InsertWorkspaceResourceParams{
ID: takeFirst(orig.ID, uuid.New()),
Expand Down
7 changes: 7 additions & 0 deletionscoderd/database/dbmetrics/querymetrics.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

15 changes: 15 additions & 0 deletionscoderd/database/dbmock/dbmock.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

View file
Open in desktop
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

Obligatory reminder to check migration number before merge!

ssncferreira reacted with thumbs up emoji
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
-- Remove Task 'working' transition template notification
DELETEFROM notification_templatesWHERE id='bd4b7168-d05e-4e19-ad0f-3593b77aa90f';
-- Remove Task 'idle' transition template notification
DELETEFROM notification_templatesWHERE id='d4a6271c-cced-4ed0-84ad-afd02a9c7799';
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
-- Task transition to 'working' status
INSERT INTO notification_templates (
id,
name,
title_template,
body_template,
actions,
"group",
method,
kind,
enabled_by_default
) VALUES (
'bd4b7168-d05e-4e19-ad0f-3593b77aa90f',
'Task Working',
Copy link
ContributorAuthor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others.Learn more.

I kept the terminology aligned with the current workspace agent app status (Working,Idle). In PR:https://github.com/coder/coder/pull/19773/files#diff-1894d4f2ccb1125739e504fc6d8d3a7daeec9dd829a81c342cf28f3e92efbf58R2-R7 I see the task status types differ. Is that finalized? If yes, should I update this PR to adopt the new task status terms?

E'Task ''{{.Labels.workspace}}'' is working',
E'The task ''{{.Labels.task}}'' transitioned to a working state.',
'[
{
"label": "View task",
"url": "{{base_url}}/tasks/{{.UserUsername}}/{{.Labels.workspace}}"
},
{
"label": "View workspace",
"url": "{{base_url}}/@{{.UserUsername}}/{{.Labels.workspace}}"
}
]'::jsonb,
'Task Events',
NULL,
'system'::notification_template_kind,
true
);

-- Task transition to 'idle' status
INSERT INTO notification_templates (
id,
name,
title_template,
body_template,
actions,
"group",
method,
kind,
enabled_by_default
) VALUES (
'd4a6271c-cced-4ed0-84ad-afd02a9c7799',
'Task Idle',
E'Task ''{{.Labels.workspace}}'' is idle',
E'The task ''{{.Labels.task}}'' is idle and ready for input.',
'[
{
"label": "View task",
"url": "{{base_url}}/tasks/{{.UserUsername}}/{{.Labels.workspace}}"
},
{
"label": "View workspace",
"url": "{{base_url}}/@{{.UserUsername}}/{{.Labels.workspace}}"
}
]'::jsonb,
'Task Events',
NULL,
'system'::notification_template_kind,
true
);
1 change: 1 addition & 0 deletionscoderd/database/querier.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

39 changes: 39 additions & 0 deletionscoderd/database/queries.sql.go
View file
Open in desktop

Some generated files are not rendered by default. Learn more abouthow customized files appear on GitHub.

Loading
Loading

[8]ページ先頭

©2009-2025 Movatter.jp