merge: resolve conflicts with main (reactions feature)
Main added reaction routes and event types while this branch added task message routes and event types. Both sides kept — no code lost.
This commit is contained in:
commit
e20e1b74dc
40 changed files with 1596 additions and 76 deletions
|
|
@ -25,10 +25,13 @@ import {
|
|||
MoreHorizontal,
|
||||
Play,
|
||||
ChevronDown,
|
||||
Globe,
|
||||
Lock,
|
||||
} from "lucide-react";
|
||||
import type {
|
||||
Agent,
|
||||
AgentStatus,
|
||||
AgentVisibility,
|
||||
AgentTool,
|
||||
AgentTrigger,
|
||||
AgentTriggerType,
|
||||
|
|
@ -126,6 +129,7 @@ function CreateAgentDialog({
|
|||
const [name, setName] = useState("");
|
||||
const [description, setDescription] = useState("");
|
||||
const [selectedRuntimeId, setSelectedRuntimeId] = useState(runtimes[0]?.id ?? "");
|
||||
const [visibility, setVisibility] = useState<AgentVisibility>("private");
|
||||
const [creating, setCreating] = useState(false);
|
||||
const [runtimeOpen, setRuntimeOpen] = useState(false);
|
||||
|
||||
|
|
@ -145,6 +149,7 @@ function CreateAgentDialog({
|
|||
name: name.trim(),
|
||||
description: description.trim(),
|
||||
runtime_id: selectedRuntime.id,
|
||||
visibility,
|
||||
triggers: [{ id: generateId(), type: "on_assign", enabled: true, config: {} }],
|
||||
});
|
||||
onClose();
|
||||
|
|
@ -189,6 +194,42 @@ function CreateAgentDialog({
|
|||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground">Visibility</Label>
|
||||
<div className="mt-1.5 flex gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setVisibility("workspace")}
|
||||
className={`flex flex-1 items-center gap-2 rounded-lg border px-3 py-2.5 text-sm transition-colors ${
|
||||
visibility === "workspace"
|
||||
? "border-primary bg-primary/5"
|
||||
: "border-border hover:bg-muted"
|
||||
}`}
|
||||
>
|
||||
<Globe className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
<div className="text-left">
|
||||
<div className="font-medium">Workspace</div>
|
||||
<div className="text-xs text-muted-foreground">All members can assign</div>
|
||||
</div>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setVisibility("private")}
|
||||
className={`flex flex-1 items-center gap-2 rounded-lg border px-3 py-2.5 text-sm transition-colors ${
|
||||
visibility === "private"
|
||||
? "border-primary bg-primary/5"
|
||||
: "border-border hover:bg-muted"
|
||||
}`}
|
||||
>
|
||||
<Lock className="h-4 w-4 shrink-0 text-muted-foreground" />
|
||||
<div className="text-left">
|
||||
<div className="font-medium">Private</div>
|
||||
<div className="text-xs text-muted-foreground">Only you can assign</div>
|
||||
</div>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<Label className="text-xs text-muted-foreground">Runtime</Label>
|
||||
<Popover open={runtimeOpen} onOpenChange={setRuntimeOpen}>
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ const typeLabels: Record<InboxItemType, string> = {
|
|||
task_failed: "Task failed",
|
||||
agent_blocked: "Agent blocked",
|
||||
agent_completed: "Agent completed",
|
||||
reaction_added: "Reacted",
|
||||
};
|
||||
|
||||
function timeAgo(dateStr: string): string {
|
||||
|
|
@ -126,6 +127,11 @@ function InboxDetailLabel({ item }: { item: InboxItem }) {
|
|||
if (item.body) return <span>{item.body}</span>;
|
||||
return <span>{typeLabels[item.type]}</span>;
|
||||
}
|
||||
case "reaction_added": {
|
||||
const emoji = details.emoji;
|
||||
if (emoji) return <span>Reacted {emoji} to your comment</span>;
|
||||
return <span>{typeLabels[item.type]}</span>;
|
||||
}
|
||||
default:
|
||||
return <span>{typeLabels[item.type] ?? item.type}</span>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -291,6 +291,7 @@ describe("IssueDetailPage", () => {
|
|||
author_type: "member",
|
||||
author_id: "user-1",
|
||||
parent_id: null,
|
||||
reactions: [],
|
||||
created_at: "2026-01-18T00:00:00Z",
|
||||
updated_at: "2026-01-18T00:00:00Z",
|
||||
};
|
||||
|
|
|
|||
42
apps/web/components/common/emoji-picker.tsx
Normal file
42
apps/web/components/common/emoji-picker.tsx
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
"use client";
|
||||
|
||||
import { useEffect, useRef, useCallback } from "react";
|
||||
import data from "@emoji-mart/data";
|
||||
import { Picker } from "emoji-mart";
|
||||
|
||||
interface EmojiPickerProps {
|
||||
onSelect: (emoji: string) => void;
|
||||
}
|
||||
|
||||
export function EmojiPicker({ onSelect }: EmojiPickerProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null);
|
||||
const onSelectRef = useRef(onSelect);
|
||||
onSelectRef.current = onSelect;
|
||||
|
||||
const handleSelect = useCallback((emoji: { native: string }) => {
|
||||
onSelectRef.current(emoji.native);
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const container = containerRef.current;
|
||||
if (!container) return;
|
||||
|
||||
const picker = new Picker({
|
||||
data,
|
||||
onEmojiSelect: handleSelect,
|
||||
theme: "auto",
|
||||
set: "native",
|
||||
previewPosition: "none",
|
||||
skinTonePosition: "search",
|
||||
maxFrequentRows: 2,
|
||||
});
|
||||
|
||||
container.appendChild(picker as unknown as Node);
|
||||
|
||||
return () => {
|
||||
container.replaceChildren();
|
||||
};
|
||||
}, [handleSelect]);
|
||||
|
||||
return <div ref={containerRef} />;
|
||||
}
|
||||
144
apps/web/components/common/reaction-bar.tsx
Normal file
144
apps/web/components/common/reaction-bar.tsx
Normal file
|
|
@ -0,0 +1,144 @@
|
|||
"use client";
|
||||
|
||||
import { useState, lazy, Suspense } from "react";
|
||||
import { SmilePlus } from "lucide-react";
|
||||
import { Popover, PopoverTrigger, PopoverContent } from "@/components/ui/popover";
|
||||
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
|
||||
import { useActorName } from "@/features/workspace";
|
||||
|
||||
const EmojiPicker = lazy(() =>
|
||||
import("@/components/common/emoji-picker").then((m) => ({ default: m.EmojiPicker })),
|
||||
);
|
||||
|
||||
const QUICK_EMOJIS = ["👍", "👎", "❤️", "😄", "🎉", "😕", "🚀", "👀"];
|
||||
|
||||
interface ReactionItem {
|
||||
id: string;
|
||||
actor_type: string;
|
||||
actor_id: string;
|
||||
emoji: string;
|
||||
}
|
||||
|
||||
interface GroupedReaction {
|
||||
emoji: string;
|
||||
count: number;
|
||||
reacted: boolean;
|
||||
actors: { type: string; id: string }[];
|
||||
}
|
||||
|
||||
function groupReactions(reactions: ReactionItem[], currentUserId?: string): GroupedReaction[] {
|
||||
const map = new Map<string, GroupedReaction>();
|
||||
for (const r of reactions) {
|
||||
let group = map.get(r.emoji);
|
||||
if (!group) {
|
||||
group = { emoji: r.emoji, count: 0, reacted: false, actors: [] };
|
||||
map.set(r.emoji, group);
|
||||
}
|
||||
group.count++;
|
||||
group.actors.push({ type: r.actor_type, id: r.actor_id });
|
||||
if (r.actor_type === "member" && r.actor_id === currentUserId) {
|
||||
group.reacted = true;
|
||||
}
|
||||
}
|
||||
return Array.from(map.values());
|
||||
}
|
||||
|
||||
export function ReactionBar({
|
||||
reactions,
|
||||
currentUserId,
|
||||
onToggle,
|
||||
className,
|
||||
}: {
|
||||
reactions: ReactionItem[];
|
||||
currentUserId?: string;
|
||||
onToggle: (emoji: string) => void;
|
||||
className?: string;
|
||||
}) {
|
||||
const [pickerOpen, setPickerOpen] = useState(false);
|
||||
const [showFullPicker, setShowFullPicker] = useState(false);
|
||||
const grouped = groupReactions(reactions, currentUserId);
|
||||
const { getActorName } = useActorName();
|
||||
|
||||
const handlePickerOpenChange = (open: boolean) => {
|
||||
setPickerOpen(open);
|
||||
if (!open) setShowFullPicker(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className={`flex flex-wrap items-center gap-1.5 ${className ?? ""}`}>
|
||||
{grouped.map((g) => (
|
||||
<Tooltip key={g.emoji}>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onToggle(g.emoji)}
|
||||
className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-xs transition-colors hover:bg-accent ${
|
||||
g.reacted
|
||||
? "border-primary/40 bg-primary/10 text-primary"
|
||||
: "border-border text-muted-foreground"
|
||||
}`}
|
||||
>
|
||||
<span>{g.emoji}</span>
|
||||
<span>{g.count}</span>
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<TooltipContent side="top">
|
||||
{g.actors.map((a) => getActorName(a.type, a.id)).join(", ")}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
))}
|
||||
<Popover open={pickerOpen} onOpenChange={handlePickerOpenChange}>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<button
|
||||
type="button"
|
||||
className="inline-flex items-center justify-center h-6 w-6 rounded-full text-muted-foreground hover:bg-accent hover:text-foreground transition-colors"
|
||||
>
|
||||
<SmilePlus className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
}
|
||||
/>
|
||||
<PopoverContent align="start" className="w-auto p-0">
|
||||
{showFullPicker ? (
|
||||
<Suspense fallback={<div className="p-4 text-sm text-muted-foreground">Loading...</div>}>
|
||||
<EmojiPicker
|
||||
onSelect={(emoji) => {
|
||||
onToggle(emoji);
|
||||
setPickerOpen(false);
|
||||
setShowFullPicker(false);
|
||||
}}
|
||||
/>
|
||||
</Suspense>
|
||||
) : (
|
||||
<div className="p-2">
|
||||
<div className="flex gap-1">
|
||||
{QUICK_EMOJIS.map((emoji) => (
|
||||
<button
|
||||
key={emoji}
|
||||
type="button"
|
||||
onClick={() => {
|
||||
onToggle(emoji);
|
||||
setPickerOpen(false);
|
||||
}}
|
||||
className="h-8 w-8 flex items-center justify-center rounded hover:bg-accent text-base transition-colors"
|
||||
>
|
||||
{emoji}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowFullPicker(true)}
|
||||
className="mt-1.5 w-full text-xs text-muted-foreground hover:text-foreground text-center py-1 rounded hover:bg-accent transition-colors"
|
||||
>
|
||||
More emojis...
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -14,6 +14,7 @@ import {
|
|||
} from "@/components/ui/dropdown-menu";
|
||||
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
|
||||
import { ActorAvatar } from "@/components/common/actor-avatar";
|
||||
import { ReactionBar } from "@/components/common/reaction-bar";
|
||||
import { Markdown } from "@/components/markdown";
|
||||
import { useActorName } from "@/features/workspace";
|
||||
import { timeAgo } from "@/shared/utils";
|
||||
|
|
@ -31,6 +32,7 @@ interface CommentCardProps {
|
|||
onReply: (parentId: string, content: string) => Promise<void>;
|
||||
onEdit: (commentId: string, content: string) => Promise<void>;
|
||||
onDelete: (commentId: string) => void;
|
||||
onToggleReaction: (commentId: string, emoji: string) => void;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
@ -42,11 +44,13 @@ function CommentRow({
|
|||
currentUserId,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onToggleReaction,
|
||||
}: {
|
||||
entry: TimelineEntry;
|
||||
currentUserId?: string;
|
||||
onEdit: (commentId: string, content: string) => Promise<void>;
|
||||
onDelete: (commentId: string) => void;
|
||||
onToggleReaction: (commentId: string, emoji: string) => void;
|
||||
}) {
|
||||
const { getActorName } = useActorName();
|
||||
const [editing, setEditing] = useState(false);
|
||||
|
|
@ -77,6 +81,8 @@ function CommentRow({
|
|||
}
|
||||
};
|
||||
|
||||
const reactions = entry.reactions ?? [];
|
||||
|
||||
return (
|
||||
<div className={`py-3${isTemp ? " opacity-60" : ""}`}>
|
||||
<div className="flex items-center gap-2.5">
|
||||
|
|
@ -136,9 +142,19 @@ function CommentRow({
|
|||
</div>
|
||||
</form>
|
||||
) : (
|
||||
<div className="mt-1.5 pl-8 text-sm leading-relaxed text-foreground/85">
|
||||
<Markdown mode="minimal">{entry.content ?? ""}</Markdown>
|
||||
</div>
|
||||
<>
|
||||
<div className="mt-1.5 pl-8 text-sm leading-relaxed text-foreground/85">
|
||||
<Markdown mode="minimal">{entry.content ?? ""}</Markdown>
|
||||
</div>
|
||||
{!isTemp && (
|
||||
<ReactionBar
|
||||
reactions={reactions}
|
||||
currentUserId={currentUserId}
|
||||
onToggle={(emoji) => onToggleReaction(entry.id, emoji)}
|
||||
className="mt-1.5 pl-8"
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
|
@ -155,6 +171,7 @@ function CommentCard({
|
|||
onReply,
|
||||
onEdit,
|
||||
onDelete,
|
||||
onToggleReaction,
|
||||
}: CommentCardProps) {
|
||||
// Collect all nested replies recursively into a flat list
|
||||
const allNestedReplies: TimelineEntry[] = [];
|
||||
|
|
@ -176,6 +193,7 @@ function CommentCard({
|
|||
currentUserId={currentUserId}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
onToggleReaction={onToggleReaction}
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
|
@ -187,6 +205,7 @@ function CommentCard({
|
|||
currentUserId={currentUserId}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
onToggleReaction={onToggleReaction}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
|
|
|
|||
|
|
@ -55,7 +55,7 @@ import { Checkbox } from "@/components/ui/checkbox";
|
|||
import { Command, CommandInput, CommandList, CommandEmpty, CommandGroup, CommandItem } from "@/components/ui/command";
|
||||
import { Avatar, AvatarFallback, AvatarGroup, AvatarGroupCount } from "@/components/ui/avatar";
|
||||
import { ActorAvatar } from "@/components/common/actor-avatar";
|
||||
import type { Issue, Comment, IssueSubscriber, UpdateIssueRequest, IssueStatus, IssuePriority, TimelineEntry } from "@/shared/types";
|
||||
import type { Issue, IssueReaction, Comment, IssueSubscriber, UpdateIssueRequest, IssueStatus, IssuePriority, TimelineEntry } from "@/shared/types";
|
||||
import { ALL_STATUSES, STATUS_CONFIG, PRIORITY_ORDER, PRIORITY_CONFIG } from "@/features/issues/config";
|
||||
import { StatusIcon, PriorityIcon, DueDatePicker } from "@/features/issues/components";
|
||||
import { CommentCard } from "./comment-card";
|
||||
|
|
@ -66,7 +66,8 @@ import { useAuthStore } from "@/features/auth";
|
|||
import { useWorkspaceStore, useActorName } from "@/features/workspace";
|
||||
import { useWSEvent } from "@/features/realtime";
|
||||
import { useIssueStore } from "@/features/issues";
|
||||
import type { CommentCreatedPayload, CommentUpdatedPayload, CommentDeletedPayload, SubscriberAddedPayload, SubscriberRemovedPayload, ActivityCreatedPayload } from "@/shared/types";
|
||||
import type { CommentCreatedPayload, CommentUpdatedPayload, CommentDeletedPayload, SubscriberAddedPayload, SubscriberRemovedPayload, ActivityCreatedPayload, ReactionAddedPayload, ReactionRemovedPayload, IssueReactionAddedPayload, IssueReactionRemovedPayload } from "@/shared/types";
|
||||
import { ReactionBar } from "@/components/common/reaction-bar";
|
||||
import { timeAgo } from "@/shared/utils";
|
||||
|
||||
function shortDate(date: string | null): string {
|
||||
|
|
@ -136,6 +137,7 @@ function commentToTimelineEntry(c: Comment): TimelineEntry {
|
|||
created_at: c.created_at,
|
||||
updated_at: c.updated_at,
|
||||
comment_type: c.type,
|
||||
reactions: c.reactions ?? [],
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -196,6 +198,7 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
|
|||
const sidebarRef = usePanelRef();
|
||||
const [sidebarOpen, setSidebarOpen] = useState(defaultSidebarOpen);
|
||||
const [issue, setIssue] = useState<Issue | null>(null);
|
||||
const [issueReactions, setIssueReactions] = useState<IssueReaction[]>([]);
|
||||
const [timeline, setTimeline] = useState<TimelineEntry[]>([]);
|
||||
const [subscribers, setSubscribers] = useState<IssueSubscriber[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
|
@ -229,12 +232,14 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
|
|||
wasLoadedRef.current = false;
|
||||
setIssue(null);
|
||||
setTitleDraft("");
|
||||
setIssueReactions([]);
|
||||
setTimeline([]);
|
||||
setSubscribers([]);
|
||||
setLoading(true);
|
||||
Promise.all([api.getIssue(id), api.listTimeline(id), api.listIssueSubscribers(id)])
|
||||
.then(([iss, entries, subs]) => {
|
||||
setIssue(iss);
|
||||
setIssueReactions(iss.reactions ?? []);
|
||||
setTitleDraft(iss.title);
|
||||
setTimeline(entries);
|
||||
setSubscribers(subs);
|
||||
|
|
@ -431,6 +436,157 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
|
|||
}, [id]),
|
||||
);
|
||||
|
||||
// Real-time reaction updates
|
||||
useWSEvent(
|
||||
"reaction:added",
|
||||
useCallback((payload: unknown) => {
|
||||
const { reaction, issue_id } = payload as ReactionAddedPayload;
|
||||
if (issue_id !== id) return;
|
||||
// Skip own reactions — already added optimistically
|
||||
if (reaction.actor_type === "member" && reaction.actor_id === user?.id) return;
|
||||
setTimeline((prev) => prev.map((e) => {
|
||||
if (e.id !== reaction.comment_id) return e;
|
||||
const existing = e.reactions ?? [];
|
||||
if (existing.some((r) => r.id === reaction.id)) return e;
|
||||
return { ...e, reactions: [...existing, reaction] };
|
||||
}));
|
||||
}, [id, user?.id]),
|
||||
);
|
||||
|
||||
useWSEvent(
|
||||
"reaction:removed",
|
||||
useCallback((payload: unknown) => {
|
||||
const p = payload as ReactionRemovedPayload;
|
||||
if (p.issue_id !== id) return;
|
||||
// Skip own removals — already removed optimistically
|
||||
if (p.actor_type === "member" && p.actor_id === user?.id) return;
|
||||
setTimeline((prev) => prev.map((e) => {
|
||||
if (e.id !== p.comment_id) return e;
|
||||
return {
|
||||
...e,
|
||||
reactions: (e.reactions ?? []).filter(
|
||||
(r) => !(r.emoji === p.emoji && r.actor_type === p.actor_type && r.actor_id === p.actor_id),
|
||||
),
|
||||
};
|
||||
}));
|
||||
}, [id, user?.id]),
|
||||
);
|
||||
|
||||
// Real-time issue reaction updates
|
||||
useWSEvent(
|
||||
"issue_reaction:added",
|
||||
useCallback((payload: unknown) => {
|
||||
const { reaction, issue_id } = payload as IssueReactionAddedPayload;
|
||||
if (issue_id !== id) return;
|
||||
if (reaction.actor_type === "member" && reaction.actor_id === user?.id) return;
|
||||
setIssueReactions((prev) => {
|
||||
if (prev.some((r) => r.id === reaction.id)) return prev;
|
||||
return [...prev, reaction];
|
||||
});
|
||||
}, [id, user?.id]),
|
||||
);
|
||||
|
||||
useWSEvent(
|
||||
"issue_reaction:removed",
|
||||
useCallback((payload: unknown) => {
|
||||
const p = payload as IssueReactionRemovedPayload;
|
||||
if (p.issue_id !== id) return;
|
||||
if (p.actor_type === "member" && p.actor_id === user?.id) return;
|
||||
setIssueReactions((prev) =>
|
||||
prev.filter((r) => !(r.emoji === p.emoji && r.actor_type === p.actor_type && r.actor_id === p.actor_id)),
|
||||
);
|
||||
}, [id, user?.id]),
|
||||
);
|
||||
|
||||
const handleToggleIssueReaction = async (emoji: string) => {
|
||||
if (!user) return;
|
||||
const existing = issueReactions.find(
|
||||
(r) => r.emoji === emoji && r.actor_type === "member" && r.actor_id === user.id,
|
||||
);
|
||||
if (existing) {
|
||||
setIssueReactions((prev) => prev.filter((r) => r.id !== existing.id));
|
||||
try {
|
||||
await api.removeIssueReaction(id, emoji);
|
||||
} catch {
|
||||
setIssueReactions((prev) => [...prev, existing]);
|
||||
toast.error("Failed to remove reaction");
|
||||
}
|
||||
} else {
|
||||
const temp = {
|
||||
id: `temp-${Date.now()}`,
|
||||
issue_id: id,
|
||||
actor_type: "member",
|
||||
actor_id: user.id,
|
||||
emoji,
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
setIssueReactions((prev) => [...prev, temp]);
|
||||
try {
|
||||
const reaction = await api.addIssueReaction(id, emoji);
|
||||
setIssueReactions((prev) => prev.map((r) => (r.id === temp.id ? reaction : r)));
|
||||
} catch {
|
||||
setIssueReactions((prev) => prev.filter((r) => r.id !== temp.id));
|
||||
toast.error("Failed to add reaction");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleToggleReaction = async (commentId: string, emoji: string) => {
|
||||
if (!user) return;
|
||||
const entry = timeline.find((e) => e.id === commentId);
|
||||
const existing = (entry?.reactions ?? []).find(
|
||||
(r) => r.emoji === emoji && r.actor_type === "member" && r.actor_id === user.id,
|
||||
);
|
||||
if (existing) {
|
||||
// Optimistic remove
|
||||
setTimeline((prev) => prev.map((e) => {
|
||||
if (e.id !== commentId) return e;
|
||||
return { ...e, reactions: (e.reactions ?? []).filter((r) => r.id !== existing.id) };
|
||||
}));
|
||||
try {
|
||||
await api.removeReaction(commentId, emoji);
|
||||
} catch {
|
||||
// Rollback
|
||||
setTimeline((prev) => prev.map((e) => {
|
||||
if (e.id !== commentId) return e;
|
||||
return { ...e, reactions: [...(e.reactions ?? []), existing] };
|
||||
}));
|
||||
toast.error("Failed to remove reaction");
|
||||
}
|
||||
} else {
|
||||
// Optimistic add
|
||||
const tempReaction = {
|
||||
id: `temp-${Date.now()}`,
|
||||
comment_id: commentId,
|
||||
actor_type: "member",
|
||||
actor_id: user.id,
|
||||
emoji,
|
||||
created_at: new Date().toISOString(),
|
||||
};
|
||||
setTimeline((prev) => prev.map((e) => {
|
||||
if (e.id !== commentId) return e;
|
||||
return { ...e, reactions: [...(e.reactions ?? []), tempReaction] };
|
||||
}));
|
||||
try {
|
||||
const reaction = await api.addReaction(commentId, emoji);
|
||||
setTimeline((prev) => prev.map((e) => {
|
||||
if (e.id !== commentId) return e;
|
||||
return {
|
||||
...e,
|
||||
reactions: (e.reactions ?? []).map((r) => (r.id === tempReaction.id ? reaction : r)),
|
||||
};
|
||||
}));
|
||||
} catch {
|
||||
// Rollback
|
||||
setTimeline((prev) => prev.map((e) => {
|
||||
if (e.id !== commentId) return e;
|
||||
return { ...e, reactions: (e.reactions ?? []).filter((r) => r.id !== tempReaction.id) };
|
||||
}));
|
||||
toast.error("Failed to add reaction");
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Real-time subscriber updates
|
||||
useWSEvent(
|
||||
"subscriber:added",
|
||||
|
|
@ -771,6 +927,13 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
|
|||
className="mt-5"
|
||||
/>
|
||||
|
||||
<ReactionBar
|
||||
reactions={issueReactions}
|
||||
currentUserId={user?.id}
|
||||
onToggle={handleToggleIssueReaction}
|
||||
className="mt-3"
|
||||
/>
|
||||
|
||||
<div className="my-8 border-t" />
|
||||
|
||||
{/* Activity / Comments */}
|
||||
|
|
@ -933,6 +1096,7 @@ export function IssueDetail({ issueId, onDelete, defaultSidebarOpen = true, layo
|
|||
onReply={handleSubmitReply}
|
||||
onEdit={handleEditComment}
|
||||
onDelete={handleDeleteComment}
|
||||
onToggleReaction={handleToggleReaction}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Bot, UserMinus } from "lucide-react";
|
||||
import type { IssueAssigneeType, UpdateIssueRequest } from "@/shared/types";
|
||||
import { Bot, Lock, UserMinus } from "lucide-react";
|
||||
import type { Agent, IssueAssigneeType, UpdateIssueRequest } from "@/shared/types";
|
||||
import { useAuthStore } from "@/features/auth";
|
||||
import { useWorkspaceStore, useActorName } from "@/features/workspace";
|
||||
import {
|
||||
PropertyPicker,
|
||||
|
|
@ -11,6 +12,13 @@ import {
|
|||
PickerEmpty,
|
||||
} from "./property-picker";
|
||||
|
||||
function canAssignAgent(agent: Agent, userId: string | undefined, memberRole: string | undefined): boolean {
|
||||
if (agent.visibility !== "private") return true;
|
||||
if (agent.owner_id === userId) return true;
|
||||
if (memberRole === "owner" || memberRole === "admin") return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
export function AssigneePicker({
|
||||
assigneeType,
|
||||
assigneeId,
|
||||
|
|
@ -24,10 +32,14 @@ export function AssigneePicker({
|
|||
}) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [filter, setFilter] = useState("");
|
||||
const user = useAuthStore((s) => s.user);
|
||||
const members = useWorkspaceStore((s) => s.members);
|
||||
const agents = useWorkspaceStore((s) => s.agents);
|
||||
const { getActorName, getActorInitials } = useActorName();
|
||||
|
||||
const currentMember = members.find((m) => m.user_id === user?.id);
|
||||
const memberRole = currentMember?.role;
|
||||
|
||||
const query = filter.toLowerCase();
|
||||
const filteredMembers = members.filter((m) =>
|
||||
m.name.toLowerCase().includes(query),
|
||||
|
|
@ -117,24 +129,32 @@ export function AssigneePicker({
|
|||
{/* Agents */}
|
||||
{filteredAgents.length > 0 && (
|
||||
<PickerSection label="Agents">
|
||||
{filteredAgents.map((a) => (
|
||||
<PickerItem
|
||||
key={a.id}
|
||||
selected={isSelected("agent", a.id)}
|
||||
onClick={() => {
|
||||
onUpdate({
|
||||
assignee_type: "agent",
|
||||
assignee_id: a.id,
|
||||
});
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
<div className="inline-flex size-4.5 shrink-0 items-center justify-center rounded-full bg-info/10 text-info">
|
||||
<Bot className="size-2.5" />
|
||||
</div>
|
||||
<span>{a.name}</span>
|
||||
</PickerItem>
|
||||
))}
|
||||
{filteredAgents.map((a) => {
|
||||
const allowed = canAssignAgent(a, user?.id, memberRole);
|
||||
return (
|
||||
<PickerItem
|
||||
key={a.id}
|
||||
selected={isSelected("agent", a.id)}
|
||||
disabled={!allowed}
|
||||
onClick={() => {
|
||||
if (!allowed) return;
|
||||
onUpdate({
|
||||
assignee_type: "agent",
|
||||
assignee_id: a.id,
|
||||
});
|
||||
setOpen(false);
|
||||
}}
|
||||
>
|
||||
<div className={`inline-flex size-4.5 shrink-0 items-center justify-center rounded-full ${allowed ? "bg-info/10 text-info" : "bg-muted text-muted-foreground"}`}>
|
||||
<Bot className="size-2.5" />
|
||||
</div>
|
||||
<span className={allowed ? "" : "text-muted-foreground"}>{a.name}</span>
|
||||
{a.visibility === "private" && (
|
||||
<Lock className="ml-auto h-3 w-3 text-muted-foreground" />
|
||||
)}
|
||||
</PickerItem>
|
||||
);
|
||||
})}
|
||||
</PickerSection>
|
||||
)}
|
||||
|
||||
|
|
|
|||
|
|
@ -79,11 +79,13 @@ export function PropertyPicker({
|
|||
|
||||
export function PickerItem({
|
||||
selected,
|
||||
disabled,
|
||||
onClick,
|
||||
hoverClassName,
|
||||
children,
|
||||
}: {
|
||||
selected: boolean;
|
||||
disabled?: boolean;
|
||||
onClick: () => void;
|
||||
hoverClassName?: string;
|
||||
children: React.ReactNode;
|
||||
|
|
@ -91,8 +93,9 @@ export function PickerItem({
|
|||
return (
|
||||
<button
|
||||
type="button"
|
||||
disabled={disabled}
|
||||
onClick={onClick}
|
||||
className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm ${hoverClassName ?? "hover:bg-accent"} transition-colors`}
|
||||
className={`flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-sm ${disabled ? "opacity-50 cursor-not-allowed" : hoverClassName ?? "hover:bg-accent"} transition-colors`}
|
||||
>
|
||||
<span className="flex flex-1 items-center gap-2">{children}</span>
|
||||
{selected && <Check className="h-3.5 w-3.5 text-muted-foreground" />}
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@
|
|||
"@dnd-kit/core": "^6.3.1",
|
||||
"@dnd-kit/sortable": "^10.0.0",
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@emoji-mart/data": "^1.2.1",
|
||||
"@tiptap/extension-link": "^3.20.5",
|
||||
"@tiptap/extension-mention": "^3.20.5",
|
||||
"@tiptap/extension-placeholder": "^3.20.5",
|
||||
|
|
@ -29,6 +30,7 @@
|
|||
"cmdk": "^1.1.1",
|
||||
"date-fns": "^4.1.0",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
"emoji-mart": "^5.6.0",
|
||||
"input-otp": "^1.4.2",
|
||||
"linkify-it": "^5.0.0",
|
||||
"lucide-react": "catalog:",
|
||||
|
|
|
|||
|
|
@ -17,6 +17,8 @@ import type {
|
|||
InboxItem,
|
||||
IssueSubscriber,
|
||||
Comment,
|
||||
Reaction,
|
||||
IssueReaction,
|
||||
Workspace,
|
||||
WorkspaceRepo,
|
||||
MemberWithUser,
|
||||
|
|
@ -226,6 +228,34 @@ export class ApiClient {
|
|||
await this.fetch(`/api/comments/${commentId}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
async addReaction(commentId: string, emoji: string): Promise<Reaction> {
|
||||
return this.fetch(`/api/comments/${commentId}/reactions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ emoji }),
|
||||
});
|
||||
}
|
||||
|
||||
async removeReaction(commentId: string, emoji: string): Promise<void> {
|
||||
await this.fetch(`/api/comments/${commentId}/reactions`, {
|
||||
method: "DELETE",
|
||||
body: JSON.stringify({ emoji }),
|
||||
});
|
||||
}
|
||||
|
||||
async addIssueReaction(issueId: string, emoji: string): Promise<IssueReaction> {
|
||||
return this.fetch(`/api/issues/${issueId}/reactions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ emoji }),
|
||||
});
|
||||
}
|
||||
|
||||
async removeIssueReaction(issueId: string, emoji: string): Promise<void> {
|
||||
await this.fetch(`/api/issues/${issueId}/reactions`, {
|
||||
method: "DELETE",
|
||||
body: JSON.stringify({ emoji }),
|
||||
});
|
||||
}
|
||||
|
||||
// Subscribers
|
||||
async listIssueSubscribers(issueId: string): Promise<IssueSubscriber[]> {
|
||||
return this.fetch(`/api/issues/${issueId}/subscribers`);
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import type { Reaction } from "./comment";
|
||||
|
||||
export interface TimelineEntry {
|
||||
type: "activity" | "comment";
|
||||
id: string;
|
||||
|
|
@ -12,4 +14,5 @@ export interface TimelineEntry {
|
|||
parent_id?: string | null;
|
||||
updated_at?: string;
|
||||
comment_type?: string;
|
||||
reactions?: Reaction[];
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,6 +2,15 @@ export type CommentType = "comment" | "status_change" | "progress_update" | "sys
|
|||
|
||||
export type CommentAuthorType = "member" | "agent";
|
||||
|
||||
export interface Reaction {
|
||||
id: string;
|
||||
comment_id: string;
|
||||
actor_type: string;
|
||||
actor_id: string;
|
||||
emoji: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface Comment {
|
||||
id: string;
|
||||
issue_id: string;
|
||||
|
|
@ -10,6 +19,7 @@ export interface Comment {
|
|||
content: string;
|
||||
type: CommentType;
|
||||
parent_id: string | null;
|
||||
reactions: Reaction[];
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import type { Issue } from "./issue";
|
||||
import type { Issue, IssueReaction } from "./issue";
|
||||
import type { Agent } from "./agent";
|
||||
import type { InboxItem } from "./inbox";
|
||||
import type { Comment } from "./comment";
|
||||
import type { Comment, Reaction } from "./comment";
|
||||
import type { TimelineEntry } from "./activity";
|
||||
import type { Workspace, MemberWithUser } from "./workspace";
|
||||
|
||||
|
|
@ -38,7 +38,11 @@ export type WSEventType =
|
|||
| "skill:deleted"
|
||||
| "subscriber:added"
|
||||
| "subscriber:removed"
|
||||
| "activity:created";
|
||||
| "activity:created"
|
||||
| "reaction:added"
|
||||
| "reaction:removed"
|
||||
| "issue_reaction:added"
|
||||
| "issue_reaction:removed";
|
||||
|
||||
export interface WSMessage<T = unknown> {
|
||||
type: WSEventType;
|
||||
|
|
@ -173,3 +177,28 @@ export interface TaskFailedPayload {
|
|||
issue_id: string;
|
||||
status: string;
|
||||
}
|
||||
|
||||
export interface ReactionAddedPayload {
|
||||
reaction: Reaction;
|
||||
issue_id: string;
|
||||
}
|
||||
|
||||
export interface ReactionRemovedPayload {
|
||||
comment_id: string;
|
||||
issue_id: string;
|
||||
emoji: string;
|
||||
actor_type: string;
|
||||
actor_id: string;
|
||||
}
|
||||
|
||||
export interface IssueReactionAddedPayload {
|
||||
reaction: IssueReaction;
|
||||
issue_id: string;
|
||||
}
|
||||
|
||||
export interface IssueReactionRemovedPayload {
|
||||
issue_id: string;
|
||||
emoji: string;
|
||||
actor_type: string;
|
||||
actor_id: string;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -15,7 +15,8 @@ export type InboxItemType =
|
|||
| "task_completed"
|
||||
| "task_failed"
|
||||
| "agent_blocked"
|
||||
| "agent_completed";
|
||||
| "agent_completed"
|
||||
| "reaction_added";
|
||||
|
||||
export interface InboxItem {
|
||||
id: string;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
export type { Issue, IssueStatus, IssuePriority, IssueAssigneeType } from "./issue";
|
||||
export type { Issue, IssueStatus, IssuePriority, IssueAssigneeType, IssueReaction } from "./issue";
|
||||
export type {
|
||||
Agent,
|
||||
AgentStatus,
|
||||
|
|
@ -24,7 +24,7 @@ export type {
|
|||
} from "./agent";
|
||||
export type { Workspace, WorkspaceRepo, Member, MemberRole, User, MemberWithUser } from "./workspace";
|
||||
export type { InboxItem, InboxSeverity, InboxItemType } from "./inbox";
|
||||
export type { Comment, CommentType, CommentAuthorType } from "./comment";
|
||||
export type { Comment, CommentType, CommentAuthorType, Reaction } from "./comment";
|
||||
export type { TimelineEntry } from "./activity";
|
||||
export type { IssueSubscriber } from "./subscriber";
|
||||
export type { DaemonPairingSession, DaemonPairingSessionStatus, ApproveDaemonPairingSessionRequest } from "./daemon";
|
||||
|
|
|
|||
|
|
@ -11,6 +11,15 @@ export type IssuePriority = "urgent" | "high" | "medium" | "low" | "none";
|
|||
|
||||
export type IssueAssigneeType = "member" | "agent";
|
||||
|
||||
export interface IssueReaction {
|
||||
id: string;
|
||||
issue_id: string;
|
||||
actor_type: string;
|
||||
actor_id: string;
|
||||
emoji: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface Issue {
|
||||
id: string;
|
||||
workspace_id: string;
|
||||
|
|
@ -27,6 +36,7 @@ export interface Issue {
|
|||
parent_issue_id: string | null;
|
||||
position: number;
|
||||
due_date: string | null;
|
||||
reactions?: IssueReaction[];
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
|
|
|||
16
pnpm-lock.yaml
generated
16
pnpm-lock.yaml
generated
|
|
@ -69,6 +69,9 @@ importers:
|
|||
'@dnd-kit/utilities':
|
||||
specifier: ^3.2.2
|
||||
version: 3.2.2(react@19.2.3)
|
||||
'@emoji-mart/data':
|
||||
specifier: ^1.2.1
|
||||
version: 1.2.1
|
||||
'@tiptap/extension-link':
|
||||
specifier: ^3.20.5
|
||||
version: 3.20.5(@tiptap/core@3.20.5(@tiptap/pm@3.20.5))(@tiptap/pm@3.20.5)
|
||||
|
|
@ -108,6 +111,9 @@ importers:
|
|||
embla-carousel-react:
|
||||
specifier: ^8.6.0
|
||||
version: 8.6.0(react@19.2.3)
|
||||
emoji-mart:
|
||||
specifier: ^5.6.0
|
||||
version: 5.6.0
|
||||
input-otp:
|
||||
specifier: ^1.4.2
|
||||
version: 1.4.2(react-dom@19.2.3(react@19.2.3))(react@19.2.3)
|
||||
|
|
@ -464,6 +470,9 @@ packages:
|
|||
'@emnapi/wasi-threads@1.2.0':
|
||||
resolution: {integrity: sha512-N10dEJNSsUx41Z6pZsXU8FjPjpBEplgH24sfkmITrBED1/U2Esum9F3lfLrMjKHHjmi557zQn7kR9R+XWXu5Rg==}
|
||||
|
||||
'@emoji-mart/data@1.2.1':
|
||||
resolution: {integrity: sha512-no2pQMWiBy6gpBEiqGeU77/bFejDqUTRY7KX+0+iur13op3bqUsXdnwoZs6Xb1zbv0gAj5VvS1PWoUUckSr5Dw==}
|
||||
|
||||
'@exodus/bytes@1.15.0':
|
||||
resolution: {integrity: sha512-UY0nlA+feH81UGSHv92sLEPLCeZFjXOuHhrIo0HQydScuQc8s0A7kL/UdgwgDq8g8ilksmuoF35YVTNphV2aBQ==}
|
||||
engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0}
|
||||
|
|
@ -2010,6 +2019,9 @@ packages:
|
|||
embla-carousel@8.6.0:
|
||||
resolution: {integrity: sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==}
|
||||
|
||||
emoji-mart@5.6.0:
|
||||
resolution: {integrity: sha512-eJp3QRe79pjwa+duv+n7+5YsNhRcMl812EcFVwrnRvYKoNPoQb5qxU8DG6Bgwji0akHdp6D4Ln6tYLG58MFSow==}
|
||||
|
||||
emoji-regex@10.6.0:
|
||||
resolution: {integrity: sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==}
|
||||
|
||||
|
|
@ -4232,6 +4244,8 @@ snapshots:
|
|||
tslib: 2.8.1
|
||||
optional: true
|
||||
|
||||
'@emoji-mart/data@1.2.1': {}
|
||||
|
||||
'@exodus/bytes@1.15.0(@noble/hashes@1.8.0)':
|
||||
optionalDependencies:
|
||||
'@noble/hashes': 1.8.0
|
||||
|
|
@ -5567,6 +5581,8 @@ snapshots:
|
|||
|
||||
embla-carousel@8.6.0: {}
|
||||
|
||||
emoji-mart@5.6.0: {}
|
||||
|
||||
emoji-regex@10.6.0: {}
|
||||
|
||||
emoji-regex@8.0.0: {}
|
||||
|
|
|
|||
|
|
@ -473,6 +473,76 @@ func registerNotificationListeners(bus *events.Bus, queries *db.Queries) {
|
|||
}
|
||||
})
|
||||
|
||||
// issue_reaction:added — notify the issue creator
|
||||
bus.Subscribe(protocol.EventIssueReactionAdded, func(e events.Event) {
|
||||
payload, ok := e.Payload.(map[string]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
reaction, ok := payload["reaction"].(handler.IssueReactionResponse)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
creatorType, _ := payload["creator_type"].(string)
|
||||
creatorID, _ := payload["creator_id"].(string)
|
||||
issueID, _ := payload["issue_id"].(string)
|
||||
issueTitle, _ := payload["issue_title"].(string)
|
||||
issueStatus, _ := payload["issue_status"].(string)
|
||||
|
||||
if creatorType == "" || creatorID == "" {
|
||||
return
|
||||
}
|
||||
|
||||
details, _ := json.Marshal(map[string]string{
|
||||
"emoji": reaction.Emoji,
|
||||
})
|
||||
|
||||
notifyDirect(ctx, queries, bus,
|
||||
creatorType, creatorID,
|
||||
e.WorkspaceID, e, issueID, issueStatus,
|
||||
"reaction_added", "info",
|
||||
issueTitle, "",
|
||||
details,
|
||||
)
|
||||
})
|
||||
|
||||
// reaction:added — notify the comment author
|
||||
bus.Subscribe(protocol.EventReactionAdded, func(e events.Event) {
|
||||
payload, ok := e.Payload.(map[string]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
reaction, ok := payload["reaction"].(handler.ReactionResponse)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
commentAuthorType, _ := payload["comment_author_type"].(string)
|
||||
commentAuthorID, _ := payload["comment_author_id"].(string)
|
||||
issueID, _ := payload["issue_id"].(string)
|
||||
issueTitle, _ := payload["issue_title"].(string)
|
||||
issueStatus, _ := payload["issue_status"].(string)
|
||||
|
||||
if commentAuthorType == "" || commentAuthorID == "" {
|
||||
return
|
||||
}
|
||||
|
||||
details, _ := json.Marshal(map[string]string{
|
||||
"emoji": reaction.Emoji,
|
||||
})
|
||||
|
||||
notifyDirect(ctx, queries, bus,
|
||||
commentAuthorType, commentAuthorID,
|
||||
e.WorkspaceID, e, issueID, issueStatus,
|
||||
"reaction_added", "info",
|
||||
issueTitle, "",
|
||||
details,
|
||||
)
|
||||
})
|
||||
|
||||
// task:completed — notify all subscribers except the agent
|
||||
bus.Subscribe(protocol.EventTaskCompleted, func(e events.Event) {
|
||||
payload, ok := e.Payload.(map[string]any)
|
||||
|
|
|
|||
|
|
@ -168,6 +168,8 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus) chi.Route
|
|||
r.Post("/unsubscribe", h.UnsubscribeFromIssue)
|
||||
r.Get("/active-task", h.GetActiveTaskForIssue)
|
||||
r.Get("/task-runs", h.ListTasksByIssue)
|
||||
r.Post("/reactions", h.AddIssueReaction)
|
||||
r.Delete("/reactions", h.RemoveIssueReaction)
|
||||
})
|
||||
})
|
||||
|
||||
|
|
@ -175,6 +177,8 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus) chi.Route
|
|||
r.Route("/api/comments/{commentId}", func(r chi.Router) {
|
||||
r.Put("/", h.UpdateComment)
|
||||
r.Delete("/", h.DeleteComment)
|
||||
r.Post("/reactions", h.AddReaction)
|
||||
r.Delete("/reactions", h.RemoveReaction)
|
||||
})
|
||||
|
||||
// Agents
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import (
|
|||
"sort"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
db "github.com/multica-ai/multica/server/pkg/db/generated"
|
||||
)
|
||||
|
||||
|
|
@ -24,10 +25,11 @@ type TimelineEntry struct {
|
|||
Details json.RawMessage `json:"details,omitempty"`
|
||||
|
||||
// Comment-only fields
|
||||
Content *string `json:"content,omitempty"`
|
||||
ParentID *string `json:"parent_id,omitempty"`
|
||||
UpdatedAt *string `json:"updated_at,omitempty"`
|
||||
CommentType *string `json:"comment_type,omitempty"`
|
||||
Content *string `json:"content,omitempty"`
|
||||
ParentID *string `json:"parent_id,omitempty"`
|
||||
UpdatedAt *string `json:"updated_at,omitempty"`
|
||||
CommentType *string `json:"comment_type,omitempty"`
|
||||
Reactions []ReactionResponse `json:"reactions,omitempty"`
|
||||
}
|
||||
|
||||
// ListTimeline returns a merged, chronologically-sorted timeline of activities
|
||||
|
|
@ -77,6 +79,13 @@ func (h *Handler) ListTimeline(w http.ResponseWriter, r *http.Request) {
|
|||
})
|
||||
}
|
||||
|
||||
// Fetch reactions for all comments in one batch.
|
||||
commentIDs := make([]pgtype.UUID, len(comments))
|
||||
for i, c := range comments {
|
||||
commentIDs[i] = c.ID
|
||||
}
|
||||
grouped := h.groupReactions(r, commentIDs)
|
||||
|
||||
for _, c := range comments {
|
||||
content := c.Content
|
||||
commentType := c.Type
|
||||
|
|
@ -91,6 +100,7 @@ func (h *Handler) ListTimeline(w http.ResponseWriter, r *http.Request) {
|
|||
ParentID: uuidToPtr(c.ParentID),
|
||||
CreatedAt: timestampToString(c.CreatedAt),
|
||||
UpdatedAt: &updatedAt,
|
||||
Reactions: grouped[uuidToString(c.ID)],
|
||||
})
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -246,7 +246,7 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
if req.Visibility == "" {
|
||||
req.Visibility = "workspace"
|
||||
req.Visibility = "private"
|
||||
}
|
||||
if req.MaxConcurrentTasks == 0 {
|
||||
req.MaxConcurrentTasks = 6
|
||||
|
|
@ -325,13 +325,35 @@ type UpdateAgentRequest struct {
|
|||
Triggers any `json:"triggers"`
|
||||
}
|
||||
|
||||
// canManageAgent checks whether the current user can update or delete an agent.
|
||||
// Workspace-visible agents require owner/admin role. Private agents additionally
|
||||
// require the user to be the agent's owner (or a workspace owner/admin).
|
||||
func (h *Handler) canManageAgent(w http.ResponseWriter, r *http.Request, agent db.Agent) bool {
|
||||
wsID := uuidToString(agent.WorkspaceID)
|
||||
member, ok := h.requireWorkspaceRole(w, r, wsID, "agent not found", "owner", "admin", "member")
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
isAdmin := roleAllowed(member.Role, "owner", "admin")
|
||||
isAgentOwner := uuidToString(agent.OwnerID) == requestUserID(r)
|
||||
if agent.Visibility == "private" && !isAdmin && !isAgentOwner {
|
||||
writeError(w, http.StatusForbidden, "only the agent owner can manage this private agent")
|
||||
return false
|
||||
}
|
||||
if agent.Visibility != "private" && !isAdmin && !isAgentOwner {
|
||||
writeError(w, http.StatusForbidden, "insufficient permissions")
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {
|
||||
id := chi.URLParam(r, "id")
|
||||
agent, ok := h.loadAgentForUser(w, r, id)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, ok := h.requireWorkspaceRole(w, r, uuidToString(agent.WorkspaceID), "agent not found", "owner", "admin"); !ok {
|
||||
if !h.canManageAgent(w, r, agent) {
|
||||
return
|
||||
}
|
||||
|
||||
|
|
@ -413,8 +435,7 @@ func (h *Handler) DeleteAgent(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
wsID := uuidToString(agent.WorkspaceID)
|
||||
|
||||
// Require owner or admin role
|
||||
if _, ok := h.requireWorkspaceRole(w, r, wsID, "agent not found", "owner", "admin"); !ok {
|
||||
if !h.canManageAgent(w, r, agent) {
|
||||
return
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -13,18 +13,22 @@ import (
|
|||
)
|
||||
|
||||
type CommentResponse struct {
|
||||
ID string `json:"id"`
|
||||
IssueID string `json:"issue_id"`
|
||||
AuthorType string `json:"author_type"`
|
||||
AuthorID string `json:"author_id"`
|
||||
Content string `json:"content"`
|
||||
Type string `json:"type"`
|
||||
ParentID *string `json:"parent_id"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
ID string `json:"id"`
|
||||
IssueID string `json:"issue_id"`
|
||||
AuthorType string `json:"author_type"`
|
||||
AuthorID string `json:"author_id"`
|
||||
Content string `json:"content"`
|
||||
Type string `json:"type"`
|
||||
ParentID *string `json:"parent_id"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
Reactions []ReactionResponse `json:"reactions"`
|
||||
}
|
||||
|
||||
func commentToResponse(c db.Comment) CommentResponse {
|
||||
func commentToResponse(c db.Comment, reactions []ReactionResponse) CommentResponse {
|
||||
if reactions == nil {
|
||||
reactions = []ReactionResponse{}
|
||||
}
|
||||
return CommentResponse{
|
||||
ID: uuidToString(c.ID),
|
||||
IssueID: uuidToString(c.IssueID),
|
||||
|
|
@ -35,6 +39,7 @@ func commentToResponse(c db.Comment) CommentResponse {
|
|||
ParentID: uuidToPtr(c.ParentID),
|
||||
CreatedAt: timestampToString(c.CreatedAt),
|
||||
UpdatedAt: timestampToString(c.UpdatedAt),
|
||||
Reactions: reactions,
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -54,9 +59,15 @@ func (h *Handler) ListComments(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
|
||||
commentIDs := make([]pgtype.UUID, len(comments))
|
||||
for i, c := range comments {
|
||||
commentIDs[i] = c.ID
|
||||
}
|
||||
grouped := h.groupReactions(r, commentIDs)
|
||||
|
||||
resp := make([]CommentResponse, len(comments))
|
||||
for i, c := range comments {
|
||||
resp[i] = commentToResponse(c)
|
||||
resp[i] = commentToResponse(c, grouped[uuidToString(c.ID)])
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
|
|
@ -122,7 +133,7 @@ func (h *Handler) CreateComment(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
|
||||
resp := commentToResponse(comment)
|
||||
resp := commentToResponse(comment, nil)
|
||||
slog.Info("comment created", append(logger.RequestAttrs(r), "comment_id", uuidToString(comment.ID), "issue_id", issueID)...)
|
||||
h.publish(protocol.EventCommentCreated, uuidToString(issue.WorkspaceID), authorType, authorID, map[string]any{
|
||||
"comment": resp,
|
||||
|
|
@ -197,7 +208,9 @@ func (h *Handler) UpdateComment(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
|
||||
resp := commentToResponse(comment)
|
||||
// Fetch reactions for the updated comment.
|
||||
grouped := h.groupReactions(r, []pgtype.UUID{comment.ID})
|
||||
resp := commentToResponse(comment, grouped[uuidToString(comment.ID)])
|
||||
slog.Info("comment updated", append(logger.RequestAttrs(r), "comment_id", commentId)...)
|
||||
h.publish(protocol.EventCommentUpdated, workspaceID, actorType, actorID, map[string]any{"comment": resp})
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
|
|
|
|||
|
|
@ -18,23 +18,24 @@ import (
|
|||
|
||||
// IssueResponse is the JSON response for an issue.
|
||||
type IssueResponse struct {
|
||||
ID string `json:"id"`
|
||||
WorkspaceID string `json:"workspace_id"`
|
||||
Number int32 `json:"number"`
|
||||
Identifier string `json:"identifier"`
|
||||
Title string `json:"title"`
|
||||
Description *string `json:"description"`
|
||||
Status string `json:"status"`
|
||||
Priority string `json:"priority"`
|
||||
AssigneeType *string `json:"assignee_type"`
|
||||
AssigneeID *string `json:"assignee_id"`
|
||||
CreatorType string `json:"creator_type"`
|
||||
CreatorID string `json:"creator_id"`
|
||||
ParentIssueID *string `json:"parent_issue_id"`
|
||||
Position float64 `json:"position"`
|
||||
DueDate *string `json:"due_date"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
ID string `json:"id"`
|
||||
WorkspaceID string `json:"workspace_id"`
|
||||
Number int32 `json:"number"`
|
||||
Identifier string `json:"identifier"`
|
||||
Title string `json:"title"`
|
||||
Description *string `json:"description"`
|
||||
Status string `json:"status"`
|
||||
Priority string `json:"priority"`
|
||||
AssigneeType *string `json:"assignee_type"`
|
||||
AssigneeID *string `json:"assignee_id"`
|
||||
CreatorType string `json:"creator_type"`
|
||||
CreatorID string `json:"creator_id"`
|
||||
ParentIssueID *string `json:"parent_issue_id"`
|
||||
Position float64 `json:"position"`
|
||||
DueDate *string `json:"due_date"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
Reactions []IssueReactionResponse `json:"reactions,omitempty"`
|
||||
}
|
||||
|
||||
type agentTriggerSnapshot struct {
|
||||
|
|
@ -130,7 +131,18 @@ func (h *Handler) GetIssue(w http.ResponseWriter, r *http.Request) {
|
|||
return
|
||||
}
|
||||
prefix := h.getIssuePrefix(r.Context(), issue.WorkspaceID)
|
||||
writeJSON(w, http.StatusOK, issueToResponse(issue, prefix))
|
||||
resp := issueToResponse(issue, prefix)
|
||||
|
||||
// Fetch issue reactions.
|
||||
reactions, err := h.Queries.ListIssueReactions(r.Context(), issue.ID)
|
||||
if err == nil && len(reactions) > 0 {
|
||||
resp.Reactions = make([]IssueReactionResponse, len(reactions))
|
||||
for i, rx := range reactions {
|
||||
resp.Reactions[i] = issueReactionToResponse(rx)
|
||||
}
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
type CreateIssueRequest struct {
|
||||
|
|
@ -182,6 +194,14 @@ func (h *Handler) CreateIssue(w http.ResponseWriter, r *http.Request) {
|
|||
assigneeID = parseUUID(*req.AssigneeID)
|
||||
}
|
||||
|
||||
// Enforce agent visibility: private agents can only be assigned by owner/admin.
|
||||
if req.AssigneeType != nil && *req.AssigneeType == "agent" && req.AssigneeID != nil {
|
||||
if ok, msg := h.canAssignAgent(r.Context(), r, *req.AssigneeID, workspaceID); !ok {
|
||||
writeError(w, http.StatusForbidden, msg)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
var parentIssueID pgtype.UUID
|
||||
if req.ParentIssueID != nil {
|
||||
parentIssueID = parseUUID(*req.ParentIssueID)
|
||||
|
|
@ -347,6 +367,14 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
}
|
||||
|
||||
// Enforce agent visibility: private agents can only be assigned by owner/admin.
|
||||
if req.AssigneeType != nil && *req.AssigneeType == "agent" && req.AssigneeID != nil {
|
||||
if ok, msg := h.canAssignAgent(r.Context(), r, *req.AssigneeID, workspaceID); !ok {
|
||||
writeError(w, http.StatusForbidden, msg)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
issue, err := h.Queries.UpdateIssue(r.Context(), params)
|
||||
if err != nil {
|
||||
slog.Warn("update issue failed", append(logger.RequestAttrs(r), "error", err, "issue_id", id, "workspace_id", workspaceID)...)
|
||||
|
|
@ -403,6 +431,34 @@ func (h *Handler) UpdateIssue(w http.ResponseWriter, r *http.Request) {
|
|||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// canAssignAgent checks whether the requesting user is allowed to assign issues
|
||||
// to the given agent. Private agents can only be assigned by their owner or
|
||||
// workspace admins/owners.
|
||||
func (h *Handler) canAssignAgent(ctx context.Context, r *http.Request, agentID, workspaceID string) (bool, string) {
|
||||
agent, err := h.Queries.GetAgentInWorkspace(ctx, db.GetAgentInWorkspaceParams{
|
||||
ID: parseUUID(agentID),
|
||||
WorkspaceID: parseUUID(workspaceID),
|
||||
})
|
||||
if err != nil {
|
||||
return false, "agent not found"
|
||||
}
|
||||
if agent.Visibility != "private" {
|
||||
return true, ""
|
||||
}
|
||||
userID := requestUserID(r)
|
||||
if uuidToString(agent.OwnerID) == userID {
|
||||
return true, ""
|
||||
}
|
||||
member, err := h.getWorkspaceMember(ctx, userID, workspaceID)
|
||||
if err != nil {
|
||||
return false, "cannot assign to private agent"
|
||||
}
|
||||
if roleAllowed(member.Role, "owner", "admin") {
|
||||
return true, ""
|
||||
}
|
||||
return false, "cannot assign to private agent"
|
||||
}
|
||||
|
||||
func (h *Handler) shouldEnqueueAgentTask(ctx context.Context, issue db.Issue) bool {
|
||||
if issue.Status != "todo" {
|
||||
return false
|
||||
|
|
@ -580,6 +636,13 @@ func (h *Handler) BatchUpdateIssues(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
}
|
||||
|
||||
// Enforce agent visibility for batch assignment.
|
||||
if req.Updates.AssigneeType != nil && *req.Updates.AssigneeType == "agent" && req.Updates.AssigneeID != nil {
|
||||
if ok, _ := h.canAssignAgent(r.Context(), r, *req.Updates.AssigneeID, workspaceID); !ok {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
issue, err := h.Queries.UpdateIssue(r.Context(), params)
|
||||
if err != nil {
|
||||
slog.Warn("batch update issue failed", "issue_id", issueID, "error", err)
|
||||
|
|
|
|||
131
server/internal/handler/issue_reaction.go
Normal file
131
server/internal/handler/issue_reaction.go
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/multica-ai/multica/server/internal/logger"
|
||||
db "github.com/multica-ai/multica/server/pkg/db/generated"
|
||||
"github.com/multica-ai/multica/server/pkg/protocol"
|
||||
)
|
||||
|
||||
type IssueReactionResponse struct {
|
||||
ID string `json:"id"`
|
||||
IssueID string `json:"issue_id"`
|
||||
ActorType string `json:"actor_type"`
|
||||
ActorID string `json:"actor_id"`
|
||||
Emoji string `json:"emoji"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
func issueReactionToResponse(r db.IssueReaction) IssueReactionResponse {
|
||||
return IssueReactionResponse{
|
||||
ID: uuidToString(r.ID),
|
||||
IssueID: uuidToString(r.IssueID),
|
||||
ActorType: r.ActorType,
|
||||
ActorID: uuidToString(r.ActorID),
|
||||
Emoji: r.Emoji,
|
||||
CreatedAt: timestampToString(r.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) AddIssueReaction(w http.ResponseWriter, r *http.Request) {
|
||||
issueID := chi.URLParam(r, "id")
|
||||
issue, ok := h.loadIssueForUser(w, r, issueID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
userID, ok := requireUserID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Emoji string `json:"emoji"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if req.Emoji == "" {
|
||||
writeError(w, http.StatusBadRequest, "emoji is required")
|
||||
return
|
||||
}
|
||||
|
||||
workspaceID := uuidToString(issue.WorkspaceID)
|
||||
actorType, actorID := h.resolveActor(r, userID, workspaceID)
|
||||
|
||||
reaction, err := h.Queries.AddIssueReaction(r.Context(), db.AddIssueReactionParams{
|
||||
IssueID: issue.ID,
|
||||
WorkspaceID: issue.WorkspaceID,
|
||||
ActorType: actorType,
|
||||
ActorID: parseUUID(actorID),
|
||||
Emoji: req.Emoji,
|
||||
})
|
||||
if err != nil {
|
||||
slog.Warn("add issue reaction failed", append(logger.RequestAttrs(r), "error", err, "issue_id", issueID)...)
|
||||
writeError(w, http.StatusInternalServerError, "failed to add reaction")
|
||||
return
|
||||
}
|
||||
|
||||
resp := issueReactionToResponse(reaction)
|
||||
h.publish(protocol.EventIssueReactionAdded, workspaceID, actorType, actorID, map[string]any{
|
||||
"reaction": resp,
|
||||
"issue_id": uuidToString(issue.ID),
|
||||
"issue_title": issue.Title,
|
||||
"issue_status": issue.Status,
|
||||
"creator_type": issue.CreatorType,
|
||||
"creator_id": uuidToString(issue.CreatorID),
|
||||
})
|
||||
writeJSON(w, http.StatusCreated, resp)
|
||||
}
|
||||
|
||||
func (h *Handler) RemoveIssueReaction(w http.ResponseWriter, r *http.Request) {
|
||||
issueID := chi.URLParam(r, "id")
|
||||
issue, ok := h.loadIssueForUser(w, r, issueID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
userID, ok := requireUserID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Emoji string `json:"emoji"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if req.Emoji == "" {
|
||||
writeError(w, http.StatusBadRequest, "emoji is required")
|
||||
return
|
||||
}
|
||||
|
||||
workspaceID := uuidToString(issue.WorkspaceID)
|
||||
actorType, actorID := h.resolveActor(r, userID, workspaceID)
|
||||
|
||||
if err := h.Queries.RemoveIssueReaction(r.Context(), db.RemoveIssueReactionParams{
|
||||
IssueID: issue.ID,
|
||||
ActorType: actorType,
|
||||
ActorID: parseUUID(actorID),
|
||||
Emoji: req.Emoji,
|
||||
}); err != nil {
|
||||
slog.Warn("remove issue reaction failed", append(logger.RequestAttrs(r), "error", err, "issue_id", issueID)...)
|
||||
writeError(w, http.StatusInternalServerError, "failed to remove reaction")
|
||||
return
|
||||
}
|
||||
|
||||
h.publish(protocol.EventIssueReactionRemoved, workspaceID, actorType, actorID, map[string]any{
|
||||
"issue_id": uuidToString(issue.ID),
|
||||
"emoji": req.Emoji,
|
||||
"actor_type": actorType,
|
||||
"actor_id": actorID,
|
||||
})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
169
server/internal/handler/reaction.go
Normal file
169
server/internal/handler/reaction.go
Normal file
|
|
@ -0,0 +1,169 @@
|
|||
package handler
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/multica-ai/multica/server/internal/logger"
|
||||
db "github.com/multica-ai/multica/server/pkg/db/generated"
|
||||
"github.com/multica-ai/multica/server/pkg/protocol"
|
||||
)
|
||||
|
||||
type ReactionResponse struct {
|
||||
ID string `json:"id"`
|
||||
CommentID string `json:"comment_id"`
|
||||
ActorType string `json:"actor_type"`
|
||||
ActorID string `json:"actor_id"`
|
||||
Emoji string `json:"emoji"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
func reactionToResponse(r db.CommentReaction) ReactionResponse {
|
||||
return ReactionResponse{
|
||||
ID: uuidToString(r.ID),
|
||||
CommentID: uuidToString(r.CommentID),
|
||||
ActorType: r.ActorType,
|
||||
ActorID: uuidToString(r.ActorID),
|
||||
Emoji: r.Emoji,
|
||||
CreatedAt: timestampToString(r.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) AddReaction(w http.ResponseWriter, r *http.Request) {
|
||||
commentId := chi.URLParam(r, "commentId")
|
||||
|
||||
userID, ok := requireUserID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
workspaceID := resolveWorkspaceID(r)
|
||||
comment, err := h.Queries.GetCommentInWorkspace(r.Context(), db.GetCommentInWorkspaceParams{
|
||||
ID: parseUUID(commentId),
|
||||
WorkspaceID: parseUUID(workspaceID),
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "comment not found")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Emoji string `json:"emoji"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if req.Emoji == "" {
|
||||
writeError(w, http.StatusBadRequest, "emoji is required")
|
||||
return
|
||||
}
|
||||
|
||||
actorType, actorID := h.resolveActor(r, userID, workspaceID)
|
||||
|
||||
reaction, err := h.Queries.AddReaction(r.Context(), db.AddReactionParams{
|
||||
CommentID: comment.ID,
|
||||
WorkspaceID: parseUUID(workspaceID),
|
||||
ActorType: actorType,
|
||||
ActorID: parseUUID(actorID),
|
||||
Emoji: req.Emoji,
|
||||
})
|
||||
if err != nil {
|
||||
slog.Warn("add reaction failed", append(logger.RequestAttrs(r), "error", err, "comment_id", commentId)...)
|
||||
writeError(w, http.StatusInternalServerError, "failed to add reaction")
|
||||
return
|
||||
}
|
||||
|
||||
resp := reactionToResponse(reaction)
|
||||
|
||||
// Look up issue title for inbox notifications.
|
||||
issueID := uuidToString(comment.IssueID)
|
||||
var issueTitle, issueStatus string
|
||||
if issue, err := h.Queries.GetIssue(r.Context(), comment.IssueID); err == nil {
|
||||
issueTitle = issue.Title
|
||||
issueStatus = issue.Status
|
||||
}
|
||||
|
||||
h.publish(protocol.EventReactionAdded, workspaceID, actorType, actorID, map[string]any{
|
||||
"reaction": resp,
|
||||
"issue_id": issueID,
|
||||
"issue_title": issueTitle,
|
||||
"issue_status": issueStatus,
|
||||
"comment_author_type": comment.AuthorType,
|
||||
"comment_author_id": uuidToString(comment.AuthorID),
|
||||
})
|
||||
writeJSON(w, http.StatusCreated, resp)
|
||||
}
|
||||
|
||||
func (h *Handler) RemoveReaction(w http.ResponseWriter, r *http.Request) {
|
||||
commentId := chi.URLParam(r, "commentId")
|
||||
|
||||
userID, ok := requireUserID(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
workspaceID := resolveWorkspaceID(r)
|
||||
comment, err := h.Queries.GetCommentInWorkspace(r.Context(), db.GetCommentInWorkspaceParams{
|
||||
ID: parseUUID(commentId),
|
||||
WorkspaceID: parseUUID(workspaceID),
|
||||
})
|
||||
if err != nil {
|
||||
writeError(w, http.StatusNotFound, "comment not found")
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Emoji string `json:"emoji"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, "invalid request body")
|
||||
return
|
||||
}
|
||||
if req.Emoji == "" {
|
||||
writeError(w, http.StatusBadRequest, "emoji is required")
|
||||
return
|
||||
}
|
||||
|
||||
actorType, actorID := h.resolveActor(r, userID, workspaceID)
|
||||
|
||||
if err := h.Queries.RemoveReaction(r.Context(), db.RemoveReactionParams{
|
||||
CommentID: comment.ID,
|
||||
ActorType: actorType,
|
||||
ActorID: parseUUID(actorID),
|
||||
Emoji: req.Emoji,
|
||||
}); err != nil {
|
||||
slog.Warn("remove reaction failed", append(logger.RequestAttrs(r), "error", err, "comment_id", commentId)...)
|
||||
writeError(w, http.StatusInternalServerError, "failed to remove reaction")
|
||||
return
|
||||
}
|
||||
|
||||
h.publish(protocol.EventReactionRemoved, workspaceID, actorType, actorID, map[string]any{
|
||||
"comment_id": commentId,
|
||||
"issue_id": uuidToString(comment.IssueID),
|
||||
"emoji": req.Emoji,
|
||||
"actor_type": actorType,
|
||||
"actor_id": actorID,
|
||||
})
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
// groupReactions fetches reactions for the given comment IDs and groups them by comment_id.
|
||||
func (h *Handler) groupReactions(r *http.Request, commentIDs []pgtype.UUID) map[string][]ReactionResponse {
|
||||
if len(commentIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
reactions, err := h.Queries.ListReactionsByCommentIDs(r.Context(), commentIDs)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
grouped := make(map[string][]ReactionResponse, len(commentIDs))
|
||||
for _, rx := range reactions {
|
||||
cid := uuidToString(rx.CommentID)
|
||||
grouped[cid] = append(grouped[cid], reactionToResponse(rx))
|
||||
}
|
||||
return grouped
|
||||
}
|
||||
|
|
@ -16,6 +16,7 @@ import (
|
|||
"github.com/multica-ai/multica/server/internal/util"
|
||||
db "github.com/multica-ai/multica/server/pkg/db/generated"
|
||||
"github.com/multica-ai/multica/server/pkg/protocol"
|
||||
"github.com/multica-ai/multica/server/pkg/redact"
|
||||
)
|
||||
|
||||
type TaskService struct {
|
||||
|
|
@ -187,7 +188,7 @@ func (s *TaskService) CompleteTask(ctx context.Context, taskID pgtype.UUID, resu
|
|||
var payload protocol.TaskCompletedPayload
|
||||
if err := json.Unmarshal(result, &payload); err == nil {
|
||||
if payload.Output != "" {
|
||||
s.createAgentComment(ctx, task.IssueID, task.AgentID, payload.Output, "comment")
|
||||
s.createAgentComment(ctx, task.IssueID, task.AgentID, redact.Text(payload.Output), "comment")
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -227,7 +228,7 @@ func (s *TaskService) FailTask(ctx context.Context, taskID pgtype.UUID, errMsg s
|
|||
slog.Warn("task failed", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID), "error", errMsg)
|
||||
|
||||
if errMsg != "" {
|
||||
s.createAgentComment(ctx, task.IssueID, task.AgentID, errMsg, "system")
|
||||
s.createAgentComment(ctx, task.IssueID, task.AgentID, redact.Text(errMsg), "system")
|
||||
}
|
||||
// Reconcile agent status
|
||||
s.ReconcileAgentStatus(ctx, task.AgentID)
|
||||
|
|
|
|||
1
server/migrations/026_comment_reactions.down.sql
Normal file
1
server/migrations/026_comment_reactions.down.sql
Normal file
|
|
@ -0,0 +1 @@
|
|||
DROP TABLE IF EXISTS comment_reaction;
|
||||
12
server/migrations/026_comment_reactions.up.sql
Normal file
12
server/migrations/026_comment_reactions.up.sql
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
CREATE TABLE comment_reaction (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
comment_id UUID NOT NULL REFERENCES comment(id) ON DELETE CASCADE,
|
||||
workspace_id UUID NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
|
||||
actor_type TEXT NOT NULL CHECK (actor_type IN ('member', 'agent')),
|
||||
actor_id UUID NOT NULL,
|
||||
emoji TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (comment_id, actor_type, actor_id, emoji)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_comment_reaction_comment_id ON comment_reaction(comment_id);
|
||||
1
server/migrations/027_issue_reactions.down.sql
Normal file
1
server/migrations/027_issue_reactions.down.sql
Normal file
|
|
@ -0,0 +1 @@
|
|||
DROP TABLE IF EXISTS issue_reaction;
|
||||
12
server/migrations/027_issue_reactions.up.sql
Normal file
12
server/migrations/027_issue_reactions.up.sql
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
CREATE TABLE issue_reaction (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
issue_id UUID NOT NULL REFERENCES issue(id) ON DELETE CASCADE,
|
||||
workspace_id UUID NOT NULL REFERENCES workspace(id) ON DELETE CASCADE,
|
||||
actor_type TEXT NOT NULL CHECK (actor_type IN ('member', 'agent')),
|
||||
actor_id UUID NOT NULL,
|
||||
emoji TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (issue_id, actor_type, actor_id, emoji)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_issue_reaction_issue_id ON issue_reaction(issue_id);
|
||||
|
|
@ -218,6 +218,7 @@ func TestBuildEnvNilExtras(t *testing.T) {
|
|||
}
|
||||
}
|
||||
|
||||
|
||||
func mustMarshal(t *testing.T, v any) json.RawMessage {
|
||||
t.Helper()
|
||||
data, err := json.Marshal(v)
|
||||
|
|
|
|||
104
server/pkg/db/generated/issue_reaction.sql.go
Normal file
104
server/pkg/db/generated/issue_reaction.sql.go
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.30.0
|
||||
// source: issue_reaction.sql
|
||||
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const addIssueReaction = `-- name: AddIssueReaction :one
|
||||
INSERT INTO issue_reaction (issue_id, workspace_id, actor_type, actor_id, emoji)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (issue_id, actor_type, actor_id, emoji) DO UPDATE SET created_at = issue_reaction.created_at
|
||||
RETURNING id, issue_id, workspace_id, actor_type, actor_id, emoji, created_at
|
||||
`
|
||||
|
||||
type AddIssueReactionParams struct {
|
||||
IssueID pgtype.UUID `json:"issue_id"`
|
||||
WorkspaceID pgtype.UUID `json:"workspace_id"`
|
||||
ActorType string `json:"actor_type"`
|
||||
ActorID pgtype.UUID `json:"actor_id"`
|
||||
Emoji string `json:"emoji"`
|
||||
}
|
||||
|
||||
func (q *Queries) AddIssueReaction(ctx context.Context, arg AddIssueReactionParams) (IssueReaction, error) {
|
||||
row := q.db.QueryRow(ctx, addIssueReaction,
|
||||
arg.IssueID,
|
||||
arg.WorkspaceID,
|
||||
arg.ActorType,
|
||||
arg.ActorID,
|
||||
arg.Emoji,
|
||||
)
|
||||
var i IssueReaction
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.IssueID,
|
||||
&i.WorkspaceID,
|
||||
&i.ActorType,
|
||||
&i.ActorID,
|
||||
&i.Emoji,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listIssueReactions = `-- name: ListIssueReactions :many
|
||||
SELECT id, issue_id, workspace_id, actor_type, actor_id, emoji, created_at FROM issue_reaction
|
||||
WHERE issue_id = $1
|
||||
ORDER BY created_at ASC
|
||||
`
|
||||
|
||||
func (q *Queries) ListIssueReactions(ctx context.Context, issueID pgtype.UUID) ([]IssueReaction, error) {
|
||||
rows, err := q.db.Query(ctx, listIssueReactions, issueID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []IssueReaction{}
|
||||
for rows.Next() {
|
||||
var i IssueReaction
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.IssueID,
|
||||
&i.WorkspaceID,
|
||||
&i.ActorType,
|
||||
&i.ActorID,
|
||||
&i.Emoji,
|
||||
&i.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const removeIssueReaction = `-- name: RemoveIssueReaction :exec
|
||||
DELETE FROM issue_reaction
|
||||
WHERE issue_id = $1 AND actor_type = $2 AND actor_id = $3 AND emoji = $4
|
||||
`
|
||||
|
||||
type RemoveIssueReactionParams struct {
|
||||
IssueID pgtype.UUID `json:"issue_id"`
|
||||
ActorType string `json:"actor_type"`
|
||||
ActorID pgtype.UUID `json:"actor_id"`
|
||||
Emoji string `json:"emoji"`
|
||||
}
|
||||
|
||||
func (q *Queries) RemoveIssueReaction(ctx context.Context, arg RemoveIssueReactionParams) error {
|
||||
_, err := q.db.Exec(ctx, removeIssueReaction,
|
||||
arg.IssueID,
|
||||
arg.ActorType,
|
||||
arg.ActorID,
|
||||
arg.Emoji,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
|
@ -91,6 +91,16 @@ type Comment struct {
|
|||
WorkspaceID pgtype.UUID `json:"workspace_id"`
|
||||
}
|
||||
|
||||
type CommentReaction struct {
|
||||
ID pgtype.UUID `json:"id"`
|
||||
CommentID pgtype.UUID `json:"comment_id"`
|
||||
WorkspaceID pgtype.UUID `json:"workspace_id"`
|
||||
ActorType string `json:"actor_type"`
|
||||
ActorID pgtype.UUID `json:"actor_id"`
|
||||
Emoji string `json:"emoji"`
|
||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
}
|
||||
|
||||
type DaemonConnection struct {
|
||||
ID pgtype.UUID `json:"id"`
|
||||
AgentID pgtype.UUID `json:"agent_id"`
|
||||
|
|
@ -173,6 +183,16 @@ type IssueLabel struct {
|
|||
Color string `json:"color"`
|
||||
}
|
||||
|
||||
type IssueReaction struct {
|
||||
ID pgtype.UUID `json:"id"`
|
||||
IssueID pgtype.UUID `json:"issue_id"`
|
||||
WorkspaceID pgtype.UUID `json:"workspace_id"`
|
||||
ActorType string `json:"actor_type"`
|
||||
ActorID pgtype.UUID `json:"actor_id"`
|
||||
Emoji string `json:"emoji"`
|
||||
CreatedAt pgtype.Timestamptz `json:"created_at"`
|
||||
}
|
||||
|
||||
type IssueSubscriber struct {
|
||||
IssueID pgtype.UUID `json:"issue_id"`
|
||||
UserType string `json:"user_type"`
|
||||
|
|
|
|||
104
server/pkg/db/generated/reaction.sql.go
Normal file
104
server/pkg/db/generated/reaction.sql.go
Normal file
|
|
@ -0,0 +1,104 @@
|
|||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.30.0
|
||||
// source: reaction.sql
|
||||
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const addReaction = `-- name: AddReaction :one
|
||||
INSERT INTO comment_reaction (comment_id, workspace_id, actor_type, actor_id, emoji)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (comment_id, actor_type, actor_id, emoji) DO UPDATE SET created_at = comment_reaction.created_at
|
||||
RETURNING id, comment_id, workspace_id, actor_type, actor_id, emoji, created_at
|
||||
`
|
||||
|
||||
type AddReactionParams struct {
|
||||
CommentID pgtype.UUID `json:"comment_id"`
|
||||
WorkspaceID pgtype.UUID `json:"workspace_id"`
|
||||
ActorType string `json:"actor_type"`
|
||||
ActorID pgtype.UUID `json:"actor_id"`
|
||||
Emoji string `json:"emoji"`
|
||||
}
|
||||
|
||||
func (q *Queries) AddReaction(ctx context.Context, arg AddReactionParams) (CommentReaction, error) {
|
||||
row := q.db.QueryRow(ctx, addReaction,
|
||||
arg.CommentID,
|
||||
arg.WorkspaceID,
|
||||
arg.ActorType,
|
||||
arg.ActorID,
|
||||
arg.Emoji,
|
||||
)
|
||||
var i CommentReaction
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.CommentID,
|
||||
&i.WorkspaceID,
|
||||
&i.ActorType,
|
||||
&i.ActorID,
|
||||
&i.Emoji,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listReactionsByCommentIDs = `-- name: ListReactionsByCommentIDs :many
|
||||
SELECT id, comment_id, workspace_id, actor_type, actor_id, emoji, created_at FROM comment_reaction
|
||||
WHERE comment_id = ANY($1::uuid[])
|
||||
ORDER BY created_at ASC
|
||||
`
|
||||
|
||||
func (q *Queries) ListReactionsByCommentIDs(ctx context.Context, dollar_1 []pgtype.UUID) ([]CommentReaction, error) {
|
||||
rows, err := q.db.Query(ctx, listReactionsByCommentIDs, dollar_1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []CommentReaction{}
|
||||
for rows.Next() {
|
||||
var i CommentReaction
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.CommentID,
|
||||
&i.WorkspaceID,
|
||||
&i.ActorType,
|
||||
&i.ActorID,
|
||||
&i.Emoji,
|
||||
&i.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const removeReaction = `-- name: RemoveReaction :exec
|
||||
DELETE FROM comment_reaction
|
||||
WHERE comment_id = $1 AND actor_type = $2 AND actor_id = $3 AND emoji = $4
|
||||
`
|
||||
|
||||
type RemoveReactionParams struct {
|
||||
CommentID pgtype.UUID `json:"comment_id"`
|
||||
ActorType string `json:"actor_type"`
|
||||
ActorID pgtype.UUID `json:"actor_id"`
|
||||
Emoji string `json:"emoji"`
|
||||
}
|
||||
|
||||
func (q *Queries) RemoveReaction(ctx context.Context, arg RemoveReactionParams) error {
|
||||
_, err := q.db.Exec(ctx, removeReaction,
|
||||
arg.CommentID,
|
||||
arg.ActorType,
|
||||
arg.ActorID,
|
||||
arg.Emoji,
|
||||
)
|
||||
return err
|
||||
}
|
||||
14
server/pkg/db/queries/issue_reaction.sql
Normal file
14
server/pkg/db/queries/issue_reaction.sql
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
-- name: AddIssueReaction :one
|
||||
INSERT INTO issue_reaction (issue_id, workspace_id, actor_type, actor_id, emoji)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (issue_id, actor_type, actor_id, emoji) DO UPDATE SET created_at = issue_reaction.created_at
|
||||
RETURNING *;
|
||||
|
||||
-- name: RemoveIssueReaction :exec
|
||||
DELETE FROM issue_reaction
|
||||
WHERE issue_id = $1 AND actor_type = $2 AND actor_id = $3 AND emoji = $4;
|
||||
|
||||
-- name: ListIssueReactions :many
|
||||
SELECT * FROM issue_reaction
|
||||
WHERE issue_id = $1
|
||||
ORDER BY created_at ASC;
|
||||
14
server/pkg/db/queries/reaction.sql
Normal file
14
server/pkg/db/queries/reaction.sql
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
-- name: AddReaction :one
|
||||
INSERT INTO comment_reaction (comment_id, workspace_id, actor_type, actor_id, emoji)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (comment_id, actor_type, actor_id, emoji) DO UPDATE SET created_at = comment_reaction.created_at
|
||||
RETURNING *;
|
||||
|
||||
-- name: RemoveReaction :exec
|
||||
DELETE FROM comment_reaction
|
||||
WHERE comment_id = $1 AND actor_type = $2 AND actor_id = $3 AND emoji = $4;
|
||||
|
||||
-- name: ListReactionsByCommentIDs :many
|
||||
SELECT * FROM comment_reaction
|
||||
WHERE comment_id = ANY($1::uuid[])
|
||||
ORDER BY created_at ASC;
|
||||
|
|
@ -8,9 +8,13 @@ const (
|
|||
EventIssueDeleted = "issue:deleted"
|
||||
|
||||
// Comment events
|
||||
EventCommentCreated = "comment:created"
|
||||
EventCommentUpdated = "comment:updated"
|
||||
EventCommentDeleted = "comment:deleted"
|
||||
EventCommentCreated = "comment:created"
|
||||
EventCommentUpdated = "comment:updated"
|
||||
EventCommentDeleted = "comment:deleted"
|
||||
EventReactionAdded = "reaction:added"
|
||||
EventReactionRemoved = "reaction:removed"
|
||||
EventIssueReactionAdded = "issue_reaction:added"
|
||||
EventIssueReactionRemoved = "issue_reaction:removed"
|
||||
|
||||
// Agent events
|
||||
EventAgentStatus = "agent:status"
|
||||
|
|
|
|||
71
server/pkg/redact/redact.go
Normal file
71
server/pkg/redact/redact.go
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
// Package redact provides functions for detecting and masking secrets
|
||||
// in agent output before it reaches the database or WebSocket broadcast.
|
||||
package redact
|
||||
|
||||
import (
|
||||
"os"
|
||||
"os/user"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// secretPattern pairs a compiled regex with its replacement text.
|
||||
type secretPattern struct {
|
||||
re *regexp.Regexp
|
||||
replacement string
|
||||
}
|
||||
|
||||
// Patterns are checked in order; first match wins per position.
|
||||
var patterns = []secretPattern{
|
||||
// AWS access key IDs (always start with AKIA)
|
||||
{regexp.MustCompile(`\bAKIA[0-9A-Z]{16}\b`), "[REDACTED AWS KEY]"},
|
||||
|
||||
// AWS secret access keys (40 char base64-ish, preceded by a common separator)
|
||||
{regexp.MustCompile(`(?i)(?:aws_secret_access_key|secret_?access_?key)\s*[=:]\s*[A-Za-z0-9/+=]{40}`), "[REDACTED AWS SECRET]"},
|
||||
|
||||
// PEM private keys (multi-line)
|
||||
{regexp.MustCompile(`(?s)-----BEGIN[A-Z\s]*PRIVATE KEY-----.*?-----END[A-Z\s]*PRIVATE KEY-----`), "[REDACTED PRIVATE KEY]"},
|
||||
|
||||
// GitHub tokens (classic PAT, fine-grained, OAuth, etc.)
|
||||
{regexp.MustCompile(`\b(ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9_]{36,255}\b`), "[REDACTED GITHUB TOKEN]"},
|
||||
|
||||
// OpenAI / Anthropic API keys
|
||||
{regexp.MustCompile(`\bsk-[A-Za-z0-9_-]{20,}\b`), "[REDACTED API KEY]"},
|
||||
|
||||
// Slack tokens
|
||||
{regexp.MustCompile(`\bxox[bporas]-[A-Za-z0-9\-]{10,}\b`), "[REDACTED SLACK TOKEN]"},
|
||||
|
||||
// Generic "Bearer <token>" in output
|
||||
{regexp.MustCompile(`(?i)\bBearer\s+[A-Za-z0-9\-._~+/]+=*\b`), "Bearer [REDACTED]"},
|
||||
|
||||
// Generic key=value patterns for common secret env var names
|
||||
{regexp.MustCompile(`(?i)(?:API_KEY|API_SECRET|SECRET_KEY|ACCESS_TOKEN|AUTH_TOKEN|PRIVATE_KEY|DATABASE_URL|DB_PASSWORD|REDIS_URL)\s*[=:]\s*\S+`), "[REDACTED CREDENTIAL]"},
|
||||
}
|
||||
|
||||
// homeDir is resolved once at init for path redaction.
|
||||
var homeDir string
|
||||
var username string
|
||||
|
||||
func init() {
|
||||
homeDir, _ = os.UserHomeDir()
|
||||
if u, err := user.Current(); err == nil {
|
||||
username = u.Username
|
||||
}
|
||||
}
|
||||
|
||||
// Text scans the input string for known secret patterns and replaces
|
||||
// matches with safe placeholders. It also masks the local user's home
|
||||
// directory path to prevent leaking the username.
|
||||
func Text(s string) string {
|
||||
for _, p := range patterns {
|
||||
s = p.re.ReplaceAllString(s, p.replacement)
|
||||
}
|
||||
|
||||
// Redact home directory paths (e.g. /Users/john/ → /Users/****/).
|
||||
if homeDir != "" && username != "" {
|
||||
masked := strings.Replace(homeDir, username, "****", 1)
|
||||
s = strings.ReplaceAll(s, homeDir, masked)
|
||||
}
|
||||
|
||||
return s
|
||||
}
|
||||
139
server/pkg/redact/redact_test.go
Normal file
139
server/pkg/redact/redact_test.go
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
package redact
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestRedactAWSAccessKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
input := "Found key AKIAIOSFODNN7EXAMPLE in config"
|
||||
got := Text(input)
|
||||
if strings.Contains(got, "AKIAIOSFODNN7EXAMPLE") {
|
||||
t.Fatalf("AWS key not redacted: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "[REDACTED AWS KEY]") {
|
||||
t.Fatalf("expected [REDACTED AWS KEY] placeholder, got: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedactAWSSecretKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
input := "aws_secret_access_key = wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
|
||||
got := Text(input)
|
||||
if strings.Contains(got, "wJalrXUtnFEMI") {
|
||||
t.Fatalf("AWS secret not redacted: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedactPrivateKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
input := "Here is the key:\n-----BEGIN RSA PRIVATE KEY-----\nMIIEow...\n-----END RSA PRIVATE KEY-----\nDone."
|
||||
got := Text(input)
|
||||
if strings.Contains(got, "MIIEow") {
|
||||
t.Fatalf("private key content not redacted: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "[REDACTED PRIVATE KEY]") {
|
||||
t.Fatalf("expected [REDACTED PRIVATE KEY] placeholder, got: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedactGitHubToken(t *testing.T) {
|
||||
t.Parallel()
|
||||
input := "export GITHUB_TOKEN=ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn"
|
||||
got := Text(input)
|
||||
if strings.Contains(got, "ghp_") {
|
||||
t.Fatalf("GitHub token not redacted: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedactOpenAIKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
input := "OPENAI_API_KEY=sk-proj-abc123def456ghi789jkl012mno345"
|
||||
got := Text(input)
|
||||
if strings.Contains(got, "sk-proj-abc123") {
|
||||
t.Fatalf("OpenAI key not redacted: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedactSlackToken(t *testing.T) {
|
||||
t.Parallel()
|
||||
input := "token: xoxb-123456789012-1234567890123-AbCdEfGhIjKl"
|
||||
got := Text(input)
|
||||
if strings.Contains(got, "xoxb-") {
|
||||
t.Fatalf("Slack token not redacted: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedactBearerToken(t *testing.T) {
|
||||
t.Parallel()
|
||||
input := "Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.abc123"
|
||||
got := Text(input)
|
||||
if strings.Contains(got, "eyJhbGci") {
|
||||
t.Fatalf("Bearer token not redacted: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedactGenericCredentials(t *testing.T) {
|
||||
t.Parallel()
|
||||
cases := []struct {
|
||||
name string
|
||||
input string
|
||||
}{
|
||||
{"API_KEY", "API_KEY=mysupersecretkey123"},
|
||||
{"DATABASE_URL", "DATABASE_URL=postgres://user:pass@host/db"},
|
||||
{"DB_PASSWORD", "DB_PASSWORD: hunter2"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := Text(tc.input)
|
||||
if !strings.Contains(got, "[REDACTED CREDENTIAL]") {
|
||||
t.Fatalf("expected credential redaction for %s, got: %s", tc.name, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedactHomeDirectory(t *testing.T) {
|
||||
t.Parallel()
|
||||
if homeDir == "" || username == "" {
|
||||
t.Skip("cannot determine home dir or username")
|
||||
}
|
||||
input := "Reading file at " + homeDir + "/Documents/secret.txt"
|
||||
got := Text(input)
|
||||
if strings.Contains(got, username) {
|
||||
t.Fatalf("home directory username not redacted: %s", got)
|
||||
}
|
||||
if !strings.Contains(got, "****") {
|
||||
t.Fatalf("expected **** in path, got: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoFalsePositivesOnNormalText(t *testing.T) {
|
||||
t.Parallel()
|
||||
inputs := []string{
|
||||
"This is a normal commit message about fixing a bug",
|
||||
"The function returns skip-navigation as the class name",
|
||||
"Created PR #42 for the authentication feature",
|
||||
"Running tests in /tmp/test-workspace/project",
|
||||
"The API endpoint /api/issues/123 was updated",
|
||||
}
|
||||
for _, input := range inputs {
|
||||
got := Text(input)
|
||||
if got != input {
|
||||
t.Fatalf("false positive redaction:\n input: %s\n output: %s", input, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRedactMultipleSecrets(t *testing.T) {
|
||||
t.Parallel()
|
||||
input := "Keys: AKIAIOSFODNN7EXAMPLE and ghp_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmn"
|
||||
got := Text(input)
|
||||
if strings.Contains(got, "AKIAIOSFODNN7EXAMPLE") {
|
||||
t.Fatal("AWS key not redacted in multi-secret text")
|
||||
}
|
||||
if strings.Contains(got, "ghp_") {
|
||||
t.Fatal("GitHub token not redacted in multi-secret text")
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue