Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
175 changes: 169 additions & 6 deletions apps/web/src/pages/ProjectGroupPage.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useEffect, useMemo, useRef, useState, type FormEvent } from "react";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type FormEvent } from "react";
import { flushSync } from "react-dom";
import { api } from "../api";
import { Link } from "../router";
Expand All @@ -7,9 +7,58 @@ import type { Agent, ProjectGroupMessage } from "../types";
import { EmptyState, ErrorState, Icon, LoadingPanel, PageHeader, Spinner, StatePill, formatTime, shortId } from "../ui";
import {
MAX_PROJECT_GROUP_MESSAGE_LENGTH,
filterProjectGroupMentionTargets,
findProjectGroupMentionCandidates,
prependProjectGroupMentionWithinLimit,
replaceProjectGroupMentionQuery,
type ProjectGroupMentionTarget,
} from "./project-group-mention";

const MENTION_SUGGESTIONS_ID = "group-message-mention-suggestions";
const SCROLL_PINNED_TOLERANCE = 24;

function isPinnedToMessageEnd(element: HTMLElement): boolean {
return element.scrollHeight - element.scrollTop - element.clientHeight <= SCROLL_PINNED_TOLERANCE;
}

function projectGroupMessageSnapshot(message: ProjectGroupMessage): string {
return JSON.stringify([
message.id,
message.projectId,
message.missionId,
message.senderType,
message.senderId,
message.content,
message.targetAgentId,
message.contractId,
message.contractAssignment ?? null,
message.createdAt,
]);
}

export function projectGroupMessagesMatch(
current: readonly ProjectGroupMessage[],
next: readonly ProjectGroupMessage[],
): boolean {
return current.length === next.length && current.every((message, index) => {
const candidate = next[index];
return candidate !== undefined && projectGroupMessageSnapshot(message) === projectGroupMessageSnapshot(candidate);
});
}

export function resolveProjectGroupMessageRefresh(
current: ProjectGroupMessage[],
next: ProjectGroupMessage[],
options: { pinnedToMessageEnd: boolean; followAfterSend: boolean },
): { messages: ProjectGroupMessage[]; shouldFollowMessageEnd: boolean } {
const changed = !projectGroupMessagesMatch(current, next);
return {
messages: changed ? next : current,
shouldFollowMessageEnd: options.followAfterSend
|| (changed && (current.length === 0 || options.pinnedToMessageEnd)),
};
}

function senderName(message: ProjectGroupMessage, agents: Agent[]): string {
if (message.senderType === "human") return "You";
if (message.senderType === "shepherd") return "Shepherd";
Expand Down Expand Up @@ -56,11 +105,25 @@ export function ProjectGroupPage({ agents }: { agents: Agent[] }) {
const [composerError, setComposerError] = useState<string | null>(null);
const [sending, setSending] = useState(false);
const [initializing, setInitializing] = useState(false);
const [mentionCursor, setMentionCursor] = useState(0);
const [mentionActiveIndex, setMentionActiveIndex] = useState(0);
const [mentionDismissed, setMentionDismissed] = useState(false);
const messagesPane = useRef<HTMLDivElement>(null);
const messageEnd = useRef<HTMLDivElement>(null);
const mentionSuggestions = useRef<HTMLDivElement>(null);
const messageComposer = useRef<HTMLTextAreaElement>(null);
const inFlight = useRef(false);
const scrollToMessageEndOnChange = useRef(true);
const scrollAfterSend = useRef(false);

const callableAgents = useMemo(() => filterProjectGroupMentionTargets(agents), [agents]);
const mentionCandidates = useMemo(
() => findProjectGroupMentionCandidates(content, mentionCursor, callableAgents),
[callableAgents, content, mentionCursor],
);
const showMentionSuggestions = Boolean(project) && !sending && !mentionDismissed && mentionCandidates.length > 0;

const insertMention = (agent: Agent) => {
const insertMention = (agent: ProjectGroupMentionTarget) => {
if (sending) return;
const nextContent = prependProjectGroupMentionWithinLimit(agent.name, agent.id, content);
flushSync(() => {
Expand All @@ -69,6 +132,8 @@ export function ProjectGroupPage({ agents }: { agents: Agent[] }) {
} else {
setComposerError(null);
setContent(nextContent);
setMentionCursor(nextContent.length);
setMentionDismissed(false);
}
});
const composer = messageComposer.current;
Expand All @@ -82,7 +147,23 @@ export function ProjectGroupPage({ agents }: { agents: Agent[] }) {
inFlight.current = true;
try {
const result = await api.groupMessages(project.id);
setMessages(result.messages);
const pinnedToMessageEnd = messagesPane.current
? isPinnedToMessageEnd(messagesPane.current)
: true;
const followAfterSend = scrollAfterSend.current;
scrollAfterSend.current = false;
setMessages((current) => {
const refresh = resolveProjectGroupMessageRefresh(current, result.messages, {
pinnedToMessageEnd,
followAfterSend,
});
if (refresh.messages === current) return current;
scrollToMessageEndOnChange.current = refresh.shouldFollowMessageEnd;
return refresh.messages;
});
if (followAfterSend) {
window.requestAnimationFrame(() => messageEnd.current?.scrollIntoView({ block: "nearest" }));
}
setMessageError(null);
} catch (reason) {
setMessageError(reason instanceof Error ? reason.message : "Project Group is unavailable");
Expand All @@ -103,10 +184,41 @@ export function ProjectGroupPage({ agents }: { agents: Agent[] }) {
return () => window.clearInterval(interval);
}, [project, refreshMessages]);

useEffect(() => {
useLayoutEffect(() => {
if (!scrollToMessageEndOnChange.current) return;
messageEnd.current?.scrollIntoView({ block: "nearest" });
scrollToMessageEndOnChange.current = false;
}, [messages]);

useEffect(() => {
setMentionActiveIndex(0);
}, [content, mentionCursor]);

useEffect(() => {
if (!showMentionSuggestions) return;
mentionSuggestions.current
?.querySelector<HTMLElement>('[role="option"][aria-selected="true"]')
?.scrollIntoView({ block: "nearest" });
}, [mentionActiveIndex, mentionCandidates, showMentionSuggestions]);

const selectMention = (agent: ProjectGroupMentionTarget) => {
const next = replaceProjectGroupMentionQuery(content, mentionCursor, agent);
if (!next) {
setComposerError("Mention would exceed the 2,000-character message limit.");
return;
}
flushSync(() => {
setContent(next.content);
setMentionCursor(next.selectionStart);
setMentionDismissed(true);
setComposerError(null);
});
const composer = messageComposer.current;
if (!composer) return;
composer.focus();
composer.setSelectionRange(next.selectionStart, next.selectionStart);
};

const initializeGroup = async () => {
if (initializing) return;
setInitializing(true);
Expand Down Expand Up @@ -139,6 +251,9 @@ export function ProjectGroupPage({ agents }: { agents: Agent[] }) {
...(nextContent.startsWith("@") ? { assignmentPreset: "auth-demo-contract" as const } : {}),
});
setContent("");
setMentionCursor(0);
setMentionDismissed(false);
scrollAfterSend.current = true;
await Promise.all([refreshMessages(), refreshState()]);
} catch (reason) {
setMessageError(reason instanceof Error ? reason.message : "Message could not be routed");
Expand All @@ -160,7 +275,7 @@ export function ProjectGroupPage({ agents }: { agents: Agent[] }) {
<section className="group-chat-panel" aria-label="Project Group conversation">
<div className="group-members" aria-label="Available mention targets">
<span>Route directly:</span>
{agents.map((agent) => (
{callableAgents.map((agent) => (
<ProjectGroupMentionButton
key={agent.id}
agentName={agent.name}
Expand All @@ -172,7 +287,7 @@ export function ProjectGroupPage({ agents }: { agents: Agent[] }) {
{messageError ? (
<div className="reconnect-banner" role="status">{messageError} · retrying automatically</div>
) : null}
<div className="group-messages" aria-live="polite">
<div className="group-messages" ref={messagesPane} aria-live="polite">
{messagesLoading && messages.length === 0 ? <LoadingPanel label="Loading real group messages…" /> : null}
{!messagesLoading && sortedMessages.length === 0 ? (
<EmptyState
Expand Down Expand Up @@ -215,9 +330,36 @@ export function ProjectGroupPage({ agents }: { agents: Agent[] }) {
value={content}
onChange={(event) => {
setContent(event.target.value);
setMentionCursor(event.target.selectionStart);
setMentionDismissed(false);
setComposerError(null);
}}
onSelect={(event) => setMentionCursor(event.currentTarget.selectionStart)}
onKeyUp={(event) => setMentionCursor(event.currentTarget.selectionStart)}
onKeyDown={(event) => {
if (showMentionSuggestions) {
if (event.key === "ArrowDown") {
event.preventDefault();
setMentionActiveIndex((current) => Math.min(current + 1, mentionCandidates.length - 1));
return;
}
if (event.key === "ArrowUp") {
event.preventDefault();
setMentionActiveIndex((current) => Math.max(current - 1, 0));
return;
}
if (event.key === "Escape") {
event.preventDefault();
setMentionDismissed(true);
return;
}
if (event.key === "Enter" || event.key === "Tab") {
event.preventDefault();
const agent = mentionCandidates[mentionActiveIndex];
if (agent) selectMention(agent);
return;
}
Comment on lines +356 to +361
}
if (event.key === "Enter" && !event.shiftKey) {
event.preventDefault();
event.currentTarget.form?.requestSubmit();
Expand All @@ -227,7 +369,28 @@ export function ProjectGroupPage({ agents }: { agents: Agent[] }) {
disabled={!project || sending}
maxLength={MAX_PROJECT_GROUP_MESSAGE_LENGTH}
aria-describedby={composerError ? "group-message-error" : undefined}
aria-autocomplete="list"
aria-controls={showMentionSuggestions ? MENTION_SUGGESTIONS_ID : undefined}
aria-expanded={showMentionSuggestions}
aria-activedescendant={showMentionSuggestions ? `${MENTION_SUGGESTIONS_ID}-${mentionActiveIndex}` : undefined}
/>
{showMentionSuggestions ? (
<div ref={mentionSuggestions} className="group-mention-suggestions" id={MENTION_SUGGESTIONS_ID} role="listbox" aria-label="Agent mentions">
{mentionCandidates.map((agent, index) => (
<button
id={`${MENTION_SUGGESTIONS_ID}-${index}`}
key={agent.id}
type="button"
role="option"
aria-selected={index === mentionActiveIndex}
onMouseDown={(event) => event.preventDefault()}
onClick={() => selectMention(agent)}
Comment on lines +380 to +387
>
@{agent.name}
</button>
))}
</div>
) : null}
<div>
<span id={composerError ? "group-message-error" : undefined} role={composerError ? "status" : undefined}>
{composerError ?? "Unmentioned → Shepherd · @AgentName → targeted contract"}
Expand Down
99 changes: 98 additions & 1 deletion apps/web/src/pages/project-group-mention.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,20 @@ import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
import { parseProjectGroupMessage } from "../../../server/src/shepherd/group-routing.js";
import { InitializeProjectGroupButton, ProjectGroupMentionButton } from "./ProjectGroupPage.js";
import {
InitializeProjectGroupButton,
ProjectGroupMentionButton,
projectGroupMessagesMatch,
resolveProjectGroupMessageRefresh,
} from "./ProjectGroupPage.js";
import {
filterProjectGroupMentionTargets,
findProjectGroupMentionCandidates,
MAX_PROJECT_GROUP_MESSAGE_LENGTH,
formatProjectGroupMention,
prependProjectGroupMention,
prependProjectGroupMentionWithinLimit,
replaceProjectGroupMentionQuery,
} from "./project-group-mention.js";

describe("formatProjectGroupMention", () => {
Expand Down Expand Up @@ -89,6 +97,95 @@ describe("prependProjectGroupMention", () => {
});
});

describe("typed Project Group mentions", () => {
const agents = [
{ id: "agent-frontend", name: "Frontend Agent", role: "Frontend" as const, status: "ready" as const, currentContractId: null },
{ id: "agent-backend", name: "Backend Agent", role: "Backend" as const, status: "ready" as const, currentContractId: null },
{ id: "agent-general", name: "Generalist", role: "Generalist" as const, status: "ready" as const, currentContractId: null },
];

it("shows every callable Agent after a leading at-sign and filters a partial name prefix", () => {
expect(findProjectGroupMentionCandidates("@", 1, agents)).toEqual([agents[0], agents[1]]);
expect(findProjectGroupMentionCandidates("@f", 2, agents)).toEqual([agents[0]]);
});

it("filters typed mentions by visible Agent name rather than an opaque matching ID", () => {
const opaqueIdMatch = { id: "f-random-uuid", name: "Group Frontend", role: "Frontend" as const, status: "ready" as const, currentContractId: null };
expect(findProjectGroupMentionCandidates("@F", 2, [...agents, opaqueIdMatch])).toEqual([agents[0]]);
});

it("keeps only ready uncontracted Frontend and Backend Agents callable", () => {
const unsetContract = { ...agents[0], id: "agent-unset-contract", name: "Unset Contract", currentContractId: undefined };
expect(filterProjectGroupMentionTargets([
agents[0],
agents[1],
unsetContract,
agents[2],
{ ...agents[0], id: "agent-verification", name: "Verification", role: "Verification" as const },
{ ...agents[0], id: "agent-stopped", name: "Stopped", status: "stopped" as const },
{ ...agents[0], id: "agent-busy", name: "Busy", status: "busy" as const },
{ ...agents[0], id: "agent-error", name: "Error", status: "error" as const },
{ ...agents[0], id: "agent-contracted", name: "Contracted", currentContractId: "contract-1" },
])).toEqual([agents[0], agents[1], unsetContract]);
});

it("replaces the active leading partial mention with parser-safe syntax and retains the draft", () => {
expect(replaceProjectGroupMentionQuery("@F finish the form", 2, agents[0])).toEqual({
content: '@"Frontend Agent" finish the form',
selectionStart: '@"Frontend Agent" '.length,
});
});

it("accepts an exact-length expanded mention and rejects one character over the composer limit", () => {
const formattedMention = '@"Frontend Agent" ';
const exactDraft = "x".repeat(MAX_PROJECT_GROUP_MESSAGE_LENGTH - formattedMention.length);
expect(replaceProjectGroupMentionQuery(`@F ${exactDraft}`, 2, agents[0])).toEqual({
content: `${formattedMention}${exactDraft}`,
selectionStart: formattedMention.length,
});
expect(replaceProjectGroupMentionQuery(`@F ${exactDraft}x`, 2, agents[0])).toBeNull();
});

it("does not suggest an Agent mention outside the leading routing directive", () => {
expect(findProjectGroupMentionCandidates("Ask @F for help", 6, agents)).toEqual([]);
});
});

describe("Project Group message refresh", () => {
const message = {
id: "group-message",
projectId: "auth-demo",
missionId: null,
senderType: "human" as const,
senderId: null,
content: "use a bearer JWT",
targetAgentId: "agent-backend",
contractId: null,
createdAt: "2026-09-01T00:00:00.000Z",
};

it("treats a same-ID message with a completed Contract binding as a changed snapshot", () => {
expect(projectGroupMessagesMatch([message], [{ ...message, contractId: "contract-backend" }])).toBe(false);
});

it("consumes a send-follow request even when the fetched snapshot is unchanged", () => {
const currentMessages = [message];
const afterSend = resolveProjectGroupMessageRefresh(currentMessages, [message], {
pinnedToMessageEnd: false,
followAfterSend: true,
});
expect(afterSend.messages).toBe(currentMessages);
expect(afterSend.shouldFollowMessageEnd).toBe(true);

const laterAppend = resolveProjectGroupMessageRefresh(
[message],
[...[message], { ...message, id: "other-message" }],
{ pinnedToMessageEnd: false, followAfterSend: false },
);
expect(laterAppend.shouldFollowMessageEnd).toBe(false);
});
});

describe("ProjectGroupMentionButton", () => {
it("is natively disabled while a message submission is in flight", () => {
const markup = renderToStaticMarkup(
Expand Down
Loading