Skip to content

feat: allow tagging in incident comments #4669

New issue

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

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
wants to merge 7 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")
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""empty message
Revision ID: eeae12935acd
Revises: add_incident_comments, 7b687c555318
Create Date: 2025-05-12 12:44:15.300078
"""

import sqlalchemy as sa
import sqlalchemy_utils
import sqlmodel
from alembic import op

# revision identifiers, used by Alembic.
revision = "eeae12935acd"
down_revision = ("add_incident_comments", "7b687c555318")
branch_labels = None
depends_on = None


def upgrade() -> None:
pass


def downgrade() -> None:
pass
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
Loading