feat: attribute cross-task agent messages with a sender badge (#819)

* feat(orchestrator): carry sender_task metadata through user message paths

Add WithSenderTask builder to UserMessageMeta and a metadata-aware
QueueMessageWithMetadata variant on the message queue. The drain path
in event_handlers_agent merges queued metadata into the recorded user
message so attribution survives the queue → DB transition.

* feat(mcp): attribute message_task_kandev calls to the sending agent

The MCP server inside agentctl now injects sender_task_id and
sender_session_id from its own server context. The backend handler
validates the sender (rejecting missing IDs, self-messages, and unknown
tasks), looks up the sender title, wraps the prompt in a <kandev-system>
attribution block, and propagates structured metadata across all three
delivery paths (queue, created-session, record+prompt). The wrapped
content lets the receiving agent identify the peer both live and on ACP
session resume; the existing sysprompt strip pipeline hides the wrapper
from the UI.

* feat(web): render sender-task badge on cross-task agent messages

User messages whose metadata carries sender_task_id now render a
clickable purple badge above the bubble, linking to the source task.
The badge live-resolves the sender's title from the kanban store and
falls back to a greyed snapshot when the task isn't loaded
(cross-workspace, deleted, etc.). Adds a non-subscribing useTaskById
selector so badges don't fan out WS subscriptions per message.

* test(e2e): cover cross-task agent message attribution

Eight scenarios driven through the mock-agent's MCP script directive:
queue path, prompt path, self-message rejection, unknown-target error,
badge link target, live title re-resolution after rename, kandev-system
wrapper preservation in raw_content, and prompt bodies containing their
own kandev-system tags. Adds an updateTaskTitle helper to ApiClient.

* fix: address CodeRabbit + Greptile P1 findings on PR #819

- requeueMessage now forwards queuedMsg.Metadata via QueueMessageWithMetadata
  so sender attribution survives transient delivery failures and retries.
- CREATED-session branch in handleMessageTask records the user message AFTER
  StartCreatedSession succeeds, so a launch failure no longer leaves an
  orphaned attributed chat row.
- SenderTaskBadge: collapse identical displayTitle/fullTitle locals.
- E2E: extract waitForTargetIdle helper; replace the 1.5s raw sleep in the
  collision-check test with the same poll the rest of the suite uses.

* fix: address Claude review suggestions on PR #819

- wrapAgentMessage strips </kandev-system> from the embedded sender title
  before formatting. Without this, a title containing the closing tag
  would short-circuit the non-greedy strip regex and leak the attribution
  tail into the visible UI bubble. Metadata snapshot keeps the original
  title so the badge still displays it.
- Add a regression test covering the malicious-title case.
- Document the deliberate cross-workspace messaging policy on the sender
  lookup so future readers don't add a workspace-scope check (Q13 of the
  feature plan locked this as intentional).
This commit is contained in:
José Almeida
2026-05-04 19:30:10 +01:00
committed by GitHub
parent cb0feea650
commit a4e0fc0452
16 changed files with 1119 additions and 86 deletions
@@ -0,0 +1,133 @@
import { describe, expect, it } from "vitest";
import type { ReactNode } from "react";
import { render } from "@testing-library/react";
import { StateProvider } from "@/components/state-provider";
import { ChatMessage } from "./chat-message";
import type { Message } from "@/lib/types/http";
const SENDER_TASK_ID = "task-sender";
const SENDER_TITLE = "Fix login bug";
const SENDER_BADGE_SELECTOR = "[data-testid='sender-task-badge']";
function userMessage(overrides: Partial<Message>): Message {
return {
id: "msg-1",
session_id: "sess-1",
task_id: "task-target",
author_type: "user",
content: "hello",
type: "message",
created_at: "2026-05-04T00:00:00Z",
...overrides,
};
}
function wrapper(tasks: Array<{ id: string; title: string }> = []) {
return function Wrapper({ children }: { children: ReactNode }) {
return (
<StateProvider
initialState={{
// Seed the kanban slice so useTaskById can resolve sender tasks for
// live-title resolution; tests that exercise the deleted-sender
// fallback simply omit the sender from this list.
// The full Task shape isn't required by useTaskById — only id+title.
kanban: {
tasks: tasks.map((t) => ({
id: t.id,
title: t.title,
workflow_step_id: "",
priority: 0,
parent_id: undefined,
})),
} as unknown as never,
}}
>
{children}
</StateProvider>
);
};
}
function renderWithSender(
tasks: Array<{ id: string; title: string }>,
metadata: Partial<Message["metadata"] & object>,
) {
const Wrapper = wrapper(tasks);
return render(
<Wrapper>
<ChatMessage comment={userMessage({ metadata })} label="Message" className="" />
</Wrapper>,
);
}
describe("ChatMessage sender badge", () => {
it("renders the sender badge when sender_task_id is present in metadata", () => {
const { container } = renderWithSender([{ id: SENDER_TASK_ID, title: SENDER_TITLE }], {
sender_task_id: SENDER_TASK_ID,
sender_task_title: SENDER_TITLE,
sender_session_id: "sender-sess",
});
const badge = container.querySelector(SENDER_BADGE_SELECTOR);
expect(badge).not.toBeNull();
expect(badge?.getAttribute("data-sender-task-id")).toBe(SENDER_TASK_ID);
expect(badge?.textContent).toContain(SENDER_TITLE);
});
it("links the badge to the source task when the sender is loaded", () => {
const { container } = renderWithSender([{ id: SENDER_TASK_ID, title: SENDER_TITLE }], {
sender_task_id: SENDER_TASK_ID,
sender_task_title: SENDER_TITLE,
});
const link = container.querySelector(`a[href='/t/${SENDER_TASK_ID}']`);
expect(link).not.toBeNull();
});
it("renders a non-clickable greyed badge when sender task is unknown", () => {
// No tasks seeded — sender task is "deleted" or cross-workspace.
const { container } = renderWithSender([], {
sender_task_id: "task-deleted",
sender_task_title: "Old title",
});
const badge = container.querySelector(SENDER_BADGE_SELECTOR);
expect(badge).not.toBeNull();
expect(container.querySelector("a[href='/t/task-deleted']")).toBeNull();
// Falls back to the snapshotted title rather than blanking the badge.
expect(badge?.textContent).toContain("Old title");
});
it("uses the live title when it differs from the snapshot", () => {
// The badge re-resolves the title from the kanban store so renames are
// reflected without re-sending the message.
const { container } = renderWithSender([{ id: SENDER_TASK_ID, title: "Renamed task" }], {
sender_task_id: SENDER_TASK_ID,
sender_task_title: "Old name",
});
const badge = container.querySelector(SENDER_BADGE_SELECTOR);
expect(badge?.textContent).toContain("Renamed task");
expect(badge?.textContent).not.toContain("Old name");
});
it("truncates very long titles for display", () => {
const longTitle = "This is a really long task title that should be truncated";
const { container } = renderWithSender([{ id: SENDER_TASK_ID, title: longTitle }], {
sender_task_id: SENDER_TASK_ID,
sender_task_title: longTitle,
});
const badge = container.querySelector(SENDER_BADGE_SELECTOR);
expect(badge).not.toBeNull();
// The badge text must contain the ellipsis (truncated) and not the full title.
expect(badge?.textContent).toContain("…");
expect(badge?.textContent ?? "").not.toContain(longTitle);
});
it("does not render a sender badge when metadata has no sender_task_id", () => {
const { container } = renderWithSender([], { plan_mode: true });
expect(container.querySelector(SENDER_BADGE_SELECTOR)).toBeNull();
});
});
@@ -1,13 +1,17 @@
"use client";
import { memo, useState, useCallback } from "react";
import Link from "next/link";
import ReactMarkdown from "react-markdown";
import { IconWand, IconMessageDots, IconFile } from "@tabler/icons-react";
import { IconWand, IconMessageDots, IconFile, IconRobot } from "@tabler/icons-react";
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@kandev/ui/tooltip";
import { cn } from "@/lib/utils";
import type { Message } from "@/lib/types/http";
import { RichBlocks } from "@/components/task/chat/messages/rich-blocks";
import { MessageActions } from "@/components/task/chat/messages/message-actions";
import { useMessageNavigation } from "@/hooks/use-message-navigation";
import { useTaskById } from "@/hooks/domains/kanban/use-task-by-id";
import { linkToTask } from "@/lib/links";
import { markdownComponents, remarkPlugins } from "@/components/shared/markdown-components";
type ChatMessageProps = {
@@ -104,6 +108,16 @@ type UserMessageMetadata = {
has_review_comments?: boolean;
has_hidden_prompts?: boolean;
context_files?: Array<{ path: string; name: string }>;
sender_task_id?: string;
sender_task_title?: string;
sender_session_id?: string;
};
type SenderTaskInfo = {
id: string;
// Snapshot title captured when the message was sent. May differ from the
// task's current title; used as a fallback when the live task isn't loaded.
snapshotTitle: string;
};
function parseUserMessageMetadata(comment: Message) {
@@ -116,6 +130,9 @@ function parseUserMessageMetadata(comment: Message) {
const hasHiddenPrompts = !!metadata?.has_hidden_prompts;
const hasContent = !!(comment.content && comment.content.trim() !== "");
const hasAttachments = imageAttachments.length > 0 || fileAttachments.length > 0;
const senderTask: SenderTaskInfo | null = metadata?.sender_task_id
? { id: metadata.sender_task_id, snapshotTitle: metadata.sender_task_title || "" }
: null;
return {
imageAttachments,
fileAttachments,
@@ -125,21 +142,76 @@ function parseUserMessageMetadata(comment: Message) {
hasHiddenPrompts,
hasContent,
hasAttachments,
senderTask,
};
}
const SENDER_TITLE_MAX = 24;
function truncateTitle(title: string): string {
if (title.length <= SENDER_TITLE_MAX) return title;
return title.slice(0, SENDER_TITLE_MAX - 1).trimEnd() + "…";
}
function SenderTaskBadge({ sender }: { sender: SenderTaskInfo }) {
// Live-resolve the sender task from the loaded kanban state so the badge
// reflects renames. When the sender task isn't loaded (cross-workspace,
// archived, etc.) we fall back to the snapshot title and render a static,
// non-clickable greyed-out badge — the source URL only works when we have
// routing context.
const liveTask = useTaskById(sender.id);
const fullTitle = liveTask?.title || sender.snapshotTitle || "(unknown task)";
const truncated = truncateTitle(fullTitle);
const inner = (
<span
className={cn(
"inline-flex items-center gap-1.5 rounded-full bg-purple-500/20 px-2.5 py-1 text-xs font-medium text-purple-300",
liveTask && "cursor-pointer hover:bg-purple-500/30 transition-colors",
!liveTask && "opacity-60",
)}
data-testid="sender-task-badge"
data-sender-task-id={sender.id}
>
<IconRobot size={14} /> {truncated}
</span>
);
const wrapped = liveTask ? (
<Link href={linkToTask(sender.id)} aria-label={`Open source task ${fullTitle}`}>
{inner}
</Link>
) : (
inner
);
return (
<TooltipProvider delayDuration={300}>
<Tooltip>
<TooltipTrigger asChild>{wrapped}</TooltipTrigger>
<TooltipContent>
From agent in task <span className="font-semibold">&ldquo;{fullTitle}&rdquo;</span>
</TooltipContent>
</Tooltip>
</TooltipProvider>
);
}
function UserContextBadges({
hasPlanMode,
hasReviewComments,
contextFiles,
senderTask,
}: {
hasPlanMode: boolean;
hasReviewComments: boolean;
contextFiles: Array<{ path: string; name: string }>;
senderTask: SenderTaskInfo | null;
}) {
if (!hasPlanMode && !hasReviewComments && contextFiles.length === 0) return null;
if (!hasPlanMode && !hasReviewComments && contextFiles.length === 0 && !senderTask) return null;
return (
<div className="flex justify-end gap-1.5 mb-1 flex-wrap">
{senderTask && <SenderTaskBadge sender={senderTask} />}
{hasPlanMode && (
<span className="inline-flex items-center gap-1 rounded-full bg-slate-500/20 px-2 py-0.5 text-[10px] text-slate-400">
<IconWand size={10} /> Plan mode
@@ -188,6 +260,7 @@ function UserMessageContent({
hasHiddenPrompts,
hasContent,
hasAttachments,
senderTask,
} = parseUserMessageMetadata(comment);
return (
@@ -197,6 +270,7 @@ function UserMessageContent({
hasPlanMode={hasPlanMode}
hasReviewComments={hasReviewComments}
contextFiles={contextFiles}
senderTask={senderTask}
/>
<div className="rounded-2xl bg-primary/30 px-4 py-2.5 overflow-hidden">
{hasAttachments && (