Skip to content

feat: allow tagging in incident comments #4669

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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
74 changes: 74 additions & 0 deletions keep-ui/app/(keep)/incidents/[id]/activity/ui/CommentInput.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { User } from "@/entities/users/model/types";
import dynamic from "next/dynamic";
import "react-quill-new/dist/quill.snow.css";
import { useCallback, useMemo } from "react";

const ReactQuill = dynamic(() => import("react-quill-new"), { ssr: false });

interface CommentInputProps {
value: string;
onValueChange: (value: string) => void;
users: User[];
placeholder?: string;
}

export function CommentInput({
value,
onValueChange,
users,
placeholder = "Add a new comment... Use @ to mention users",
}: CommentInputProps) {
const commentSuggestions = useMemo(() => {
return users.map((user) => ({
id: user.email,
value: user.name || user.email,
}));
}, [users]);

const modules = useMemo(
() => ({
toolbar: [
["bold", "italic", "underline"],
[{ list: "ordered" }, { list: "bullet" }],
["link"],
],
mention: {
allowedChars: /^[A-Za-z\sÅÄÖΓ₯Àâ]*$/,
mentionDenotationChars: ["@"],
source: function (searchTerm: string, renderList: Function) {
const matches = commentSuggestions.filter((item) =>
item.value.toLowerCase().includes(searchTerm.toLowerCase())
);
renderList(matches, searchTerm);
},
renderItem: function (item: any) {
return `${item.value} <${item.id}>`;
},
},
}),
[commentSuggestions]
);

const formats = ["bold", "italic", "underline", "list", "bullet", "link", "mention"];

const handleChange = useCallback(
(content: string) => {
onValueChange(content);
},
[onValueChange]
);

return (
<div className="w-full">
<ReactQuill
theme="snow"
value={value}
onChange={handleChange}
modules={modules}
formats={formats}
placeholder={placeholder}
className="border border-tremor-border rounded-tremor-default shadow-tremor-input"
/>
</div>
);
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { IncidentDto } from "@/entities/incidents/model";
import { TextInput, Button } from "@tremor/react";
import { Button } from "@tremor/react";
import { useState, useCallback, useEffect } from "react";
import { toast } from "react-toastify";
import { KeyedMutator } from "swr";
import { useApi } from "@/shared/lib/hooks/useApi";
import { showErrorToast } from "@/shared/ui";
import { AuditEvent } from "@/entities/alerts/model";
import { useUsers } from "@/entities/users/model/useUsers";
import { CommentInput } from "./CommentInput";

export function IncidentActivityComment({
incident,
Expand All @@ -16,12 +18,19 @@ export function IncidentActivityComment({
}) {
const [comment, setComment] = useState("");
const api = useApi();
const { data: users = [] } = useUsers();

const onSubmit = useCallback(async () => {
try {
// Extract mentioned users from Quill-formatted comment
const mentionedUsers = (comment.match(/@[^>]+<([^>]+)>/g) || [])
.map(mention => mention.match(/<([^>]+)>/)?.[1])
.filter(Boolean) as string[];

await api.post(`/incidents/${incident.id}/comment`, {
status: incident.status,
comment,
mentioned_users: mentionedUsers,
});
toast.success("Comment added!", { position: "top-right" });
setComment("");
Expand Down Expand Up @@ -53,10 +62,11 @@ export function IncidentActivityComment({

return (
<div className="flex h-full w-full relative items-center">
<TextInput
<CommentInput
value={comment}
onValueChange={setComment}
placeholder="Add a new comment..."
users={users}
placeholder="Add a new comment... Use @ to mention users"
/>
<Button
color="orange"
Expand Down
8 changes: 8 additions & 0 deletions keep/api/models/comment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from typing import List
from pydantic import BaseModel
from keep.api.models.db.incident import IncidentStatus

class IncidentCommentDto(BaseModel):
status: IncidentStatus
comment: str
mentioned_users: List[str] = []
29 changes: 29 additions & 0 deletions keep/api/models/db/comment.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
from datetime import datetime
from typing import List
from uuid import UUID, uuid4

from sqlalchemy import Column, ForeignKey, Text
from sqlalchemy_utils import UUIDType
from sqlmodel import Field, JSON, SQLModel

from keep.api.models.db.incident import Incident, IncidentStatus


class IncidentComment(SQLModel, table=True):
"""Model for storing incident comments with mentioned users."""
id: UUID = Field(default_factory=uuid4, primary_key=True)
incident_id: UUID = Field(
sa_column=Column(
UUIDType(binary=False),
ForeignKey("incident.id", ondelete="CASCADE"),
index=True,
)
)
status: str = Field(sa_column=Column(Text, nullable=False))
comment: str = Field(sa_column=Column(Text, nullable=False))
mentioned_users: List[str] = Field(default=[], sa_column=Column(JSON))
created_at: datetime = Field(
default_factory=datetime.utcnow,
nullable=False,
)
created_by: str | None = Field(default=None)
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""Add incident comments table

Revision ID: add_incident_comments
Revises: 92f4f93f2140
Create Date: 2024-07-29 18:11:00.000000

"""
from typing import List

import sqlalchemy as sa
import sqlmodel
from alembic import op
from sqlalchemy.dialects.postgresql import ARRAY
from sqlalchemy_utils import UUIDType

# revision identifiers, used by Alembic.
revision = "add_incident_comments"
down_revision = "92f4f93f2140"
branch_labels = None
depends_on = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table(
"incident_comment",
sa.Column("id", UUIDType(binary=False), primary_key=True),
sa.Column("incident_id", UUIDType(binary=False), nullable=False),
sa.Column("status", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("comment", sa.Text(), nullable=False),
sa.Column(
"mentioned_users",
sa.JSON(),
nullable=False,
server_default=sa.text("'[]'"),
),
sa.Column(
"created_at",
sa.DateTime(timezone=True),
server_default=sa.text("CURRENT_TIMESTAMP"),
nullable=False,
),
sa.Column("created_by", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.ForeignKeyConstraint(
["incident_id"],
["incident.id"],
ondelete="CASCADE",
),
)
op.create_index(
op.f("ix_incident_comment_incident_id"),
"incident_comment",
["incident_id"],
unique=False,
)


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f("ix_incident_comment_incident_id"), table_name="incident_comment")
op.drop_table("incident_comment")
19 changes: 17 additions & 2 deletions keep/api/routes/incidents.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
from keep.identitymanager.identitymanagerfactory import IdentityManagerFactory
from keep.providers.providers_factory import ProvidersFactory
from keep.topologies.topologies_service import TopologiesService # noqa
from keep.api.models.comment import IncidentCommentDto

router = APIRouter()
logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -888,7 +889,7 @@ def change_incident_severity(
@router.post("/{incident_id}/comment", description="Add incident audit activity")
def add_comment(
incident_id: UUID,
change: IncidentStatusChangeDto,
change: IncidentCommentDto,
authenticated_entity: AuthenticatedEntity = Depends(
IdentityManagerFactory.get_auth_verifier(["write:incident"])
),
Expand All @@ -899,6 +900,7 @@ def add_comment(
"commenter": authenticated_entity.email,
"comment": change.comment,
"incident_id": str(incident_id),
"mentioned_users": change.mentioned_users,
}
logger.info("Adding comment to incident", extra=extra)
comment = add_audit(
Expand All @@ -910,11 +912,24 @@ def add_comment(
)

if pusher_client:
# Notify about the comment
pusher_client.trigger(
f"private-{authenticated_entity.tenant_id}", "incident-comment", {}
)

# Send notifications to mentioned users
for mentioned_user in change.mentioned_users:
pusher_client.trigger(
f"private-{authenticated_entity.tenant_id}-{mentioned_user}",
"user-mention",
{
"incident_id": str(incident_id),
"comment": change.comment,
"mentioned_by": authenticated_entity.email,
}
)

logger.info("Added comment to incident", extra=extra)
logger.info("Added comment to incident with mentions", extra=extra)
return comment


Expand Down
94 changes: 94 additions & 0 deletions tests/e2e_tests/incidents_alerts_tests/test_incident_comments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import time
from datetime import datetime

from playwright.sync_api import Page, expect

from tests.e2e_tests.incidents_alerts_tests.incidents_alerts_setup import (
KEEP_UI_URL,
KEEP_API_URL,
)
from tests.e2e_tests.test_end_to_end import init_e2e_test, setup_console_listener
from tests.e2e_tests.utils import get_token


def test_incident_comment_with_mentions(browser: Page):
"""Test adding comments with user mentions to incidents."""
log_entries = []
setup_console_listener(browser, log_entries)

# Initialize test and navigate to incidents page
init_e2e_test(browser, next_url="/incidents")

# Create a test incident first
browser.locator("[data-testid='create-incident-button']").click()
browser.locator("[data-testid='incident-name-input']").fill("Test Incident for Comments")
browser.locator("[data-testid='incident-summary-input']").fill("Testing comment functionality with user mentions")
browser.locator("[data-testid='create-incident-submit']").click()

# Wait for incident to be created and navigate to its details
browser.wait_for_selector("table[data-testid='incidents-table'] tbody tr", timeout=5000)
browser.locator("table[data-testid='incidents-table'] tbody tr").first.click()

# Add a comment with user mentions
browser.locator("[data-testid='add-comment-button']").click()
comment_input = browser.locator("[data-testid='comment-input']")
comment_input.fill("Hey @Rohit.dash and @Oz.rooh, please take a look at this incident")

# Verify mention suggestions appear
browser.wait_for_selector("[data-testid='mention-suggestions']")
expect(browser.locator("[data-testid='mention-suggestions']")).to_be_visible()

# Submit the comment
browser.locator("[data-testid='submit-comment-button']").click()

# Verify the comment appears with proper mention formatting
comment_element = browser.locator("[data-testid='incident-comment']").first
expect(comment_element).to_contain_text("@rohit.dash")
expect(comment_element).to_contain_text("@oz.rooh")

# Verify mentioned users are highlighted
mentioned_users = browser.locator("[data-testid='mentioned-user']")
expect(mentioned_users).to_have_count(2)
expect(mentioned_users.first).to_have_class("mentioned-user")

# Verify notification creation
notifications_url = f"{KEEP_API_URL}/notifications"
notifications_response = browser.request.get(notifications_url)
expect(notifications_response).to_be_ok()
notifications = notifications_response.json()
mentioned_emails = ["[email protected]", "[email protected]"]
assert any(n["recipient"] in mentioned_emails and "mention" in n["type"] for n in notifications), "Missing mention notifications"

# Verify workflow execution
workflow_executions_url = f"{KEEP_API_URL}/workflows/executions"
executions_response = browser.request.get(workflow_executions_url)
expect(executions_response).to_be_ok()
executions = executions_response.json()
assert any(e["workflow_id"] == "user-mention-notification" and e["status"] == "success" for e in executions), "Missing workflow execution"

# Test editing a comment with mentions
browser.locator("[data-testid='edit-comment-button']").first.click()
edit_input = browser.locator("[data-testid='edit-comment-input']")
edit_input.fill("Updated: @rohit.dash please check this ASAP")
browser.locator("[data-testid='save-comment-button']").click()

# Verify the edited comment
updated_comment = browser.locator("[data-testid='incident-comment']").first
expect(updated_comment).to_contain_text("Updated:")
expect(updated_comment).to_contain_text("@rohit.dash")
expect(updated_comment).not_to_contain_text("@oz.rooh")

# Test comment with status change
browser.locator("[data-testid='add-comment-button']").click()
comment_input = browser.locator("[data-testid='comment-input']")
comment_input.fill("@oz.rooh I'm acknowledging this incident")
browser.locator("[data-testid='comment-status-select']").select_option("acknowledged")
browser.locator("[data-testid='submit-comment-button']").click()

# Verify status change comment
status_comment = browser.locator("[data-testid='incident-comment']").first
expect(status_comment).to_contain_text("acknowledged")
expect(status_comment).to_contain_text("@oz.rooh")

# Verify incident status updated
expect(browser.locator("[data-testid='incident-status']")).to_have_text("acknowledged")
Loading