feat: add cross-integration entity references (#1862)

* feat: add cross-integration entity references

* fix(web): anchor entity reference menu to composer

* fix: keep Kandev tasks under @ mentions

* fix: address entity reference review findings

* test(e2e): use option role for prompt menu

* test(e2e): update passthrough mention roles

* fix: preserve queued references and paginate Azure PRs
This commit is contained in:
José Almeida
2026-07-23 09:03:56 +01:00
committed by GitHub
parent 67507c9273
commit 7de788ceed
171 changed files with 15719 additions and 507 deletions
@@ -114,7 +114,7 @@ describe("useSubmitHandler", () => {
const { result } = renderHook(() => useSubmitHandler(panelState()));
await act(async () => {
await result.current.handleSubmit("hello");
await result.current.handleSubmit({ message: "hello" });
});
expect(toastMock).toHaveBeenCalledWith({
@@ -135,7 +135,7 @@ describe("useSubmitHandler", () => {
const { result } = renderHook(() => useSubmitHandler(panelState()));
await act(async () => {
await result.current.handleSubmit("hello");
await result.current.handleSubmit({ message: "hello" });
});
expect(toastMock).toHaveBeenCalledWith({
@@ -159,7 +159,7 @@ describe("useSubmitHandler", () => {
);
await act(async () => {
await result.current.handleSubmit("hello");
await result.current.handleSubmit({ message: "hello" });
});
expect(markCommentsSent).not.toHaveBeenCalled();
@@ -182,10 +182,10 @@ describe("useSubmitHandler", () => {
);
await act(async () => {
await result.current.handleSubmit("hello");
await result.current.handleSubmit({ message: "hello" });
});
const [sentMessage] = handleSendMessageMock.mock.calls[0] as [string];
const [{ message: sentMessage }] = handleSendMessageMock.mock.calls[0] as [{ message: string }];
expect(sentMessage.match(/### Agent Message Comments/g)).toHaveLength(1);
expect(sentMessage).toContain("> settled answer");
expect(sentMessage).toContain("> Please expand this.");
@@ -14,13 +14,11 @@ import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut";
import { useMessageHandler, buildTaskMentionsContext } from "@/hooks/use-message-handler";
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
import { getShortcut } from "@/lib/keyboard/shortcut-overrides";
import { type ContextFile } from "@/lib/state/context-files-store";
import type { TaskMentionData } from "@/hooks/use-inline-mention";
import {
ChatInputContainer,
type ChatSubmitPayload,
type ChatSubmitResult,
type ChatInputContainerHandle,
type MessageAttachment,
} from "@/components/task/chat/chat-input-container";
import { QueueAffordance } from "@/components/task/chat/queued-ghost-list";
import {
@@ -38,6 +36,7 @@ import type { DiffComment } from "@/lib/diff/types";
import type { AgentMessageComment } from "@/lib/state/slices/comments";
import type { useChatPanelState } from "./use-chat-panel-state";
import { cn } from "@/lib/utils";
import { resolveComposerWorkspaceId } from "./composer-workspace";
const PLAN_CONTEXT_PATH = "plan:context";
@@ -163,7 +162,7 @@ function usePanelMessageHandler(panelState: ReturnType<typeof useChatPanelState>
export function useSubmitHandler(
panelState: ReturnType<typeof useChatPanelState>,
onSend?: (message: string) => void,
onSend?: (payload: ChatSubmitPayload) => ChatSubmitResult,
) {
const [isSending, setIsSending] = useState(false);
const storeApi = useAppStoreApi();
@@ -185,42 +184,30 @@ export function useSubmitHandler(
const { handleSendMessage } = usePanelMessageHandler(panelState);
const handleSubmit = useCallback(
async (
message: string,
reviewComments?: DiffComment[],
attachments?: MessageAttachment[],
inlineMentions?: ContextFile[],
inlineTaskMentions?: TaskMentionData[],
) => {
async (payload: ChatSubmitPayload) => {
if (isSending) return;
setIsSending(true);
try {
const finalMessage = buildSubmitMessage({
message,
reviewComments,
message: payload.message,
reviewComments: payload.reviewComments,
pendingPRFeedback,
planComments,
walkthroughComments,
messageComments,
});
const hasReviewComments = !!(reviewComments && reviewComments.length > 0);
const outbound = { ...payload, message: finalMessage };
if (onSend) {
// Expand task mentions because onSend bypasses useMessageHandler.buildFinalMessage.
const taskCtx = inlineTaskMentions?.length
? buildTaskMentionsContext(inlineTaskMentions, storeApi.getState())
const taskCtx = payload.inlineTaskMentions?.length
? buildTaskMentionsContext(payload.inlineTaskMentions, storeApi.getState())
: "";
await onSend(finalMessage + taskCtx);
await onSend({ ...outbound, message: finalMessage + taskCtx });
} else {
await handleSendMessage(
finalMessage,
attachments,
hasReviewComments,
inlineMentions,
inlineTaskMentions,
);
await handleSendMessage(outbound);
}
if (reviewComments && reviewComments.length > 0)
markCommentsSent(reviewComments.map((c) => c.id));
if (payload.reviewComments && payload.reviewComments.length > 0)
markCommentsSent(payload.reviewComments.map((c) => c.id));
if (messageComments.length > 0) markCommentsSent(messageComments.map((c) => c.id));
if (pendingPRFeedback.length > 0) handleClearPRFeedback();
if (walkthroughComments.length > 0) handleClearWalkthroughComments();
@@ -380,13 +367,7 @@ type ChatInputAreaProps = {
chatInputRef: React.RefObject<ChatInputContainerHandle | null>;
clarificationKey: number;
onClarificationResolved: () => void;
handleSubmit: (
message: string,
reviewComments?: DiffComment[],
attachments?: MessageAttachment[],
inlineMentions?: ContextFile[],
inlineTaskMentions?: TaskMentionData[],
) => ChatSubmitResult;
handleSubmit: (payload: ChatSubmitPayload) => ChatSubmitResult;
handleCancelTurn: () => Promise<void>;
showRequestChangesTooltip: boolean;
onRequestChangesTooltipDismiss?: () => void;
@@ -408,6 +389,20 @@ function useExecutorUnavailable(taskId: string | null, sessionId: string | null)
};
}
function useComposerWorkspaceId(sessionId: string | null, taskId: string | null) {
return useAppStore((state) =>
resolveComposerWorkspaceId({
sessionId,
taskId,
quickChatSessions: state.quickChat.sessions,
activeWorkflowId: state.kanban.workflowId,
activeTasks: state.kanban.tasks,
snapshots: Object.values(state.kanbanMulti.snapshots),
workflows: state.workflows.items,
}),
);
}
function useChatInputDerived(
panelState: ReturnType<typeof useChatPanelState>,
chatInputRef: React.RefObject<ChatInputContainerHandle | null>,
@@ -452,8 +447,8 @@ export function ChatInputArea({
placeholderOverride,
surfaceClassName,
}: ChatInputAreaProps) {
const { resolvedSessionId, taskId, isAgentBusy, needsRecovery, planModeEnabled, todoItems } =
panelState;
const { resolvedSessionId, taskId, isAgentBusy, needsRecovery, planModeEnabled } = panelState;
const composerWorkspaceId = useComposerWorkspaceId(resolvedSessionId, taskId);
const sessionState = panelState.session?.state ?? null;
const canDrainQueue = sessionState === "WAITING_FOR_INPUT" || sessionState === "IDLE";
const { planActions, executor, placeholder } = useChatInputDerived(
@@ -472,7 +467,7 @@ export function ChatInputArea({
canDrain={canDrainQueue}
renderStatusBar={(queueChip) => (
<ChatStatusBar
todoItems={todoItems}
todoItems={panelState.todoItems}
taskId={taskId}
sessionId={resolvedSessionId}
sessionState={sessionState}
@@ -490,6 +485,8 @@ export function ChatInputArea({
onSubmit={handleSubmit}
sessionId={resolvedSessionId}
taskId={taskId}
workspaceId={composerWorkspaceId}
entityReferencesEnabled
taskTitle={panelState.task?.title}
taskDescription={panelState.taskDescription ?? ""}
planModeEnabled={planModeEnabled}
@@ -4,8 +4,13 @@ import { TooltipProvider } from "@kandev/ui/tooltip";
import { afterEach, describe, expect, it, vi } from "vitest";
import { ChatInputBody, type ChatInputBodyProps } from "./chat-input-body";
const tipTapPropsMock = vi.hoisted(() => vi.fn());
vi.mock("./tiptap-input", () => ({
TipTapInput: () => <div data-testid="mock-tiptap-input" />,
TipTapInput: (props: unknown) => {
tipTapPropsMock(props);
return <div data-testid="mock-tiptap-input" />;
},
}));
vi.mock("./chat-input-toolbar", () => ({
@@ -18,6 +23,7 @@ vi.mock("./context-items/context-zone", () => ({
afterEach(() => {
cleanup();
tipTapPropsMock.mockClear();
});
function props(overrides: Partial<ChatInputBodyProps> = {}): ChatInputBodyProps {
@@ -74,6 +80,18 @@ function props(overrides: Partial<ChatInputBodyProps> = {}): ChatInputBodyProps
}
describe("ChatInputBody", () => {
it("keeps entity references explicitly disabled unless the chat surface enables them", () => {
render(
<TooltipProvider>
<ChatInputBody {...props()} />
</TooltipProvider>,
);
expect(tipTapPropsMock).toHaveBeenCalledWith(
expect.objectContaining({ entityReferencesEnabled: false }),
);
});
it("reserves right-side editable space while the focus hint is visible", () => {
render(
<TooltipProvider>
@@ -28,6 +28,8 @@ export type ChatInputEditorAreaProps = {
setIsInputFocused: (focused: boolean) => void;
sessionId: string | null;
taskId: string | null;
workspaceId?: string | null;
entityReferencesEnabled?: boolean;
onAddContextFile?: (file: ContextFile) => void;
onToggleContextFile?: (file: ContextFile) => void;
planContextEnabled: boolean;
@@ -160,6 +162,8 @@ export function ChatInputEditorArea(p: ChatInputEditorAreaProps) {
onBlur={() => setIsInputFocused(false)}
sessionId={sessionId}
taskId={taskId}
workspaceId={p.workspaceId ?? null}
entityReferencesEnabled={p.entityReferencesEnabled ?? false}
onAddContextFile={onAddContextFile}
onToggleContextFile={onToggleContextFile}
planContextEnabled={planContextEnabled}
@@ -9,6 +9,8 @@ import { useAppStore } from "@/components/state-provider";
import type { ContextFile } from "@/lib/state/context-files-store";
import type { Message } from "@/lib/types/http";
import type { DiffComment } from "@/lib/diff/types";
import type { TaskMentionData } from "@/hooks/use-inline-mention";
import type { EntityReference } from "@/lib/types/entity-reference";
import { getWebSocketClient } from "@/lib/ws/connection";
import { useChatInputContainer } from "./use-chat-input-container";
import {
@@ -44,16 +46,21 @@ export type ChatInputContainerHandle = {
export type ChatSubmitResult = void | boolean | Promise<void | boolean>;
export type ChatSubmitPayload = {
message: string;
reviewComments?: DiffComment[];
attachments?: MessageAttachment[];
inlineMentions?: ContextFile[];
inlineTaskMentions?: TaskMentionData[];
entityReferences?: EntityReference[];
};
type ChatInputContainerProps = {
onSubmit: (
message: string,
reviewComments?: DiffComment[],
attachments?: MessageAttachment[],
inlineMentions?: ContextFile[],
inlineTaskMentions?: import("@/hooks/use-inline-mention").TaskMentionData[],
) => ChatSubmitResult;
onSubmit: (payload: ChatSubmitPayload) => ChatSubmitResult;
sessionId: string | null;
taskId: string | null;
workspaceId?: string | null;
entityReferencesEnabled?: boolean;
taskTitle?: string;
taskDescription: string;
planModeEnabled: boolean;
@@ -224,6 +231,7 @@ type NormalizedChatInputProps = ChatInputContainerProps & {
contextFiles: ContextFile[];
contextItems: ContextItem[];
showRequestChangesTooltip: boolean;
entityReferencesEnabled: boolean;
};
function normalizeChatInputProps(p: ChatInputContainerProps): NormalizedChatInputProps {
@@ -236,6 +244,7 @@ function normalizeChatInputProps(p: ChatInputContainerProps): NormalizedChatInpu
contextFiles: p.contextFiles ?? [],
contextItems: p.contextItems ?? [],
showRequestChangesTooltip: p.showRequestChangesTooltip ?? false,
entityReferencesEnabled: p.entityReferencesEnabled ?? false,
};
}
@@ -280,6 +289,8 @@ function buildEditorAreaProps(
setIsInputFocused: s.setIsInputFocused,
sessionId: p.sessionId,
taskId: p.taskId,
workspaceId: p.workspaceId ?? null,
entityReferencesEnabled: p.entityReferencesEnabled,
onAddContextFile: p.onAddContextFile,
onToggleContextFile: p.onToggleContextFile,
planContextEnabled: p.planContextEnabled,
@@ -0,0 +1,48 @@
import { describe, expect, it } from "vitest";
import { resolveComposerWorkspaceId } from "./composer-workspace";
const workflows = [{ id: "workflow-1", workspaceId: "workspace-1" }];
describe("resolveComposerWorkspaceId", () => {
it("uses the workspace persisted with a Quick Chat session", () => {
expect(
resolveComposerWorkspaceId({
sessionId: "quick-session",
taskId: null,
quickChatSessions: [{ sessionId: "quick-session", workspaceId: "quick-workspace" }],
activeWorkflowId: null,
activeTasks: [],
snapshots: [],
workflows,
}),
).toBe("quick-workspace");
});
it("maps a task through its loaded workflow", () => {
expect(
resolveComposerWorkspaceId({
sessionId: "task-session",
taskId: "task-1",
quickChatSessions: [],
activeWorkflowId: "workflow-1",
activeTasks: [{ id: "task-1" }],
snapshots: [],
workflows,
}),
).toBe("workspace-1");
});
it("fails closed when the task cannot be mapped to a workflow", () => {
expect(
resolveComposerWorkspaceId({
sessionId: "unknown-session",
taskId: "unknown-task",
quickChatSessions: [],
activeWorkflowId: "workflow-1",
activeTasks: [{ id: "another-task" }],
snapshots: [],
workflows,
}),
).toBeNull();
});
});
@@ -0,0 +1,26 @@
type TaskIdentity = { id: string };
type WorkflowIdentity = { id: string; workspaceId: string };
type QuickChatIdentity = { sessionId: string; workspaceId: string };
type WorkflowSnapshot = { workflowId: string; tasks: readonly TaskIdentity[] };
export function resolveComposerWorkspaceId(args: {
sessionId: string | null;
taskId: string | null;
quickChatSessions: readonly QuickChatIdentity[];
activeWorkflowId: string | null;
activeTasks: readonly TaskIdentity[];
snapshots: readonly WorkflowSnapshot[];
workflows: readonly WorkflowIdentity[];
}): string | null {
const quickChat = args.quickChatSessions.find((item) => item.sessionId === args.sessionId);
if (quickChat) return quickChat.workspaceId;
if (!args.taskId) return null;
const activeWorkflowOwnsTask = args.activeTasks.some((task) => task.id === args.taskId);
const workflowId = activeWorkflowOwnsTask
? args.activeWorkflowId
: (args.snapshots.find((snapshot) => snapshot.tasks.some((task) => task.id === args.taskId))
?.workflowId ?? null);
if (!workflowId) return null;
return args.workflows.find((workflow) => workflow.id === workflowId)?.workspaceId ?? null;
}
@@ -0,0 +1,21 @@
import type { EntityReference, EntityReferenceSearchGroup } from "@/lib/types/entity-reference";
export function visibleEntityReferenceGroups(
groups: readonly EntityReferenceSearchGroup[],
): EntityReferenceSearchGroup[] {
return groups.filter(
(group) =>
group.source !== "kandev_tasks" &&
group.status !== "not_configured" &&
group.status !== "unsupported_scope" &&
(group.status !== "ok" || group.results.length > 0),
);
}
export function selectableEntityReferences(
groups: readonly EntityReferenceSearchGroup[],
): EntityReference[] {
return visibleEntityReferenceGroups(groups).flatMap((group) =>
group.status === "ok" ? group.results : [],
);
}
@@ -0,0 +1,181 @@
import type { ComponentType } from "react";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { EntityReference, EntityReferenceSearchGroup } from "@/lib/types/entity-reference";
import * as entityReferenceMenus from "./entity-reference-menu";
afterEach(cleanup);
const unavailableSearchGroups: EntityReferenceSearchGroup[] = [
{
source: "gitlab_issues",
provider: "gitlab",
kind: "issue",
display_name: "GitLab",
kind_label: "Issue",
status: "unsupported_scope",
results: [],
},
{
source: "linear_issues",
provider: "linear",
kind: "issue",
display_name: "Linear",
kind_label: "Issue",
status: "not_configured",
results: [],
},
{
source: "github_issues",
provider: "github",
kind: "issue",
display_name: "GitHub",
kind_label: "Issue",
status: "timeout",
results: [],
},
];
const kandevTaskGroup: EntityReferenceSearchGroup = {
source: "kandev_tasks",
provider: "kandev",
kind: "task",
display_name: "Kandev tasks",
kind_label: "Task",
status: "ok",
results: [
{
version: 1,
ref: "mention:v1:kandev:task:workspace-1:task-1",
provider: "kandev",
kind: "task",
id: "task-1",
key: "",
title: "Existing task",
url: "/t/task-1",
scope: "workspace-1",
},
],
};
const githubIssueGroup: EntityReferenceSearchGroup = {
source: "github_issues",
provider: "github",
kind: "issue",
display_name: "GitHub",
kind_label: "Issue",
status: "ok",
results: [
{
version: 1,
ref: "mention:v1:github:issue:octo%2Frepo:7",
provider: "github",
kind: "issue",
id: "7",
key: "#7",
title: "External issue",
url: "https://github.com/octo/repo/issues/7",
scope: "octo/repo",
},
],
};
describe("EntityReferenceMenu", () => {
it("provides a menu distinct from @ context mentions", () => {
expect(typeof (entityReferenceMenus as Record<string, unknown>).EntityReferenceMenu).toBe(
"function",
);
});
it("renders descriptor-driven groups with a generic fallback and 44px touch rows", () => {
const reference: EntityReference = {
version: 1,
ref: "mention:v1:plugin:acme:incident:scope:incident-9",
provider: "plugin:acme:tracker",
kind: "incident",
id: "incident-9",
key: "INC-9",
title: "Authentication outage",
url: "https://tracker.example.test/incidents/9",
scope: "tracker.example.test/team-a",
};
const groups: EntityReferenceSearchGroup[] = [
{
source: "plugin:acme:incidents",
provider: reference.provider,
kind: reference.kind,
display_name: "Acme tracker",
kind_label: "Incident",
status: "ok",
results: [reference],
},
];
const onSelect = vi.fn();
const Menu = entityReferenceMenus.EntityReferenceMenu as unknown as ComponentType<{
isOpen: boolean;
clientRect: () => DOMRect;
groups: EntityReferenceSearchGroup[];
query: string;
selectedIndex: number;
isSearching: boolean;
error: null;
onRetry: () => void;
onSelect: (reference: EntityReference) => void;
onClose: () => void;
setSelectedIndex: (index: number) => void;
}>;
render(
<Menu
isOpen
clientRect={() => new DOMRect(16, 240, 1, 20)}
groups={groups}
query="auth"
selectedIndex={0}
isSearching={false}
error={null}
onRetry={vi.fn()}
onSelect={onSelect}
onClose={vi.fn()}
setSelectedIndex={vi.fn()}
/>,
);
expect(screen.getByText("Acme tracker")).toBeTruthy();
expect(screen.getByTestId("entity-reference-menu")).toBeTruthy();
expect(screen.getByText("Incident")).toBeTruthy();
expect(screen.getByTestId("entity-reference-generic-icon")).toBeTruthy();
const row = screen.getByRole("option", { name: /#INC-9.*Authentication outage/ });
expect(row.className).toContain("min-h-11");
fireEvent.click(row);
expect(onSelect).toHaveBeenCalledWith(reference);
});
it("omits sources that are not searchable in the active workspace", () => {
const visibleEntityReferenceGroups = (entityReferenceMenus as Record<string, unknown>)
.visibleEntityReferenceGroups;
expect(visibleEntityReferenceGroups).toBeTypeOf("function");
if (typeof visibleEntityReferenceGroups !== "function") return;
expect(
(visibleEntityReferenceGroups as (value: EntityReferenceSearchGroup[]) => unknown)(
unavailableSearchGroups,
),
).toEqual([unavailableSearchGroups[2]]);
});
it("keeps Kandev tasks out of # work item search", () => {
expect(entityReferenceMenus.visibleEntityReferenceGroups([kandevTaskGroup])).toEqual([]);
const selectableEntityReferences = (entityReferenceMenus as Record<string, unknown>)
.selectableEntityReferences;
expect(selectableEntityReferences).toBeTypeOf("function");
if (typeof selectableEntityReferences !== "function") return;
expect(
(selectableEntityReferences as (value: EntityReferenceSearchGroup[]) => unknown)([
kandevTaskGroup,
githubIssueGroup,
]),
).toEqual(githubIssueGroup.results);
});
});
@@ -0,0 +1,145 @@
"use client";
import { IconBug, IconClipboardList, IconGitPullRequest, IconLink } from "@tabler/icons-react";
import type { EntityReferenceSearchError } from "@/hooks/use-entity-reference-search";
import type {
EntityReference,
EntityReferenceGroupStatus,
EntityReferenceSearchGroup,
} from "@/lib/types/entity-reference";
import {
selectableEntityReferences,
visibleEntityReferenceGroups,
} from "./entity-reference-groups";
import { PopupMenu, PopupMenuItem, useMenuItemRefs } from "./popup-menu";
export {
selectableEntityReferences,
visibleEntityReferenceGroups,
} from "./entity-reference-groups";
type EntityReferenceMenuProps = {
isOpen: boolean;
clientRect?: (() => DOMRect | null) | null;
groups: EntityReferenceSearchGroup[];
query: string;
selectedIndex: number;
isSearching: boolean;
error: EntityReferenceSearchError | null;
onRetry: () => void;
onSelect: (reference: EntityReference) => void;
onClose: () => void;
setSelectedIndex: (index: number) => void;
};
const GROUP_STATUS_LABELS: Partial<Record<EntityReferenceGroupStatus, string>> = {
unauthorized: "Sign-in required",
rate_limited: "Temporarily rate limited",
timeout: "Search timed out",
upstream_error: "Provider unavailable",
unsupported_scope: "Unavailable for this workspace",
};
function entityReferenceIcon(kind: string) {
if (kind === "task") return <IconClipboardList className="h-4 w-4" />;
if (kind === "issue" || kind === "work_item") return <IconBug className="h-4 w-4" />;
if (kind === "pull_request" || kind === "merge_request") {
return <IconGitPullRequest className="h-4 w-4" />;
}
return <IconLink className="h-4 w-4" data-testid="entity-reference-generic-icon" />;
}
function entityReferenceEmptyState(
query: string,
isSearching: boolean,
error: EntityReferenceSearchError | null,
onRetry: () => void,
) {
if (!query.trim()) return "Type to search work items";
if (isSearching) return "Searching work items…";
if (error) {
return (
<div className="flex min-h-11 items-center justify-between gap-3 px-3 text-xs">
<span className="text-muted-foreground">{error.message}</span>
<button
type="button"
className="min-h-11 shrink-0 cursor-pointer px-2 font-medium text-primary"
onClick={onRetry}
>
Retry
</button>
</div>
);
}
return "No work items found";
}
export function EntityReferenceMenu({
isOpen,
clientRect,
groups,
query,
selectedIndex,
isSearching,
error,
onRetry,
onSelect,
onClose,
setSelectedIndex,
}: EntityReferenceMenuProps) {
const { setItemRef } = useMenuItemRefs(selectedIndex);
const selectable = selectableEntityReferences(groups);
let itemIndex = 0;
const visibleGroups = visibleEntityReferenceGroups(groups);
const hasContent = visibleGroups.length > 0;
return (
<PopupMenu
isOpen={isOpen}
testId="entity-reference-menu"
position={null}
clientRect={clientRect}
title="Reference work items"
selectedIndex={selectedIndex}
onClose={onClose}
hasItems={hasContent}
emptyState={
<div className="px-3 py-2 text-xs text-muted-foreground">
{entityReferenceEmptyState(query, isSearching, error, onRetry)}
</div>
}
>
{visibleGroups.map((group) => (
<div key={group.source} data-reference-group={group.source}>
<div className="flex items-center justify-between gap-2 px-3 py-1 text-[11px] text-muted-foreground">
<span className="truncate font-medium">{group.display_name}</span>
<span className="shrink-0">{group.kind_label}</span>
</div>
{group.status === "ok" ? (
group.results.map((reference) => {
const index = itemIndex++;
return (
<PopupMenuItem
key={reference.ref}
icon={entityReferenceIcon(group.kind)}
label={`#${reference.key || reference.title}`}
description={reference.title}
isSelected={selectedIndex === index}
onClick={() => onSelect(reference)}
onMouseEnter={() => setSelectedIndex(index)}
itemRef={setItemRef(index)}
/>
);
})
) : (
<div className="min-h-11 px-3 py-2 text-xs text-muted-foreground">
{GROUP_STATUS_LABELS[group.status] ?? "Provider unavailable"}
</div>
)}
</div>
))}
{isSearching && selectable.length > 0 && (
<div className="px-3 py-1 text-[11px] text-muted-foreground">Updating…</div>
)}
</PopupMenu>
);
}
@@ -2,12 +2,12 @@
import { useEffect, useMemo, useRef, useState } from "react";
import { createPortal } from "react-dom";
import { searchHistory, type SearchHit } from "./message-history";
import { searchHistory, type MessageHistoryEntry, type SearchHit } from "./message-history";
import { HitRow } from "./message-history-search-row";
type MessageHistorySearchProps = {
/** Newest-first list of the user's previous messages for this session. */
history: readonly string[];
history: readonly MessageHistoryEntry[];
/** True while older messages are still being paginated in from the backend
* (overlay-driven drain). The list updates live as more arrive. */
isLoadingOlder?: boolean;
@@ -30,7 +30,7 @@ function clampSelectedIndex(prev: number, hitCount: number): number {
return prev;
}
function useHits(history: readonly string[], query: string): SearchHit[] {
function useHits(history: readonly MessageHistoryEntry[], query: string): SearchHit[] {
return useMemo(() => searchHistory(history, query), [history, query]);
}
@@ -1,11 +1,13 @@
import { describe, expect, it } from "vitest";
import {
createMessageHistorySelector,
extractUserHistory,
navigateHistory,
fuzzyScore,
searchHistory,
type HistoryState,
} from "./message-history";
import * as messageHistory from "./message-history";
import type { Message } from "@/lib/types/http";
function msg(partial: Partial<Message>): Message {
@@ -21,6 +23,106 @@ function msg(partial: Partial<Message>): Message {
};
}
describe("createMessageHistorySelector", () => {
it("keeps the selector snapshot stable when only agent output changes", () => {
const selector = createMessageHistorySelector("s1");
const first = selector({
messages: {
bySession: { s1: [msg({ id: "user-1", content: "keep me" })] },
metaBySession: {},
},
});
const afterAgentStream = selector({
messages: {
bySession: {
s1: [
msg({ id: "user-1", content: "keep me" }),
msg({ id: "agent-1", author_type: "agent", content: "streaming" }),
],
},
metaBySession: {},
},
});
expect(afterAgentStream).toBe(first);
});
it("returns a new selector snapshot when reference metadata changes", () => {
const selector = createMessageHistorySelector("s1");
const reference = {
version: 1,
ref: "mention:v1:sentry:issue:sentry.example.test%2Forg-1:issue-1",
provider: "sentry",
kind: "issue",
id: "issue-1",
key: "WEB-1",
title: "Login crash",
url: "https://sentry.example.test/issues/1",
scope: "sentry.example.test/org-1",
};
const first = selector({
messages: {
bySession: {
s1: [msg({ id: "user-1", content: "See #WEB-1", metadata: { entity_references: [] } })],
},
metaBySession: {},
},
});
const withReference = selector({
messages: {
bySession: {
s1: [
msg({
id: "user-1",
content: "See #WEB-1",
metadata: { entity_references: [reference] },
}),
],
},
metaBySession: {},
},
});
expect(withReference).not.toBe(first);
expect(withReference[0]?.entityReferences).toEqual([reference]);
});
});
describe("extractUserHistoryEntries", () => {
it("provides structured history entries for rich-editor recall", () => {
expect(typeof (messageHistory as Record<string, unknown>).extractUserHistoryEntries).toBe(
"function",
);
});
it("keeps entity reference metadata with recalled message content", () => {
const reference = {
version: 1,
ref: "mention:v1:sentry:issue:sentry.example.test%2Forg-1:issue-1",
provider: "sentry",
kind: "issue",
id: "issue-1",
key: "WEB-1",
title: "Login crash",
url: "https://sentry.example.test/issues/1",
scope: "sentry.example.test/org-1",
};
const entries = messageHistory.extractUserHistoryEntries([
msg({
content: "See [#WEB-1](https://sentry.example.test/issues/1)",
metadata: { entity_references: [reference, reference] },
}),
]);
expect(entries).toEqual([
{
content: "See [#WEB-1](https://sentry.example.test/issues/1)",
entityReferences: [reference],
},
]);
});
});
describe("extractUserHistory", () => {
it("returns user message contents newest-first", () => {
const messages: Message[] = [
@@ -1,16 +1,54 @@
import type { Message } from "@/lib/types/http";
import type { EntityReference } from "@/lib/types/entity-reference";
import type { MessagesState } from "@/lib/state/slices/session/types";
import { entityReferencesFromMetadata } from "@/lib/entity-references/message-references";
/** Extract the user's previously sent text messages for a session, newest-first.
* Consecutive duplicates *in the original message stream* are collapsed —
* duplicates separated by an assistant or tool turn stay, since the user
* meaningfully repeated themselves and should be able to recall the older
* one from history. Empty/whitespace-only messages are skipped. */
export function extractUserHistory(messages: readonly Message[]): string[] {
const out: string[] = [];
export type MessageHistoryEntry = {
content: string;
entityReferences: EntityReference[];
};
type MessageHistoryStoreState = {
messages: MessagesState;
};
function sameEntityReference(left: EntityReference, right: EntityReference): boolean {
return (
left.version === right.version &&
left.ref === right.ref &&
left.provider === right.provider &&
left.kind === right.kind &&
left.id === right.id &&
left.key === right.key &&
left.title === right.title &&
left.url === right.url &&
left.scope === right.scope
);
}
function sameHistoryEntries(
left: readonly MessageHistoryEntry[],
right: readonly MessageHistoryEntry[],
): boolean {
if (left.length !== right.length) return false;
return left.every((entry, index) => {
const other = right[index];
return (
entry.content === other.content &&
entry.entityReferences.length === other.entityReferences.length &&
entry.entityReferences.every((reference, referenceIndex) =>
sameEntityReference(reference, other.entityReferences[referenceIndex]),
)
);
});
}
export function extractUserHistoryEntries(messages: readonly Message[]): MessageHistoryEntry[] {
const out: MessageHistoryEntry[] = [];
for (let i = messages.length - 1; i >= 0; i--) {
const m = messages[i];
if (m.author_type !== "user" || m.type !== "message") continue;
const content = m.content ?? "";
const message = messages[i];
if (message.author_type !== "user" || message.type !== "message") continue;
const content = message.content ?? "";
if (!content.trim()) continue;
const newer = messages[i + 1];
const isAdjacentUserDuplicate =
@@ -18,11 +56,34 @@ export function extractUserHistory(messages: readonly Message[]): string[] {
newer.type === "message" &&
(newer.content ?? "") === content;
if (isAdjacentUserDuplicate) continue;
out.push(content);
out.push({ content, entityReferences: entityReferencesFromMetadata(message.metadata) });
}
return out;
}
/** Build a Zustand selector whose result stays referentially stable while
* agent messages stream. React's external-store contract requires the same
* snapshot object when the derived user history has not changed. */
export function createMessageHistorySelector(sessionId: string | null) {
let previous: MessageHistoryEntry[] = [];
return (state: MessageHistoryStoreState): MessageHistoryEntry[] => {
const messages = sessionId ? state.messages.bySession[sessionId] : undefined;
const next = extractUserHistoryEntries(messages ?? []);
if (sameHistoryEntries(previous, next)) return previous;
previous = next;
return previous;
};
}
/** Extract the user's previously sent text messages for a session, newest-first.
* Consecutive duplicates *in the original message stream* are collapsed —
* duplicates separated by an assistant or tool turn stay, since the user
* meaningfully repeated themselves and should be able to recall the older
* one from history. Empty/whitespace-only messages are skipped. */
export function extractUserHistory(messages: readonly Message[]): string[] {
return extractUserHistoryEntries(messages).map((entry) => entry.content);
}
export type HistoryState = {
/** Position within the history list (0 = most recent). `null` means the user
* is currently editing their own draft, not viewing history. */
@@ -85,17 +146,29 @@ export type SearchHit = {
score: number;
};
function historyEntryContent(entry: string | MessageHistoryEntry): string {
return typeof entry === "string" ? entry : entry.content;
}
/** Score every history entry against `query` and return matches sorted
* best-first. An empty query returns every entry in newest-first order
* (preserving the original index). */
export function searchHistory(history: readonly string[], query: string): SearchHit[] {
export function searchHistory(
history: readonly (string | MessageHistoryEntry)[],
query: string,
): SearchHit[] {
if (!query) {
return history.map((content, index) => ({ index, content, score: 0 }));
return history.map((entry, index) => ({
index,
content: historyEntryContent(entry),
score: 0,
}));
}
const hits: SearchHit[] = [];
for (let i = 0; i < history.length; i++) {
const score = fuzzyScore(query, history[i]);
if (score !== null) hits.push({ index: i, content: history[i], score });
const content = historyEntryContent(history[i]);
const score = fuzzyScore(query, content);
if (score !== null) hits.push({ index: i, content, score });
}
hits.sort((a, b) => b.score - a.score);
return hits;
@@ -3,6 +3,8 @@ import type { ReactNode } from "react";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { StateProvider } from "@/components/state-provider";
import { ChatMessage } from "./chat-message";
import { entityReferenceMarkdown } from "@/lib/entity-references/message-references";
import type { EntityReference } from "@/lib/types/entity-reference";
import {
sessionId as toSessionId,
taskId as toTaskId,
@@ -22,6 +24,7 @@ const PNG_BASE64 =
const OPEN_ATTACHMENT_1_LABEL = "Open Attachment 1";
const FULL_SIZE_ATTACHMENT_1_ALT = "Full size Attachment 1";
const PROMPT_MENTION_TESTID = "custom-prompt-mention";
const ENTITY_REFERENCE_TESTID = "entity-reference-chip";
afterEach(() => {
cleanup();
@@ -52,6 +55,21 @@ function customPrompt(name: string): CustomPrompt {
};
}
function issueReference(overrides: Partial<EntityReference> = {}): EntityReference {
return {
version: 1,
ref: "mention:v1:jira:issue:https%3A%2F%2Fjira.example:10001",
provider: "jira",
kind: "issue",
id: "10001",
key: "ENG[1]",
title: "Fix the login flow",
url: "https://jira.example/browse/ENG-1?q=hello world(test)",
scope: "https://jira.example",
...overrides,
};
}
function wrapper(tasks: Array<{ id: string; title: string }> = [], prompts: CustomPrompt[] = []) {
return function Wrapper({ children }: { children: ReactNode }) {
return (
@@ -158,6 +176,74 @@ describe("ChatMessage prompt mentions", () => {
});
});
describe("ChatMessage entity references", () => {
it("renders an exact generated Markdown link as an accessible clickable chip", () => {
const reference = issueReference();
const Wrapper = wrapper();
render(
<Wrapper>
<ChatMessage
comment={userMessage({
content: entityReferenceMarkdown(reference),
metadata: { entity_references: [reference] },
})}
label="Message"
className=""
onOpenFile={vi.fn()}
/>
</Wrapper>,
);
const chip = screen.getByTestId(ENTITY_REFERENCE_TESTID);
expect(chip.getAttribute("aria-label")).toBe("Open #ENG[1]: Fix the login flow");
expect(chip.getAttribute("href")).toBe(
"https://jira.example/browse/ENG-1?q=hello%20world%28test%29",
);
expect(chip.getAttribute("target")).toBe("_blank");
});
it.each([
["missing metadata", undefined, "[#ENG\\[1\\]](https://jira.example/browse/ENG-1)"],
[
"malformed metadata",
{ entity_references: [{ ...issueReference(), version: 2 }] },
entityReferenceMarkdown(issueReference()),
],
[
"wrong label",
{ entity_references: [issueReference()] },
"[#Wrong](https://jira.example/browse/ENG-1?q=hello%20world%28test%29)",
],
[
"wrong URL",
{ entity_references: [issueReference()] },
"[#ENG\\[1\\]](https://evil.example/ENG-1)",
],
[
"formatted lookalike label",
{ entity_references: [issueReference()] },
"[**#ENG\\[1\\]**](https://jira.example/browse/ENG-1?q=hello%20world%28test%29)",
],
])("keeps %s as ordinary Markdown", (_name, metadata, content) => {
const Wrapper = wrapper();
render(
<Wrapper>
<ChatMessage
comment={userMessage({ content, metadata })}
label="Message"
className=""
onOpenFile={vi.fn()}
/>
</Wrapper>,
);
expect(screen.queryByTestId(ENTITY_REFERENCE_TESTID)).toBeNull();
expect(screen.getByRole("link")).not.toBeNull();
});
});
function renderWithSender(
tasks: Array<{ id: string; title: string }>,
metadata: Partial<Message["metadata"] & object>,
@@ -17,7 +17,6 @@ import { MessageActions } from "@/components/task/chat/messages/message-actions"
import { useUserMessageNavigation } from "@/hooks/use-message-navigation";
import { SenderTaskBadge, type SenderTaskInfo } from "./sender-task-badge";
import { MemoizedMarkdown } from "@/components/shared/memoized-markdown";
import { markdownComponents } from "@/components/shared/markdown-components";
import { ImagePreviewDialog } from "@/components/task/chat/image-preview-dialog";
import { useAppStore } from "@/components/state-provider";
import { HoverCard, HoverCardTrigger, HoverCardContent } from "@kandev/ui/hover-card";
@@ -33,6 +32,9 @@ import {
type WorkflowStepMessageInfo,
} from "./workflow-step-message-badge";
import { AgentMessageContent } from "./agent-message-content";
import { buildEntityReferenceMarkdownComponents } from "./entity-reference-chip";
import { entityReferencesFromMetadata } from "@/lib/entity-references/message-references";
import type { EntityReference } from "@/lib/types/entity-reference";
type ChatMessageProps = {
comment: Message;
@@ -179,14 +181,20 @@ function usePromptMentionNames() {
return useMemo(() => prompts.map((prompt) => prompt.name), [prompts]);
}
function usePromptMentionMarkdownComponents(promptNames: string[]): Components | undefined {
function usePromptMentionMarkdownComponents(
promptNames: string[],
entityReferences: readonly EntityReference[],
): Components | undefined {
return useMemo(() => {
const mentionNames = buildPromptMentionNames(promptNames);
if (mentionNames.length === 0) return undefined;
const baseComponents = buildEntityReferenceMarkdownComponents(entityReferences);
if (mentionNames.length === 0) {
return entityReferences.length === 0 ? undefined : baseComponents;
}
const renderChildren = (children: ReactNode, keyPrefix: string) =>
renderChildrenWithPromptMentions(children, mentionNames, keyPrefix);
return {
...markdownComponents,
...baseComponents,
p: ({ children, node, ...props }: MarkdownChildrenProps<"p">) => {
void node;
return <p {...props}>{renderChildren(children, "p")}</p>;
@@ -232,7 +240,7 @@ function usePromptMentionMarkdownComponents(promptNames: string[]): Components |
return <th {...props}>{renderChildren(children, "th")}</th>;
},
};
}, [promptNames]);
}, [promptNames, entityReferences]);
}
function renderChildrenWithPromptMentions(
@@ -398,7 +406,11 @@ function UserMessageContent({
}: UserMessageProps) {
const userNavigation = useUserMessageNavigation(sessionId ?? null, comment.id);
const promptNames = usePromptMentionNames();
const promptMentionComponents = usePromptMentionMarkdownComponents(promptNames);
const entityReferences = useMemo(
() => entityReferencesFromMetadata(comment.metadata),
[comment.metadata],
);
const promptMentionComponents = usePromptMentionMarkdownComponents(promptNames, entityReferences);
const {
imageAttachments,
fileAttachments,
@@ -0,0 +1,70 @@
import { IconHash } from "@tabler/icons-react";
import type { ComponentPropsWithoutRef } from "react";
import type { Components, ExtraProps } from "react-markdown";
import type { EntityReference } from "@/lib/types/entity-reference";
import {
entityReferenceHref,
entityReferenceLabel,
matchEntityReferenceLink,
} from "@/lib/entity-references/message-references";
import { markdownComponents } from "@/components/shared/markdown-components";
type EntityReferenceChipProps = {
reference: EntityReference;
};
export function EntityReferenceChip({ reference }: EntityReferenceChipProps) {
const label = entityReferenceLabel(reference);
const isInternal = reference.url.startsWith("/") || reference.url.startsWith("#");
return (
<a
href={entityReferenceHref(reference)}
target={isInternal ? "_self" : "_blank"}
rel={isInternal ? undefined : "noopener noreferrer"}
aria-label={`Open ${label}: ${reference.title}`}
title={`${reference.provider} ${reference.kind}: ${reference.title}`}
data-testid="entity-reference-chip"
data-entity-ref={reference.ref}
data-entity-provider={reference.provider}
data-entity-kind={reference.kind}
className="inline-flex max-w-full items-center gap-0.5 rounded-md bg-primary/15 px-1.5 py-0.5 align-baseline text-[0.88em] font-medium text-primary no-underline ring-1 ring-inset ring-primary/20 hover:bg-primary/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1"
>
<IconHash className="h-3 w-3 shrink-0" aria-hidden="true" />
<span className="min-w-0 truncate">{reference.key || reference.title}</span>
</a>
);
}
type EntityReferenceAnchorProps = ComponentPropsWithoutRef<"a"> &
ExtraProps & {
references: readonly EntityReference[];
};
function EntityReferenceAnchor({
references,
children,
href,
...props
}: EntityReferenceAnchorProps) {
const node = props.node;
const textChild = node?.children.length === 1 ? node.children[0] : null;
const label = textChild?.type === "text" ? textChild.value : null;
const reference = label === null ? null : matchEntityReferenceLink(references, label, href);
if (reference) return <EntityReferenceChip reference={reference} />;
const MarkdownAnchor = markdownComponents.a;
return (
<MarkdownAnchor href={href} {...props}>
{children}
</MarkdownAnchor>
);
}
export function buildEntityReferenceMarkdownComponents(
references: readonly EntityReference[],
): Components {
if (references.length === 0) return markdownComponents;
return {
...markdownComponents,
a: (props) => <EntityReferenceAnchor {...props} references={references} />,
};
}
@@ -0,0 +1,154 @@
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import * as popupMenu from "./popup-menu";
import { computePopupMenuStyle, PopupMenu, PopupMenuItem } from "./popup-menu";
afterEach(() => {
cleanup();
Object.defineProperty(window, "visualViewport", { configurable: true, value: undefined });
});
describe("popup menu geometry", () => {
it("provides a visual-viewport-aware geometry helper", () => {
expect(typeof (popupMenu as Record<string, unknown>).computePopupMenuStyle).toBe("function");
});
it("keeps an above-composer menu inside an offset phone visual viewport", () => {
const style = computePopupMenuStyle({
position: { x: 350, y: 560 },
placement: "above",
viewport: { offsetLeft: 12, offsetTop: 100, width: 360, height: 500 },
});
expect(style.left).toBe(20);
expect(style.width).toBe(344);
expect(style.top).toBe(552);
expect(style.maxHeight).toBe(280);
expect(Number(style.top) - Number(style.maxHeight)).toBe(272);
expect(style.transform).toBe("translateY(-100%)");
expect(style.bottom).toBeUndefined();
});
it("uses a focused desktop width instead of spanning the available viewport", () => {
const style = computePopupMenuStyle({
position: { x: 100, y: 700 },
placement: "above",
viewport: { offsetLeft: 0, offsetTop: 0, width: 1200, height: 800 },
});
expect(style.width).toBe(420);
});
it("anchors the rendered bottom edge instead of reserving unused maximum height", () => {
const style = computePopupMenuStyle({
position: { x: 100, y: 700 },
placement: "above",
viewport: { offsetLeft: 0, offsetTop: 0, width: 1200, height: 800 },
});
expect(style.top).toBe(692);
expect(style.transform).toBe("translateY(-100%)");
});
it("reflows while the mobile visual viewport changes", () => {
const viewport = Object.assign(new EventTarget(), {
offsetLeft: 0,
offsetTop: 0,
width: 360,
height: 500,
});
Object.defineProperty(window, "visualViewport", { configurable: true, value: viewport });
render(
<PopupMenu
isOpen
position={null}
clientRect={() => new DOMRect(16, 240, 1, 20)}
title="References"
selectedIndex={0}
onClose={() => undefined}
>
Result
</PopupMenu>,
);
const menu = screen.getByText("References").parentElement?.parentElement;
expect(menu?.style.width).toBe("344px");
act(() => {
viewport.width = 300;
viewport.dispatchEvent(new Event("resize"));
});
expect(menu?.style.width).toBe("284px");
});
});
describe("popup menu interaction", () => {
it("exposes one labelled listbox with semantic selectable options", () => {
render(
<PopupMenu
isOpen
position={{ x: 16, y: 240 }}
title="References"
selectedIndex={0}
onClose={() => undefined}
>
<PopupMenuItem
icon={<span aria-hidden="true">#</span>}
label="#ENG-123"
description="Fix authentication"
isSelected
onClick={() => undefined}
onMouseEnter={() => undefined}
/>
</PopupMenu>,
);
expect(screen.getByRole("listbox", { name: "References" })).toBeTruthy();
expect(
screen
.getByRole("option", { name: /#ENG-123.*Fix authentication/ })
.getAttribute("aria-selected"),
).toBe("true");
});
it("keeps composer focus when an option is pressed", () => {
render(
<PopupMenu
isOpen
position={{ x: 16, y: 240 }}
title="References"
selectedIndex={0}
onClose={() => undefined}
>
<PopupMenuItem
icon={<span aria-hidden="true">#</span>}
label="#ENG-123"
isSelected
onClick={() => undefined}
onMouseEnter={() => undefined}
/>
</PopupMenu>,
);
expect(fireEvent.pointerDown(screen.getByRole("option"))).toBe(false);
});
it("dismisses from an outside pointer press", () => {
const onClose = vi.fn();
render(
<PopupMenu
isOpen
position={{ x: 16, y: 240 }}
title="References"
selectedIndex={0}
onClose={onClose}
>
Result
</PopupMenu>,
);
fireEvent.pointerDown(document.body);
expect(onClose).toHaveBeenCalledOnce();
});
});
+100 -24
View File
@@ -1,14 +1,54 @@
"use client";
import { useEffect, useRef, type ReactNode } from "react";
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { cn } from "@/lib/utils";
const MENU_HEIGHT = 280;
const MENU_MAX_WIDTH = 700;
const MENU_WIDTH = 420;
const MENU_HEADER_HEIGHT = 32;
type PopupViewport = {
offsetLeft: number;
offsetTop: number;
width: number;
height: number;
};
export function computePopupMenuStyle(args: {
position: { x: number; y: number };
placement: "above" | "below";
viewport: PopupViewport;
}): React.CSSProperties {
const margin = 8;
const viewportRight = args.viewport.offsetLeft + args.viewport.width;
const viewportBottom = args.viewport.offsetTop + args.viewport.height;
const width = Math.max(0, Math.min(MENU_WIDTH, args.viewport.width - margin * 2));
const minLeft = args.viewport.offsetLeft + margin;
const maxLeft = Math.max(minLeft, viewportRight - width - margin);
const left = Math.min(Math.max(minLeft, args.position.x), maxLeft);
const availableHeight =
args.placement === "above"
? Math.max(0, args.position.y - args.viewport.offsetTop - margin * 2)
: Math.max(0, viewportBottom - args.position.y - margin * 2);
const maxHeight = Math.min(MENU_HEIGHT, availableHeight);
const top = args.placement === "above" ? args.position.y - margin : args.position.y + margin;
return {
position: "fixed",
left,
top,
width,
maxWidth: width,
maxHeight,
zIndex: 60,
pointerEvents: "auto",
transform: args.placement === "above" ? "translateY(-100%)" : undefined,
};
}
export type PopupMenuProps = {
isOpen: boolean;
testId?: string;
position: { x: number; y: number } | null;
/** Alternative to position: a function returning a DOMRect (from TipTap suggestion) */
clientRect?: (() => DOMRect | null) | null;
@@ -24,6 +64,7 @@ export type PopupMenuProps = {
export function PopupMenu({
isOpen,
testId,
position,
clientRect: clientRectFn,
title,
@@ -34,21 +75,37 @@ export function PopupMenu({
placement = "above",
}: PopupMenuProps) {
const menuRef = useRef<HTMLDivElement>(null);
const titleId = useId();
const [, setViewportRevision] = useState(0);
// Close on click outside
useEffect(() => {
if (!isOpen) return;
const handleClickOutside = (event: MouseEvent) => {
const handlePointerOutside = (event: PointerEvent) => {
if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
onClose();
}
};
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
document.addEventListener("pointerdown", handlePointerOutside);
return () => document.removeEventListener("pointerdown", handlePointerOutside);
}, [isOpen, onClose]);
useEffect(() => {
if (!isOpen) return;
const update = () => setViewportRevision((revision) => revision + 1);
const viewport = window.visualViewport;
window.addEventListener("resize", update);
viewport?.addEventListener("resize", update);
viewport?.addEventListener("scroll", update);
return () => {
window.removeEventListener("resize", update);
viewport?.removeEventListener("resize", update);
viewport?.removeEventListener("scroll", update);
};
}, [isOpen]);
// Resolve position from clientRect function or direct position
const resolvedPosition = (() => {
if (position) return position;
@@ -68,31 +125,45 @@ export function PopupMenu({
// pointer-events: auto restores click-handling on the popup itself when
// Radix Dialog has set pointer-events: none on <body> for modal isolation;
// without this, the popup is visible but unclickable inside a dialog.
const menuStyle: React.CSSProperties = {
position: "fixed",
left: Math.max(8, resolvedPosition.x),
maxWidth: Math.min(MENU_MAX_WIDTH, window.innerWidth - resolvedPosition.x - 8),
maxHeight: MENU_HEIGHT,
zIndex: 60,
pointerEvents: "auto",
...(placement === "below"
? { top: resolvedPosition.y + 8 }
: { bottom: window.innerHeight - resolvedPosition.y + 8 }),
};
const visualViewport = window.visualViewport;
const menuStyle = computePopupMenuStyle({
position: resolvedPosition,
placement,
viewport: visualViewport
? {
offsetLeft: visualViewport.offsetLeft,
offsetTop: visualViewport.offsetTop,
width: visualViewport.width,
height: visualViewport.height,
}
: { offsetLeft: 0, offsetTop: 0, width: window.innerWidth, height: window.innerHeight },
});
const contentMaxHeight =
typeof menuStyle.maxHeight === "number"
? Math.max(0, menuStyle.maxHeight - MENU_HEADER_HEIGHT)
: MENU_HEIGHT - MENU_HEADER_HEIGHT;
const menu = (
<div
ref={menuRef}
data-testid={testId}
style={menuStyle}
className="overflow-hidden rounded-lg bg-popover text-popover-foreground shadow-md ring-1 ring-foreground/10"
>
{/* Header */}
<div className="px-2 py-1.5 border-b border-border/50">
<span className="text-xs font-medium text-muted-foreground">{title}</span>
<div className="border-b border-border/50 px-2 py-1.5">
<span id={titleId} className="text-xs font-medium text-muted-foreground">
{title}
</span>
</div>
{/* Content */}
<div className="overflow-y-auto py-1 scrollbar-thin" style={{ maxHeight: MENU_HEIGHT - 36 }}>
<div
role="listbox"
aria-labelledby={titleId}
className="overflow-y-auto py-1 scrollbar-thin"
style={{ maxHeight: contentMaxHeight }}
>
{hasItems ? children : emptyState}
</div>
</div>
@@ -126,22 +197,27 @@ export function PopupMenuItem({
<button
ref={itemRef}
type="button"
role="option"
aria-selected={isSelected}
className={cn(
"flex w-full cursor-pointer select-none items-center gap-3 rounded-[6px] mx-1 px-2 py-1.5 text-xs text-left",
"mx-1 flex min-h-11 w-full cursor-pointer select-none items-center gap-3 rounded-[6px] px-2 py-1.5 text-left text-xs",
"hover:bg-muted/50",
isSelected && "bg-muted/50",
)}
style={{ width: "calc(100% - 8px)" }}
onPointerDown={(event) => event.preventDefault()}
onClick={onClick}
onMouseEnter={onMouseEnter}
>
<div className="h-4 w-4 text-muted-foreground shrink-0 flex items-center justify-center">
<div className="flex h-4 w-4 shrink-0 items-center justify-center text-muted-foreground">
{icon}
</div>
<div className="flex items-baseline gap-2 min-w-0 flex-1">
<span className="shrink-0 font-medium">{label}</span>
<div className="flex min-w-0 flex-1 items-baseline gap-2">
<span className="max-w-[45%] shrink-0 truncate font-medium">{label}</span>
{description && (
<span className="text-[11px] text-muted-foreground whitespace-nowrap">{description}</span>
<span className="min-w-0 truncate whitespace-nowrap text-[11px] text-muted-foreground">
{description}
</span>
)}
</div>
</button>
@@ -1,7 +1,9 @@
import type { ReactNode } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import type { QueuedMessage } from "@/lib/state/slices/session/types";
import type { EntityReference } from "@/lib/types/entity-reference";
import { entityReferenceMarkdown } from "@/lib/entity-references/message-references";
const useQueueMock = vi.fn();
@@ -49,6 +51,20 @@ function entry(overrides: Partial<QueuedMessage> = {}): QueuedMessage {
};
}
function taskReference(): EntityReference {
return {
version: 1,
ref: "mention:v1:kandev:task:workspace-1:task-1",
provider: "kandev",
kind: "task",
id: "task-1",
key: "KAN-1",
title: "Fix authentication",
url: "/t/task-1",
scope: "workspace-1",
};
}
function queueState(entries: QueuedMessage[], extra: Partial<ReturnType<typeof baseState>> = {}) {
return { ...baseState(entries), ...extra };
}
@@ -274,3 +290,28 @@ describe("QueueAffordance — workflow entries", () => {
expect(screen.queryByTitle("Remove queued message")).toBeNull();
});
});
describe("QueueAffordance entity-reference edits", () => {
it("forwards an explicit empty replacement through the queue edit callback", async () => {
const reference = taskReference();
const state = queueState([
entry({
content: entityReferenceMarkdown(reference),
metadata: { entity_references: [reference] },
}),
]);
useQueueMock.mockReturnValue(state);
render(<QueueAffordance sessionId={SESSION_ID}>{CHILD}</QueueAffordance>);
fireEvent.click(screen.getByTestId(CHIP_ID));
fireEvent.click(screen.getByTitle("Edit queued message"));
fireEvent.change(screen.getByTestId("queue-edit-textarea"), {
target: { value: "reference removed" },
});
fireEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() =>
expect(state.editEntry).toHaveBeenCalledWith("q-1", "reference removed", undefined, []),
);
});
});
@@ -12,6 +12,7 @@ import { stripSystemTags } from "@/lib/utils/system-tags";
import { useQueue } from "@/hooks/domains/session/use-queue";
import { isWorkflowQueuedMessage, QueuedGhostMessage } from "./queued-ghost-message";
import type { QueuedMessage } from "@/lib/state/slices/session/types";
import type { EntityReference } from "@/lib/types/entity-reference";
const HEAD_PREVIEW_MAX = 80;
@@ -72,7 +73,12 @@ type QueueAffordanceProps = {
type QueuePanelHandlerArgs = {
clearAll: () => Promise<void>;
drainNext: () => Promise<void>;
editEntry: (entryId: string, content: string) => Promise<void>;
editEntry: (
entryId: string,
content: string,
attachments?: undefined,
entityReferences?: EntityReference[],
) => Promise<void>;
removeEntry: (entryId: string) => Promise<void>;
};
@@ -83,8 +89,8 @@ function useQueuePanelHandlers({
removeEntry,
}: QueuePanelHandlerArgs) {
const handleSave = useCallback(
async (entryId: string, content: string) => {
await editEntry(entryId, content);
async (entryId: string, content: string, entityReferences: EntityReference[]) => {
await editEntry(entryId, content, undefined, entityReferences);
},
[editEntry],
);
@@ -272,7 +278,7 @@ type QueuePanelProps = {
onClose: () => void;
onClear: () => void;
onDrain: () => void;
onSave: (entryId: string, content: string) => Promise<void>;
onSave: (entryId: string, content: string, entityReferences: EntityReference[]) => Promise<void>;
onRemove: (entryId: string) => Promise<void>;
};
@@ -317,7 +323,7 @@ function QueuePanel({
entry={entry}
index={index}
canEdit={canUserEditEntry(entry)}
onSave={(content) => onSave(entry.id, content)}
onSave={(content, entityReferences) => onSave(entry.id, content, entityReferences)}
onRemove={() => onRemove(entry.id)}
/>
))}
@@ -1,6 +1,10 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { QueuedGhostMessage } from "./queued-ghost-message";
import { StateProvider } from "@/components/state-provider";
import { ToastProvider } from "@/components/toast-provider";
import { entityReferenceMarkdown } from "@/lib/entity-references/message-references";
import type { EntityReference } from "@/lib/types/entity-reference";
import type { QueuedMessage } from "@/lib/state/slices/session/types";
afterEach(() => {
@@ -35,6 +39,43 @@ function entry(overrides: Partial<QueuedMessage> = {}): QueuedMessage {
};
}
function taskReference(overrides: Partial<EntityReference> = {}): EntityReference {
return {
version: 1,
ref: "mention:v1:kandev:task:workspace-1:task-1",
provider: "kandev",
kind: "task",
id: "task-1",
key: "KAN-1",
title: "Fix authentication",
url: "/t/task-1",
scope: "workspace-1",
...overrides,
};
}
function issueReference(): EntityReference {
return {
version: 1,
ref: "mention:v1:jira:issue:https%3A%2F%2Fjira.example:10001",
provider: "jira",
kind: "issue",
id: "10001",
key: "ENG-1",
title: "Fix login flow",
url: "https://jira.example/browse/ENG-1",
scope: "https://jira.example",
};
}
function renderWithProviders(node: React.ReactNode) {
return render(
<StateProvider>
<ToastProvider>{node}</ToastProvider>
</StateProvider>,
);
}
describe("QueuedGhostMessage workflow badge", () => {
it("renders workflow metadata as a workflow step badge", () => {
render(
@@ -155,3 +196,75 @@ describe("QueuedGhostMessage attachment thumbnails", () => {
expect(container.querySelector("img")).toBeNull();
});
});
describe("QueuedGhostMessage entity references", () => {
it("renders an exact queued Markdown link as an accessible chip", () => {
const reference = taskReference();
renderWithProviders(
<QueuedGhostMessage
entry={entry({
content: entityReferenceMarkdown(reference),
metadata: { entity_references: [reference] },
})}
canEdit
onSave={async () => {}}
onRemove={() => {}}
/>,
);
const chip = screen.getByTestId("entity-reference-chip");
expect(chip.getAttribute("href")).toBe("/t/task-1");
expect(chip.getAttribute("target")).toBe("_self");
});
it("recomputes surviving references in edited document order", async () => {
const task = taskReference();
const issue = issueReference();
const edited = `${entityReferenceMarkdown(issue)} then ${entityReferenceMarkdown(task)}`;
const onSave = vi.fn(async () => {});
renderWithProviders(
<QueuedGhostMessage
entry={entry({
content: `${entityReferenceMarkdown(task)} then ${entityReferenceMarkdown(issue)}`,
metadata: { entity_references: [task, issue] },
})}
canEdit
onSave={onSave}
onRemove={() => {}}
/>,
);
fireEvent.click(screen.getByTitle("Edit queued message"));
fireEvent.change(screen.getByTestId("queue-edit-textarea"), { target: { value: edited } });
fireEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(onSave).toHaveBeenCalledWith(edited, [issue, task]));
});
it("sends an explicit empty reference replacement after all links are removed", async () => {
const reference = taskReference();
const onSave = vi.fn(async () => {});
renderWithProviders(
<QueuedGhostMessage
entry={entry({
content: entityReferenceMarkdown(reference),
metadata: { entity_references: [reference] },
})}
canEdit
onSave={onSave}
onRemove={() => {}}
/>,
);
fireEvent.click(screen.getByTitle("Edit queued message"));
fireEvent.change(screen.getByTestId("queue-edit-textarea"), {
target: { value: "reference removed" },
});
fireEvent.click(screen.getByRole("button", { name: "Save" }));
await waitFor(() => expect(onSave).toHaveBeenCalledWith("reference removed", []));
});
});
@@ -1,6 +1,14 @@
"use client";
import { forwardRef, useCallback, useEffect, useImperativeHandle, useRef, useState } from "react";
import {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useMemo,
useRef,
useState,
} from "react";
import {
IconCheck,
IconChevronDown,
@@ -29,8 +37,14 @@ import {
workflowMessageInfoFromMetadata,
type WorkflowStepMessageInfo,
} from "@/components/task/chat/messages/workflow-step-message-badge";
import { markdownComponents, remarkPlugins } from "@/components/shared/markdown-components";
import { remarkPlugins } from "@/components/shared/markdown-components";
import type { QueuedMessage } from "@/lib/state/slices/session/types";
import type { EntityReference } from "@/lib/types/entity-reference";
import {
entityReferencesFromMetadata,
survivingEntityReferences,
} from "@/lib/entity-references/message-references";
import { buildEntityReferenceMarkdownComponents } from "@/components/task/chat/messages/entity-reference-chip";
type QueuedAttachment = NonNullable<QueuedMessage["attachments"]>[number];
@@ -239,6 +253,7 @@ function EditView({
type DisplayViewProps = {
entry: QueuedMessage;
entityReferences: readonly EntityReference[];
positionLabel: string;
canEdit: boolean;
onStartEdit: () => void;
@@ -255,13 +270,24 @@ function shouldOfferExpand(text: string): boolean {
return text.length > EXPAND_THRESHOLD || text.includes("\n");
}
function DisplayView({ entry, positionLabel, canEdit, onStartEdit, onRemove }: DisplayViewProps) {
function DisplayView({
entry,
entityReferences,
positionLabel,
canEdit,
onStartEdit,
onRemove,
}: DisplayViewProps) {
const visible = stripSystemTags(entry.content);
const attachments = (entry.attachments ?? []) as QueuedAttachment[];
const senderTask = getSenderTaskInfo(entry);
const workflowMessage = getWorkflowMessageInfo(entry);
const [expanded, setExpanded] = useState(false);
const canExpand = shouldOfferExpand(visible);
const referenceMarkdownComponents = useMemo(
() => buildEntityReferenceMarkdownComponents(entityReferences),
[entityReferences],
);
return (
<div className="group flex items-start gap-2 py-1.5">
<span className="flex items-center gap-1.5 mt-0.5 text-muted-foreground">
@@ -287,7 +313,7 @@ function DisplayView({ entry, positionLabel, canEdit, onStartEdit, onRemove }: D
expanded ? "max-h-[40rem]" : "max-h-[2.75rem]",
)}
>
<ReactMarkdown remarkPlugins={remarkPlugins} components={markdownComponents}>
<ReactMarkdown remarkPlugins={remarkPlugins} components={referenceMarkdownComponents}>
{visible}
</ReactMarkdown>
</div>
@@ -356,7 +382,7 @@ type QueuedGhostMessageProps = {
* entry's queued_by. Inter-task entries are visible but read-only.
*/
canEdit: boolean;
onSave: (content: string) => Promise<void>;
onSave: (content: string, entityReferences: EntityReference[]) => Promise<void>;
onRemove: () => void | Promise<void>;
/** Called after edit save/cancel so the parent can refocus the chat input. */
onEditComplete?: () => void;
@@ -368,6 +394,10 @@ export const QueuedGhostMessage = forwardRef<QueuedGhostMessageHandle, QueuedGho
const [value, setValue] = useState(entry.content);
const [saving, setSaving] = useState(false);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const entityReferences = useMemo(
() => entityReferencesFromMetadata(entry.metadata),
[entry.metadata],
);
useEffect(() => {
if (!editing) setValue(entry.content);
@@ -404,7 +434,7 @@ export const QueuedGhostMessage = forwardRef<QueuedGhostMessageHandle, QueuedGho
}
setSaving(true);
try {
await onSave(trimmed);
await onSave(trimmed, survivingEntityReferences(trimmed, entityReferences));
setEditing(false);
onEditComplete?.();
} catch (err) {
@@ -422,7 +452,7 @@ export const QueuedGhostMessage = forwardRef<QueuedGhostMessageHandle, QueuedGho
} finally {
setSaving(false);
}
}, [value, entry.content, onSave, onEditComplete]);
}, [value, entry.content, onSave, onEditComplete, entityReferences]);
const positionNumber = entry.position ?? (index ?? 0) + 1;
const positionLabel = `#${positionNumber}`;
@@ -447,6 +477,7 @@ export const QueuedGhostMessage = forwardRef<QueuedGhostMessageHandle, QueuedGho
) : (
<DisplayView
entry={entry}
entityReferences={entityReferences}
positionLabel={positionLabel}
canEdit={canEdit}
onStartEdit={startEdit}
@@ -1,6 +1,6 @@
import { describe, it, expect } from "vitest";
import { buildTaskMentionItems } from "./task-mention-items";
import { describe, expect, it } from "vitest";
import type { AppState } from "@/lib/state/store";
import { buildTaskMentionItems } from "./task-mention-items";
function makeState(overrides: Partial<AppState> = {}): AppState {
const base = {
@@ -12,8 +12,8 @@ function makeState(overrides: Partial<AppState> = {}): AppState {
return { ...base, ...overrides } as AppState;
}
describe("buildTaskMentionItems / basics", () => {
it("returns tasks from the current workflow with workflow/step names resolved", () => {
describe("buildTaskMentionItems", () => {
it("returns sibling tasks with resolved workflow and step names", () => {
const state = makeState({
kanban: {
workflowId: "wf-1",
@@ -34,23 +34,17 @@ describe("buildTaskMentionItems / basics", () => {
},
} as unknown as Partial<AppState>);
const items = buildTaskMentionItems(state, null);
expect(items).toHaveLength(1);
expect(items[0]).toMatchObject({
kind: "task",
label: "Implement auth",
description: "Main flow · Todo",
task: {
taskId: "task-a",
title: "Implement auth",
workflowId: "wf-1",
workflowStepId: "step-1",
state: "in_progress",
},
});
expect(buildTaskMentionItems(state, null)).toEqual([
expect.objectContaining({
kind: "task",
label: "Implement auth",
description: "Main flow · Todo",
task: expect.objectContaining({ taskId: "task-a", workflowId: "wf-1" }),
}),
]);
});
it("excludes the current task by id", () => {
it("excludes the current task", () => {
const state = makeState({
kanban: {
workflowId: "wf-1",
@@ -62,18 +56,20 @@ describe("buildTaskMentionItems / basics", () => {
},
} as unknown as Partial<AppState>);
const items = buildTaskMentionItems(state, "task-a");
expect(items.map((i) => i.task?.taskId)).toEqual(["task-b"]);
expect(buildTaskMentionItems(state, "task-a").map((item) => item.task?.taskId)).toEqual([
"task-b",
]);
});
});
describe("buildTaskMentionItems / merging and filtering", () => {
it("merges tasks from kanbanMulti snapshots and dedupes by id", () => {
it("merges workflow snapshots and skips stale active-workflow tasks", () => {
const state = makeState({
kanban: {
workflowId: "wf-1",
steps: [],
tasks: [{ id: "task-a", workflowStepId: "step-1", title: "A", position: 0 }],
steps: [{ id: "step-current", title: "Todo", color: "", position: 0 }],
tasks: [
{ id: "task-a", workflowStepId: "step-current", title: "A", position: 0 },
{ id: "task-stale", workflowStepId: "step-other", title: "Stale", position: 1 },
],
},
kanbanMulti: {
snapshots: {
@@ -81,54 +77,22 @@ describe("buildTaskMentionItems / merging and filtering", () => {
workflowId: "wf-1",
workflowName: "Main",
steps: [],
tasks: [
{ id: "task-a", workflowStepId: "step-1", title: "A (dup)", position: 0 },
{ id: "task-c", workflowStepId: "step-2", title: "C", position: 0 },
],
tasks: [{ id: "task-a", workflowStepId: "step-current", title: "A", position: 0 }],
},
"wf-2": {
workflowId: "wf-2",
workflowName: "Other",
steps: [{ id: "step-9", title: "Review", color: "", position: 0 }],
tasks: [{ id: "task-d", workflowStepId: "step-9", title: "D", position: 0 }],
steps: [{ id: "step-2", title: "Review", color: "", position: 0 }],
tasks: [{ id: "task-b", workflowStepId: "step-2", title: "B", position: 0 }],
},
},
isLoading: false,
},
} as unknown as Partial<AppState>);
const ids = buildTaskMentionItems(state, null).map((i) => i.task?.taskId);
expect(ids).toEqual(["task-a", "task-c", "task-d"]);
});
it("skips stale kanban tasks whose step is not in the current workflow's steps", () => {
const state = makeState({
kanban: {
workflowId: "wf-1",
steps: [{ id: "step-current", title: "Todo", color: "", position: 0 }],
tasks: [
{ id: "task-fresh", workflowStepId: "step-current", title: "Fresh", position: 0 },
// Left over from a previous workflow: its step is not in wf-1's steps,
// so tagging it with wf-1 would be wrong.
{ id: "task-stale", workflowStepId: "step-other", title: "Stale", position: 1 },
],
},
} as unknown as Partial<AppState>);
const ids = buildTaskMentionItems(state, null).map((i) => i.task?.taskId);
expect(ids).toEqual(["task-fresh"]);
});
it("falls back to placeholder names when workflow/step are missing", () => {
const state = makeState({
kanban: {
workflowId: "wf-1",
steps: [],
tasks: [{ id: "task-a", workflowStepId: "step-missing", title: "A", position: 0 }],
},
} as unknown as Partial<AppState>);
const [item] = buildTaskMentionItems(state, null);
expect(item.description).toBe("Workflow · Step");
expect(buildTaskMentionItems(state, null).map((item) => item.task?.taskId)).toEqual([
"task-a",
"task-b",
]);
});
});
@@ -4,21 +4,23 @@ import type { AppState } from "@/lib/state/store";
type TaskLike = AppState["kanban"]["tasks"][number];
function buildWorkflowNameMap(state: AppState): Map<string, string> {
const m = new Map<string, string>();
for (const w of state.workflows.items) m.set(w.id, w.name);
for (const [wfId, snap] of Object.entries(state.kanbanMulti.snapshots)) {
if (!m.has(wfId) && snap.workflowName) m.set(wfId, snap.workflowName);
const names = new Map<string, string>();
for (const workflow of state.workflows.items) names.set(workflow.id, workflow.name);
for (const [workflowId, snapshot] of Object.entries(state.kanbanMulti.snapshots)) {
if (!names.has(workflowId) && snapshot.workflowName) {
names.set(workflowId, snapshot.workflowName);
}
}
return m;
return names;
}
function buildStepTitleMap(state: AppState): Map<string, string> {
const m = new Map<string, string>();
for (const s of state.kanban.steps) m.set(s.id, s.title);
for (const snap of Object.values(state.kanbanMulti.snapshots)) {
for (const s of snap.steps ?? []) m.set(s.id, s.title);
const titles = new Map<string, string>();
for (const step of state.kanban.steps) titles.set(step.id, step.title);
for (const snapshot of Object.values(state.kanbanMulti.snapshots)) {
for (const step of snapshot.steps ?? []) titles.set(step.id, step.title);
}
return m;
return titles;
}
function toMentionItem(
@@ -61,17 +63,14 @@ export function buildTaskMentionItems(
};
if (state.kanban.workflowId) {
// Guard against stale tasks left over from a previous workflow: only add
// entries whose workflowStepId belongs to the current workflow's steps,
// since we tag them with state.kanban.workflowId here.
const activeStepIds = new Set(state.kanban.steps.map((s) => s.id));
for (const t of state.kanban.tasks) {
if (activeStepIds.size > 0 && !activeStepIds.has(t.workflowStepId)) continue;
addTask(t, state.kanban.workflowId);
const activeStepIds = new Set(state.kanban.steps.map((step) => step.id));
for (const task of state.kanban.tasks) {
if (activeStepIds.size > 0 && !activeStepIds.has(task.workflowStepId)) continue;
addTask(task, state.kanban.workflowId);
}
}
for (const [wfId, snap] of Object.entries(state.kanbanMulti.snapshots)) {
for (const t of snap.tasks) addTask(t, wfId);
for (const [workflowId, snapshot] of Object.entries(state.kanbanMulti.snapshots)) {
for (const task of snapshot.tasks) addTask(task, workflowId);
}
return items;
@@ -0,0 +1,60 @@
import { Extension, isNodeEmpty, type Editor } from "@tiptap/core";
import type { Node as ProseMirrorNode } from "@tiptap/pm/model";
import { Plugin, PluginKey } from "@tiptap/pm/state";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
type DynamicPlaceholderStorage = {
dynamicPlaceholder: { text: string };
};
function placeholderStorage(editor: Editor): DynamicPlaceholderStorage {
return editor.storage as unknown as DynamicPlaceholderStorage;
}
/** Placeholder extension backed by live editor storage, avoiding stale options snapshots. */
export const DynamicPlaceholder = Extension.create({
name: "dynamicPlaceholder",
addStorage() {
return { text: "" };
},
addProseMirrorPlugins() {
const editor = this.editor;
return [
new Plugin({
key: new PluginKey("dynamicPlaceholder"),
props: {
decorations: ({ doc, selection }) => {
if (!editor.isEditable && !editor.isEmpty) return null;
const { anchor } = selection;
const decorations: InstanceType<typeof Decoration>[] = [];
const isEmptyDoc = editor.isEmpty;
doc.descendants((node: ProseMirrorNode, pos: number) => {
const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize;
const isEmpty = !node.isLeaf && isNodeEmpty(node);
if (hasAnchor && isEmpty) {
const classes = ["is-empty"];
if (isEmptyDoc) classes.push("is-editor-empty");
decorations.push(
Decoration.node(pos, pos + node.nodeSize, {
class: classes.join(" "),
"data-placeholder": placeholderStorage(editor).dynamicPlaceholder.text,
}),
);
}
return false;
});
return DecorationSet.create(doc, decorations);
},
},
}),
];
},
});
export function updateDynamicPlaceholder(editor: Editor | null, text: string) {
if (!editor) return;
placeholderStorage(editor).dynamicPlaceholder.text = text;
editor.view.dispatch(editor.state.tr);
}
@@ -0,0 +1,37 @@
import { describe, expect, it } from "vitest";
import * as editorHistory from "./tiptap-editor-history";
describe("rich message history", () => {
it("provides a structured history-to-editor conversion", () => {
expect(typeof (editorHistory as Record<string, unknown>).historyEntryToEditorContent).toBe(
"function",
);
});
it("restores a reference atom only from matching history metadata", () => {
const reference = {
version: 1,
ref: "mention:v1:jira:issue:scope:10001",
provider: "jira",
kind: "issue",
id: "10001",
key: "ENG-123",
title: "Fix authentication",
url: "https://jira.example.test/browse/ENG-123",
scope: "jira.example.test/site-1",
};
const content = editorHistory.historyEntryToEditorContent(
{
content: "See [#ENG-123](https://jira.example.test/browse/ENG-123)",
entityReferences: [reference],
},
[],
);
expect(content.content?.[0]?.content).toEqual([
{ type: "text", text: "See " },
{ type: "entityReference", attrs: reference },
]);
});
});
@@ -5,7 +5,7 @@ import { Plugin, PluginKey } from "@tiptap/pm/state";
import { Node as ProseMirrorNode } from "@tiptap/pm/model";
import { matchesShortcut } from "@/lib/keyboard/utils";
import { getShortcut, type StoredShortcutOverrides } from "@/lib/keyboard/shortcut-overrides";
import { navigateHistory, type HistoryState } from "./message-history";
import { navigateHistory, type HistoryState, type MessageHistoryEntry } from "./message-history";
import { getMarkdownText, textToEditorContent } from "./tiptap-helpers";
import type { SlashCommand } from "./slash-command-types";
@@ -46,7 +46,7 @@ export type HistoryKeymapRefs = {
disabledRef: React.RefObject<boolean | undefined>;
isSuggestionMenuOpenRef: React.RefObject<boolean>;
isReverseSearchOpenRef: React.RefObject<boolean>;
getHistoryRef: React.RefObject<() => readonly string[]>;
getHistoryRef: React.RefObject<() => readonly MessageHistoryEntry[]>;
getSlashCommandsRef: React.RefObject<() => readonly SlashCommand[]>;
onOpenReverseSearchRef: React.RefObject<(() => void) | undefined>;
onChangeRef: React.RefObject<(value: string) => void>;
@@ -64,24 +64,31 @@ type Editor = ReturnType<typeof useEditor>;
type HistoryRuntimeState = {
index: number | null;
draft: string;
draft: import("@tiptap/core").JSONContent | null;
isApplying: boolean;
};
export function historyEntryToEditorContent(
entry: MessageHistoryEntry,
slashCommands: readonly SlashCommand[],
) {
return textToEditorContent(entry.content, slashCommands, entry.entityReferences);
}
function writeHistoryContent(
editor: Editor,
state: HistoryRuntimeState,
text: string,
entry: MessageHistoryEntry,
slashCommands: readonly SlashCommand[],
onChange: (value: string) => void,
): void {
if (!editor) return;
state.isApplying = true;
try {
if (text === "") {
if (entry.content === "") {
editor.chain().focus().clearContent().run();
} else {
editor.chain().focus().setContent(textToEditorContent(text, slashCommands)).run();
editor.chain().focus().setContent(historyEntryToEditorContent(entry, slashCommands)).run();
editor.commands.focus("end");
}
onChange(getMarkdownText(editor));
@@ -90,6 +97,22 @@ function writeHistoryContent(
}
}
function writeDraftContent(
editor: Editor,
state: HistoryRuntimeState,
onChange: (value: string) => void,
) {
if (!editor || !state.draft) return;
state.isApplying = true;
try {
editor.chain().focus().setContent(state.draft).run();
editor.commands.focus("end");
onChange(getMarkdownText(editor));
} finally {
state.isApplying = false;
}
}
function caretAtBoundary(editor: Editor, direction: "up" | "down"): boolean {
if (!editor) return false;
const view = editor.view;
@@ -121,11 +144,20 @@ function runHistoryArrow(
if (decision.kind === "defer") return false;
if (decision.kind === "consume-noop") return true;
if (state.index === null && decision.index !== null) {
state.draft = getMarkdownText(editor);
state.draft = editor.getJSON();
}
if (decision.index === null) {
writeDraftContent(editor, state, refs.onChangeRef.current);
} else {
const slashCommands = refs.getSlashCommandsRef.current?.() ?? [];
writeHistoryContent(
editor,
state,
history[decision.index],
slashCommands,
refs.onChangeRef.current,
);
}
const text = decision.index === null ? state.draft : history[decision.index];
const slashCommands = refs.getSlashCommandsRef.current?.() ?? [];
writeHistoryContent(editor, state, text, slashCommands, refs.onChangeRef.current);
state.index = decision.index;
return true;
}
@@ -148,7 +180,7 @@ function reverseSearchPlugin(state: HistoryRuntimeState, refs: HistoryKeymapRefs
filterTransaction: (tr) => {
if (tr.docChanged && !state.isApplying && state.index !== null) {
state.index = null;
state.draft = "";
state.draft = null;
}
return true;
},
@@ -179,7 +211,7 @@ function applyHistoryIndexImpl(
if (!editor) return;
const history = refs.getHistoryRef.current?.() ?? [];
if (index < 0 || index >= history.length) return;
if (state.index === null) state.draft = getMarkdownText(editor);
if (state.index === null) state.draft = editor.getJSON();
const slashCommands = refs.getSlashCommandsRef.current?.() ?? [];
writeHistoryContent(editor, state, history[index], slashCommands, refs.onChangeRef.current);
state.index = index;
@@ -187,7 +219,7 @@ function applyHistoryIndexImpl(
export function useHistoryKeymap(refs: HistoryKeymapRefs): HistoryNavController {
return useMemo(() => {
const state: HistoryRuntimeState = { index: null, draft: "", isApplying: false };
const state: HistoryRuntimeState = { index: null, draft: null, isApplying: false };
const extension = buildHistoryExtension(state, refs);
const applyHistoryIndex: HistoryNavController["applyHistoryIndex"] = (editor, index) =>
applyHistoryIndexImpl(editor, state, index, refs);
@@ -0,0 +1,24 @@
import { describe, expect, it } from "vitest";
import * as entityReferenceExtensions from "./tiptap-entity-reference-extension";
describe("entityReference node", () => {
it("provides a distinct inline atom for # references", () => {
const extension = (entityReferenceExtensions as Record<string, unknown>).EntityReferenceNode as
| { name?: string; config?: { inline?: boolean; atom?: boolean } }
| undefined;
expect(extension).toBeDefined();
expect(extension?.name).toBe("entityReference");
expect(extension?.config?.inline).toBe(true);
expect(extension?.config?.atom).toBe(true);
});
it("renders the atom with a dedicated React node view", () => {
const extension = (entityReferenceExtensions as Record<string, unknown>)
.EntityReferenceNode as {
config?: { addNodeView?: unknown };
};
expect(typeof extension.config?.addNodeView).toBe("function");
});
});
@@ -0,0 +1,73 @@
"use client";
import { mergeAttributes, Node } from "@tiptap/core";
import { NodeViewWrapper, ReactNodeViewRenderer, type ReactNodeViewProps } from "@tiptap/react";
import { IconHash } from "@tabler/icons-react";
export const EntityReferenceNode = Node.create({
name: "entityReference",
group: "inline",
inline: true,
selectable: false,
atom: true,
addAttributes() {
return {
version: { default: 1 },
ref: { default: null },
provider: { default: null },
kind: { default: null },
id: { default: null },
key: { default: null },
title: { default: null },
url: { default: null },
scope: { default: null },
};
},
parseHTML() {
return [{ tag: "span[data-entity-reference]" }];
},
renderHTML({ HTMLAttributes }) {
return [
"span",
mergeAttributes({ "data-entity-reference": "" }, HTMLAttributes),
HTMLAttributes.key || HTMLAttributes.title || HTMLAttributes.id || "",
];
},
renderText({ node }) {
return `#${node.attrs.key ?? node.attrs.title ?? node.attrs.id ?? ""}`;
},
addNodeView() {
return ReactNodeViewRenderer(EntityReferenceChipView);
},
});
function EntityReferenceChipView({ node }: ReactNodeViewProps) {
const { key, title, provider, kind, id } = node.attrs as {
key?: string | null;
title?: string | null;
provider?: string | null;
kind?: string | null;
id?: string | null;
};
const label = key || title || id || "Reference";
const source = [provider, kind].filter(Boolean).join(" ");
const description = source ? `${source}: ${title || label}` : title || label;
return (
<NodeViewWrapper as="span" className="inline">
<span
contentEditable={false}
title={description}
data-testid="entity-reference-chip"
className="inline-flex max-w-[180px] cursor-default items-center gap-0.5 rounded bg-primary/10 px-1.5 py-0.5 align-baseline text-xs text-primary"
>
<IconHash className="h-3 w-3 shrink-0" aria-hidden="true" />
<span className="truncate">{label}</span>
</span>
</NodeViewWrapper>
);
}
@@ -0,0 +1,98 @@
import { PluginKey } from "@tiptap/pm/state";
import type {
SuggestionKeyDownProps,
SuggestionOptions,
SuggestionProps,
} from "@tiptap/suggestion";
import type { EntityReference } from "@/lib/types/entity-reference";
import { isEntityReferenceTriggerAllowed } from "./tiptap-helpers";
import type { MenuState } from "./tiptap-suggestion";
const EMPTY_ENTITY_REFERENCE_STATE: MenuState<EntityReference> = {
isOpen: false,
items: [],
query: "",
clientRect: null,
command: null,
};
export const EntityReferenceSuggestionPluginKey = new PluginKey("entityReferenceSuggestion");
export function handleEntityReferenceMenuKeyDown(args: {
event: KeyboardEvent;
items: readonly EntityReference[];
selectedIndex: number;
setSelectedIndex: (index: number) => void;
onSelect: (reference: EntityReference) => void;
}): boolean {
if (args.event.key === "ArrowDown" || args.event.key === "ArrowUp") {
if (args.items.length > 0) {
const delta = args.event.key === "ArrowDown" ? 1 : -1;
const next = Math.min(Math.max(args.selectedIndex + delta, 0), args.items.length - 1);
args.setSelectedIndex(next);
}
return true;
}
if (args.event.key !== "Enter" && args.event.key !== "Tab") return false;
const item = args.items[args.selectedIndex];
if (!item) return false;
args.onSelect(item);
return true;
}
export function createEntityReferenceSuggestion(
setMenuState: (state: MenuState<EntityReference>) => void,
onKeyDown: (event: KeyboardEvent) => boolean,
): Partial<SuggestionOptions<EntityReference>> {
return {
char: "#",
pluginKey: EntityReferenceSuggestionPluginKey,
allowSpaces: true,
allowedPrefixes: null,
allow: ({ state, range }) => {
const $from = state.doc.resolve(range.from);
const triggerOffset = range.from - $from.start();
return isEntityReferenceTriggerAllowed({
textBeforeTrigger: $from.parent.textBetween(0, triggerOffset, "\0", "\0"),
parentType: $from.parent.type.name,
hasCodeMark: $from.marks().some((mark) => mark.type.name === "code"),
});
},
items: () => [],
command: ({ editor, range, props }) => {
editor
.chain()
.focus()
.insertContentAt(range, [
{ type: "entityReference", attrs: props },
{ type: "text", text: " " },
])
.run();
},
render: () => {
const updateMenu = (props: SuggestionProps<EntityReference>) => {
setMenuState({
isOpen: true,
items: [],
query: props.query,
clientRect: props.clientRect ?? null,
command: (reference) => props.command(reference),
});
};
return {
onStart: updateMenu,
onUpdate: updateMenu,
onKeyDown(keyDown: SuggestionKeyDownProps) {
if (keyDown.event.key === "Escape") {
setMenuState(EMPTY_ENTITY_REFERENCE_STATE);
return true;
}
return onKeyDown(keyDown.event);
},
onExit() {
setMenuState(EMPTY_ENTITY_REFERENCE_STATE);
},
};
},
};
}
@@ -1,7 +1,105 @@
import { describe, expect, it } from "vitest";
import { getMarkdownText, textToEditorContent } from "./tiptap-helpers";
import * as tiptapHelpers from "./tiptap-helpers";
describe("entity reference trigger", () => {
it("provides a trigger-context guard for # suggestions", () => {
expect(typeof (tiptapHelpers as Record<string, unknown>).isEntityReferenceTriggerAllowed).toBe(
"function",
);
});
it("allows # only at a block start or after whitespace outside code", () => {
const allowed = tiptapHelpers.isEntityReferenceTriggerAllowed as unknown as (args: {
textBeforeTrigger: string;
parentType: string;
hasCodeMark: boolean;
}) => boolean;
expect(allowed({ textBeforeTrigger: "", parentType: "paragraph", hasCodeMark: false })).toBe(
true,
);
expect(
allowed({ textBeforeTrigger: "Discuss ", parentType: "paragraph", hasCodeMark: false }),
).toBe(true);
expect(
allowed({ textBeforeTrigger: "issue", parentType: "paragraph", hasCodeMark: false }),
).toBe(false);
expect(allowed({ textBeforeTrigger: "", parentType: "codeBlock", hasCodeMark: false })).toBe(
false,
);
expect(allowed({ textBeforeTrigger: "", parentType: "paragraph", hasCodeMark: true })).toBe(
false,
);
});
});
describe("entity reference metadata", () => {
it("provides structured extraction from editor JSON", () => {
expect(typeof (tiptapHelpers as Record<string, unknown>).extractEntityReferences).toBe(
"function",
);
});
it("extracts valid atoms in first-appearance order and deduplicates by ref", () => {
const reference = {
version: 1,
ref: "mention:v1:linear:issue:linear.app%2Forg-1:issue-1",
provider: "linear",
kind: "issue",
id: "issue-1",
key: "ENG-1",
title: "Fix login",
url: "https://linear.app/acme/issue/ENG-1/fix-login",
scope: "linear.app/org-1",
};
const extract = tiptapHelpers.extractEntityReferences as unknown as (doc: {
content: unknown[];
}) => (typeof reference)[];
expect(
extract({
content: [
{
type: "paragraph",
content: [
{ type: "entityReference", attrs: reference },
{ type: "entityReference", attrs: reference },
{ type: "entityReference", attrs: { ref: "malformed" } },
],
},
],
}),
).toEqual([reference]);
});
});
describe("getMarkdownText", () => {
it("serializes entity reference atoms as portable Markdown links", () => {
expect(
getMarkdownText({
getJSON: () => ({
content: [
{
type: "paragraph",
content: [
{ type: "text", text: "Track " },
{
type: "entityReference",
attrs: {
key: "ENG-123",
title: "Fix [auth] flow",
url: "https://jira.example.test/browse/ENG-123",
},
},
],
},
],
}),
}),
).toBe("Track [#ENG-123](https://jira.example.test/browse/ENG-123)");
});
it("serializes slash command chips as slash command text", () => {
expect(
getMarkdownText({
@@ -102,4 +200,49 @@ describe("textToEditorContent", () => {
],
});
});
it("restores generated reference Markdown only when matching metadata is present", () => {
const reference = {
version: 1,
ref: "mention:v1:jira:issue:scope:10001",
provider: "jira",
kind: "issue",
id: "10001",
key: "ENG-123",
title: "Fix authentication",
url: "https://jira.example.test/browse/ENG-123",
scope: "jira.example.test/site-1",
};
const restore = textToEditorContent as unknown as (
text: string,
commands: readonly (typeof slowCommand)[],
references: readonly (typeof reference)[],
) => ReturnType<typeof textToEditorContent>;
const content = restore(
"See [#ENG-123](https://jira.example.test/browse/ENG-123) and [docs](https://example.test)",
[],
[reference],
);
expect(content.content?.[0]?.content).toEqual([
{ type: "text", text: "See " },
{ type: "entityReference", attrs: reference },
{ type: "text", text: " and [docs](https://example.test)" },
]);
});
it("keeps generated-looking links literal without structured metadata", () => {
const content = textToEditorContent(
"See [#ENG-123](https://jira.example.test/browse/ENG-123)",
[],
);
expect(content.content?.[0]?.content).toEqual([
{
type: "text",
text: "See [#ENG-123](https://jira.example.test/browse/ENG-123)",
},
]);
});
});
@@ -1,4 +1,6 @@
import type React from "react";
import type { EntityReference } from "@/lib/types/entity-reference";
import { isEntityReference } from "@/lib/entity-references/message-references";
import { formatSlashCommandLabel, normalizeSlashCommandName } from "./tiptap-slash-command-utils";
import type { SlashCommand } from "./slash-command-types";
@@ -19,6 +21,38 @@ export type EditorContentNode = {
content?: EditorContentNode[];
};
export function isEntityReferenceTriggerAllowed(args: {
textBeforeTrigger: string;
parentType: string;
hasCodeMark: boolean;
}): boolean {
if (args.parentType === "codeBlock" || args.hasCodeMark) return false;
return args.textBeforeTrigger === "" || /\s$/u.test(args.textBeforeTrigger);
}
function entityReferenceFromAttrs(attrs: Record<string, unknown> | undefined) {
if (!attrs) return null;
const candidate = attrs.key === null ? { ...attrs, key: undefined } : attrs;
return isEntityReference(candidate) ? candidate : null;
}
export function extractEntityReferences(doc: JSONNode): EntityReference[] {
const references: EntityReference[] = [];
const seen = new Set<string>();
const visit = (node: JSONNode) => {
if (node.type === "entityReference") {
const reference = entityReferenceFromAttrs(node.attrs);
if (reference && !seen.has(reference.ref)) {
seen.add(reference.ref);
references.push(reference);
}
}
node.content?.forEach(visit);
};
visit(doc);
return references;
}
// ── Serialization ───────────────────────────────────────────────────
function serializeInline(nodes: JSONNode[]): string {
@@ -28,6 +62,9 @@ function serializeInline(nodes: JSONNode[]): string {
if (n.type === "contextMention") {
return n.attrs?.label ? `@${n.attrs.label}` : "";
}
if (n.type === "entityReference") {
return formatEntityReferenceMarkdown(n.attrs as Partial<EntityReference>);
}
if (n.type === "slashCommand") {
return formatSlashCommandLabel(n.attrs);
}
@@ -40,6 +77,21 @@ function serializeInline(nodes: JSONNode[]): string {
.join("");
}
function escapeMarkdownLabel(value: string): string {
return value.replace(/([\\[\]])/g, "\\$1");
}
function encodeMarkdownUrl(value: string): string {
return encodeURI(value).replace(/\(/g, "%28").replace(/\)/g, "%29");
}
export function formatEntityReferenceMarkdown(reference: Partial<EntityReference>): string {
const label = String(reference.key || reference.title || "");
const url = String(reference.url || "");
if (!label || !url) return "";
return `[#${escapeMarkdownLabel(label)}](${encodeMarkdownUrl(url)})`;
}
function serializeNode(node: JSONNode): string {
switch (node.type) {
case "paragraph":
@@ -108,7 +160,7 @@ function slashCommandMap(commands: readonly SlashCommand[]): Map<string, SlashCo
return map;
}
function textLineToNodes(line: string, commands: Map<string, SlashCommand>): EditorContentNode[] {
function slashTextToNodes(line: string, commands: Map<string, SlashCommand>): EditorContentNode[] {
const nodes: EditorContentNode[] = [];
const tokenPattern = /\/\S+/g;
let cursor = 0;
@@ -129,9 +181,44 @@ function textLineToNodes(line: string, commands: Map<string, SlashCommand>): Edi
return nodes;
}
function entityReferenceTokens(references: readonly EntityReference[]) {
return references
.map((reference) => ({ reference, markdown: formatEntityReferenceMarkdown(reference) }))
.filter((token) => token.markdown.length > 0);
}
function textLineToNodes(
line: string,
commands: Map<string, SlashCommand>,
references: readonly EntityReference[],
): EditorContentNode[] {
const tokens = entityReferenceTokens(references);
if (tokens.length === 0) return slashTextToNodes(line, commands);
const nodes: EditorContentNode[] = [];
let cursor = 0;
while (cursor < line.length) {
let match: { index: number; markdown: string; reference: EntityReference } | null = null;
for (const token of tokens) {
const index = line.indexOf(token.markdown, cursor);
if (index !== -1 && (!match || index < match.index)) match = { ...token, index };
}
if (!match) {
nodes.push(...slashTextToNodes(line.slice(cursor), commands));
break;
}
if (match.index > cursor) {
nodes.push(...slashTextToNodes(line.slice(cursor, match.index), commands));
}
nodes.push({ type: "entityReference", attrs: { ...match.reference } });
cursor = match.index + match.markdown.length;
}
return nodes;
}
export function textToEditorContent(
text: string,
slashCommands: readonly SlashCommand[] = [],
entityReferences: readonly EntityReference[] = [],
): EditorContentNode {
const commands = slashCommandMap(slashCommands);
const content: EditorContentNode[] = [];
@@ -142,7 +229,7 @@ export function textToEditorContent(
if (inCodeFence || isFenceLine) {
nodes = line ? [{ type: "text", text: line }] : [];
} else {
nodes = textLineToNodes(line, commands);
nodes = textLineToNodes(line, commands, entityReferences);
}
content.push(nodes.length > 0 ? { type: "paragraph", content: nodes } : { type: "paragraph" });
if (isFenceLine) inCodeFence = !inCodeFence;
+37 -14
View File
@@ -10,17 +10,17 @@ import {
useMemo,
} from "react";
import { EditorContent } from "@tiptap/react";
import { useShallow } from "zustand/react/shallow";
import { useCustomPrompts } from "@/hooks/domains/settings/use-custom-prompts";
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
import { getWebSocketClient } from "@/lib/ws/connection";
import { searchWorkspaceFiles } from "@/lib/ws/workspace-files";
import { EditorContextProvider } from "./editor-context";
import { EntityReferenceMenu } from "./entity-reference-menu";
import { MentionMenu } from "./mention-menu";
import { MessageHistorySearch } from "./message-history-search";
import { SlashCommandMenu } from "./slash-command-menu";
import { buildTaskMentionItems } from "./task-mention-items";
import { extractUserHistory } from "./message-history";
import { createMessageHistorySelector, type MessageHistoryEntry } from "./message-history";
import { useDrainOlderMessages } from "./use-drain-older-messages";
import {
createMentionSuggestion,
@@ -33,6 +33,7 @@ import { useTipTapEditor, type TipTapInputHandle } from "./use-tiptap-editor";
import type { MentionItem } from "@/hooks/use-inline-mention";
import type { SlashCommand } from "./slash-command-types";
import type { ContextFile } from "@/lib/state/context-files-store";
import { useEntityReferenceComposer } from "./use-entity-reference-composer";
export type { TipTapInputHandle } from "./use-tiptap-editor";
@@ -52,6 +53,8 @@ type TipTapInputProps = {
// TipTap-specific
sessionId: string | null;
taskId?: string | null;
workspaceId?: string | null;
entityReferencesEnabled?: boolean;
onAddContextFile?: (file: ContextFile) => void;
onToggleContextFile?: (file: ContextFile) => void;
planContextEnabled?: boolean;
@@ -361,6 +364,8 @@ export const TipTapInput = forwardRef<TipTapInputHandle, TipTapInputProps>(funct
onBlur,
sessionId,
taskId,
workspaceId = null,
entityReferencesEnabled = false,
onImagePaste,
},
ref,
@@ -374,9 +379,15 @@ export const TipTapInput = forwardRef<TipTapInputHandle, TipTapInputProps>(funct
setMentionMenu: menu.setMentionMenu,
setSlashMenu: menu.setSlashMenu,
});
const entityReferences = useEntityReferenceComposer({
enabled: entityReferencesEnabled,
workspaceId,
sessionId,
});
const isSuggestionMenuOpen =
(menu.mentionMenu.isOpen && menu.mentionMenu.items.length > 0) ||
(menu.slashMenu.isOpen && menu.slashMenu.items.length > 0);
(menu.slashMenu.isOpen && menu.slashMenu.items.length > 0) ||
entityReferences.isOpen;
const { history, getHistory } = useChatHistory(sessionId);
const { editorWrapperRef, ...overlay } = useReverseSearchOverlay(sessionId);
const { isDraining } = useDrainOlderMessages(sessionId, overlay.isReverseSearchOpen);
@@ -396,6 +407,7 @@ export const TipTapInput = forwardRef<TipTapInputHandle, TipTapInputProps>(funct
onImagePaste,
mentionSuggestion,
slashSuggestion,
entityReferenceSuggestion: entityReferences.suggestion,
slashCommands,
isSuggestionMenuOpen,
getHistory,
@@ -416,6 +428,7 @@ export const TipTapInput = forwardRef<TipTapInputHandle, TipTapInputProps>(funct
<>
<TipTapPopups
menu={menu}
entityReferences={entityReferences}
overlay={overlay}
history={history}
isDraining={isDraining}
@@ -435,14 +448,16 @@ export const TipTapInput = forwardRef<TipTapInputHandle, TipTapInputProps>(funct
type TipTapPopupsProps = {
menu: ReturnType<typeof useMenuHandlers>;
entityReferences: ReturnType<typeof useEntityReferenceComposer>;
overlay: Omit<ReturnType<typeof useReverseSearchOverlay>, "editorWrapperRef">;
history: readonly string[];
history: readonly MessageHistoryEntry[];
isDraining: boolean;
onReverseSearchSelect: (index: number) => void;
};
function TipTapPopups({
menu,
entityReferences,
overlay,
history,
isDraining,
@@ -461,6 +476,19 @@ function TipTapPopups({
onClose={menu.handleMentionClose}
setSelectedIndex={menu.setMentionSelectedIndex}
/>
<EntityReferenceMenu
isOpen={entityReferences.isOpen}
clientRect={entityReferences.clientRect}
groups={entityReferences.groups}
query={entityReferences.query}
selectedIndex={entityReferences.selectedIndex}
isSearching={entityReferences.isSearching}
error={entityReferences.error}
onRetry={entityReferences.retry}
onSelect={entityReferences.selectReference}
onClose={entityReferences.close}
setSelectedIndex={entityReferences.setSelectedIndex}
/>
<SlashCommandMenu
isOpen={menu.slashMenu.isOpen}
clientRect={menu.slashMenu.clientRect}
@@ -483,16 +511,11 @@ function TipTapPopups({
);
}
function useMessageHistoryForSession(sessionId: string | null): string[] {
// Subscribe to the *derived* user history (not the raw messages array) via a
// shallow comparison: agent streaming tokens churn the messages array every
// frame but don't change the user's sent-message history, so the rich editor
// only re-renders when the history list itself changes.
return useAppStore(
useShallow((s) =>
extractUserHistory((sessionId ? s.messages.bySession[sessionId] : undefined) ?? []),
),
);
function useMessageHistoryForSession(sessionId: string | null): MessageHistoryEntry[] {
// The memoized selector keeps its snapshot stable while agent messages
// stream, but still reacts to user content or reference-metadata changes.
const selector = useMemo(() => createMessageHistorySelector(sessionId), [sessionId]);
return useAppStore(selector);
}
function useChatHistory(sessionId: string | null) {
@@ -0,0 +1,212 @@
import { describe, expect, it, vi } from "vitest";
import type { MentionItem } from "@/hooks/use-inline-mention";
import type { EntityReference } from "@/lib/types/entity-reference";
import {
createEntityReferenceSuggestion,
handleEntityReferenceMenuKeyDown,
} from "./tiptap-entity-reference-suggestion";
import { createMentionSuggestion } from "./tiptap-suggestion";
import * as entityReferenceSuggestions from "./tiptap-entity-reference-suggestion";
describe("entity reference suggestion", () => {
it("provides an independent # suggestion config", () => {
expect(
typeof (entityReferenceSuggestions as Record<string, unknown>)
.createEntityReferenceSuggestion,
).toBe("function");
});
it("provides keyboard navigation for grouped reference results", () => {
expect(
typeof (entityReferenceSuggestions as Record<string, unknown>)
.handleEntityReferenceMenuKeyDown,
).toBe("function");
});
it("uses arrows to move and Enter or Tab to select without submitting", () => {
const handle = handleEntityReferenceMenuKeyDown as unknown as (args: {
event: KeyboardEvent;
items: EntityReference[];
selectedIndex: number;
setSelectedIndex: (index: number) => void;
onSelect: (reference: EntityReference) => void;
}) => boolean;
const items = [
{
version: 1,
ref: "mention:v1:kandev:task:task-1",
provider: "kandev",
kind: "task",
id: "task-1",
title: "First task",
url: "/t/task-1",
scope: "workspace-1",
},
{
version: 1,
ref: "mention:v1:kandev:task:task-2",
provider: "kandev",
kind: "task",
id: "task-2",
title: "Second task",
url: "/t/task-2",
scope: "workspace-1",
},
];
const setSelectedIndex = vi.fn();
const onSelect = vi.fn();
expect(
handle({
event: new KeyboardEvent("keydown", { key: "ArrowDown" }),
items,
selectedIndex: 0,
setSelectedIndex,
onSelect,
}),
).toBe(true);
expect(setSelectedIndex).toHaveBeenCalledWith(1);
expect(
handle({
event: new KeyboardEvent("keydown", { key: "Tab" }),
items,
selectedIndex: 1,
setSelectedIndex,
onSelect,
}),
).toBe(true);
expect(onSelect).toHaveBeenCalledWith(items[1]);
});
});
describe("entity reference suggestion lifecycle", () => {
it("replaces only the active # range with an atom and trailing space", () => {
const suggestion = createEntityReferenceSuggestion(vi.fn(), vi.fn());
const run = vi.fn();
const insertContentAt = vi.fn(() => ({ run }));
const focus = vi.fn(() => ({ insertContentAt }));
const editor = { chain: () => ({ focus }) };
const reference: EntityReference = {
version: 1,
ref: "mention:v1:github:pull_request:github.com/acme/app:42",
provider: "github",
kind: "pull_request",
id: "MDExOlB1bGxSZXF1ZXN0NDI=",
key: "42",
title: "Fix authentication",
url: "https://github.com/acme/app/pull/42",
scope: "github.com/acme/app",
};
expect(typeof suggestion.command).toBe("function");
suggestion.command?.({
editor: editor as never,
range: { from: 8, to: 13 },
props: reference,
});
expect(insertContentAt).toHaveBeenCalledWith({ from: 8, to: 13 }, [
{ type: "entityReference", attrs: reference },
{ type: "text", text: " " },
]);
expect(run).toHaveBeenCalledOnce();
});
it("opens in the primed state for bare # and Escape closes without selecting", () => {
const setMenuState = vi.fn();
const suggestion = createEntityReferenceSuggestion(setMenuState, vi.fn());
const lifecycle = suggestion.render?.();
const props = {
editor: {} as never,
range: { from: 1, to: 2 },
query: "",
text: "#",
items: [],
command: vi.fn(),
decorationNode: null,
clientRect: () => new DOMRect(10, 20, 1, 10),
};
expect(lifecycle).toBeDefined();
lifecycle?.onStart?.(props);
expect(setMenuState).toHaveBeenLastCalledWith(
expect.objectContaining({ isOpen: true, query: "", items: [] }),
);
const handled = lifecycle?.onKeyDown?.({
view: {} as never,
event: new KeyboardEvent("keydown", { key: "Escape" }),
range: props.range,
});
expect(handled).toBe(true);
expect(setMenuState).toHaveBeenLastCalledWith({
isOpen: false,
items: [],
query: "",
clientRect: null,
command: null,
});
expect(props.command).not.toHaveBeenCalled();
});
it("allows # at a text-block boundary but rejects tokens and code", () => {
const suggestion = createEntityReferenceSuggestion(vi.fn(), vi.fn());
const allowed = (prefix: string, parentType = "paragraph", hasCodeMark = false) => {
const resolved = {
parent: {
type: { name: parentType },
textBetween: () => prefix,
},
start: () => 1,
marks: () => (hasCodeMark ? [{ type: { name: "code" } }] : []),
};
return suggestion.allow?.({
editor: {} as never,
state: { doc: { resolve: () => resolved } } as never,
range: { from: prefix.length + 1, to: prefix.length + 2 },
});
};
expect(typeof suggestion.allow).toBe("function");
expect(allowed("")).toBe(true);
expect(allowed("Discuss ")).toBe(true);
expect(allowed("issue")).toBe(false);
expect(allowed("", "codeBlock")).toBe(false);
expect(allowed("", "paragraph", true)).toBe(false);
});
});
describe("createMentionSuggestion", () => {
it("keeps Kandev task discovery in the @ menu", async () => {
const file: MentionItem = {
id: "src/app.ts",
kind: "file",
label: "src/app.ts",
onSelect: vi.fn(),
};
const task: MentionItem = {
id: "task:task-2",
kind: "task",
label: "Follow-up task",
task: {
taskId: "task-2",
title: "Follow-up task",
workflowId: "workflow-1",
workflowStepId: "step-1",
state: null,
},
onSelect: vi.fn(),
};
const suggestion = createMentionSuggestion(
{ getItems: vi.fn().mockResolvedValue([task, file]) },
vi.fn(),
vi.fn(),
);
const items = await (suggestion.items as (args: { query: string }) => Promise<MentionItem[]>)({
query: "Follow",
});
expect(items).toEqual([task, file]);
});
});
@@ -46,7 +46,6 @@ export type MentionSuggestionCallbacks = {
};
export const MentionSuggestionPluginKey = new PluginKey("mentionSuggestion");
/**
* Creates a mention suggestion config for TipTap.
* `setMenuState` drives the React rendering of MentionMenu.
@@ -73,9 +72,7 @@ export function createMentionSuggestion(
pluginKey: MentionSuggestionPluginKey,
allowSpaces: false,
items: async ({ query }) => {
return callbacks.getItems(query);
},
items: ({ query }) => callbacks.getItems(query),
command: ({ editor, range, props: mentionAttrs }) => {
editor
@@ -6,10 +6,10 @@ import { useResizableInput } from "@/hooks/use-resizable-input";
import { useChatInputState } from "./use-chat-input-state";
import type { TipTapInputHandle } from "./tiptap-input";
import type { ContextItem } from "@/lib/types/context";
import type { ContextFile } from "@/lib/state/context-files-store";
import type { Message } from "@/lib/types/http";
import type { DiffComment } from "@/lib/diff/types";
import type {
ChatSubmitPayload,
ChatSubmitResult,
MessageAttachment,
ChatInputContainerHandle,
@@ -42,13 +42,7 @@ type UseChatInputContainerParams = {
hasContextComments: boolean;
showRequestChangesTooltip: boolean;
onRequestChangesTooltipDismiss: (() => void) | undefined;
onSubmit: (
message: string,
reviewComments?: DiffComment[],
attachments?: MessageAttachment[],
inlineMentions?: ContextFile[],
inlineTaskMentions?: import("@/hooks/use-inline-mention").TaskMentionData[],
) => ChatSubmitResult;
onSubmit: (payload: ChatSubmitPayload) => ChatSubmitResult;
};
function useInputHandle(
@@ -3,6 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type React from "react";
import { useChatInputState } from "./use-chat-input-state";
import type { TipTapInputHandle } from "./tiptap-input";
import type { EntityReference } from "@/lib/types/entity-reference";
type SubmitHandler = Parameters<typeof useChatInputState>[0]["onSubmit"];
@@ -18,14 +19,31 @@ function renderInputState(onSubmit: SubmitHandler) {
);
}
function attachInputHandle(inputRef: React.RefObject<TipTapInputHandle | null>, clear: () => void) {
function attachInputHandle(
inputRef: React.RefObject<TipTapInputHandle | null>,
clear: () => void,
entityReferences: EntityReference[] = [],
) {
(inputRef as React.MutableRefObject<Partial<TipTapInputHandle> | null>).current = {
clear,
getMentions: () => [],
getTaskMentions: () => [],
getEntityReferences: () => entityReferences,
};
}
const reference: EntityReference = {
version: 1,
ref: "mention:v1:github:issue:acme%2Frepo:42",
provider: "github",
kind: "issue",
id: "42",
key: "acme/repo#42",
title: "Fix composer references",
url: "https://github.com/acme/repo/issues/42",
scope: "acme/repo",
};
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((res) => {
@@ -56,13 +74,33 @@ describe("useChatInputState", () => {
result.current.handleSubmit(vi.fn());
});
await waitFor(() =>
expect(onSubmit).toHaveBeenCalledWith("hello", undefined, undefined, undefined, undefined),
);
await waitFor(() => expect(onSubmit).toHaveBeenCalledWith({ message: "hello" }));
expect(result.current.value).toBe("hello");
expect(clear).not.toHaveBeenCalled();
});
it("captures structured entity references in the named submit payload", async () => {
const onSubmit = vi.fn<(...args: Parameters<SubmitHandler>) => ReturnType<SubmitHandler>>();
const { result } = renderInputState(onSubmit);
act(() => {
result.current.handleChange("[#acme/repo#42](https://github.com/acme/repo/issues/42)");
attachInputHandle(result.current.inputRef, vi.fn(), [reference]);
});
await waitFor(() => expect(result.current.value).toContain("acme/repo#42"));
act(() => {
result.current.handleSubmit(vi.fn());
});
await waitFor(() =>
expect(onSubmit).toHaveBeenCalledWith({
message: "[#acme/repo#42](https://github.com/acme/repo/issues/42)",
entityReferences: [reference],
}),
);
});
it("clears the draft when async submit succeeds", async () => {
const onSubmit = vi
.fn<(...args: Parameters<SubmitHandler>) => ReturnType<SubmitHandler>>()
@@ -26,11 +26,13 @@ import {
type FileAttachment,
} from "./file-attachment";
import type { ContextItem, ImageContextItem, FileAttachmentContextItem } from "@/lib/types/context";
import type { ContextFile } from "@/lib/state/context-files-store";
import type { DiffComment } from "@/lib/diff/types";
import type { ChatSubmitResult, MessageAttachment } from "./chat-input-container";
import type {
ChatSubmitPayload,
ChatSubmitResult,
MessageAttachment,
} from "./chat-input-container";
import type { TipTapInputHandle } from "./tiptap-input";
import type { TaskMentionData } from "@/hooks/use-inline-mention";
type UseChatInputStateProps = {
sessionId: string | null;
@@ -41,13 +43,7 @@ type UseChatInputStateProps = {
hasContextComments?: boolean;
showRequestChangesTooltip: boolean;
onRequestChangesTooltipDismiss?: () => void;
onSubmit: (
message: string,
reviewComments?: DiffComment[],
attachments?: MessageAttachment[],
inlineMentions?: ContextFile[],
inlineTaskMentions?: TaskMentionData[],
) => ChatSubmitResult;
onSubmit: (payload: ChatSubmitPayload) => ChatSubmitResult;
};
function isPromiseLike(value: ChatSubmitResult): value is Promise<void | boolean> {
@@ -163,6 +159,14 @@ type SubmitDraftArgs = {
clearArgs: Omit<ClearSubmittedInputArgs, "submittedText" | "submittedAttachments">;
};
function buildChatSubmitPayload(payload: Required<ChatSubmitPayload>): ChatSubmitPayload {
return Object.fromEntries(
Object.entries(payload).filter(
([key, value]) => key === "message" || (Array.isArray(value) && value.length > 0),
),
) as ChatSubmitPayload;
}
function submitDraft(args: SubmitDraftArgs) {
if (args.isSending) return;
const trimmed = args.valueRef.current.trim();
@@ -175,12 +179,16 @@ function submitDraft(args: SubmitDraftArgs) {
const messageAttachments = toMessageAttachments(currentAttachments);
const inlineMentions = args.inputRef.current?.getMentions() ?? [];
const inlineTaskMentions = args.inputRef.current?.getTaskMentions() ?? [];
const entityReferences = args.inputRef.current?.getEntityReferences() ?? [];
const result = args.onSubmit(
trimmed,
allComments.length > 0 ? allComments : undefined,
messageAttachments.length > 0 ? messageAttachments : undefined,
inlineMentions.length > 0 ? inlineMentions : undefined,
inlineTaskMentions.length > 0 ? inlineTaskMentions : undefined,
buildChatSubmitPayload({
message: trimmed,
reviewComments: allComments,
attachments: messageAttachments,
inlineMentions,
inlineTaskMentions,
entityReferences,
}),
);
handleSubmitResult(result, () =>
clearSubmittedInput({
@@ -0,0 +1,42 @@
import { cleanup, renderHook } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
vi.mock("@/hooks/use-entity-reference-search", () => ({
useEntityReferenceSearch: () => ({
groups: [],
isSearching: false,
error: null,
retry: vi.fn(),
}),
}));
import { useEntityReferenceComposer } from "./use-entity-reference-composer";
afterEach(cleanup);
describe("useEntityReferenceComposer lifecycle", () => {
it("installs the # suggestion on an enabled surface before workspace hydration", () => {
const { result } = renderHook(() =>
useEntityReferenceComposer({
enabled: true,
workspaceId: null,
sessionId: "session-1",
}),
);
expect(result.current.suggestion).toBeDefined();
expect(result.current.isOpen).toBe(false);
});
it("does not install the # suggestion on an out-of-scope surface", () => {
const { result } = renderHook(() =>
useEntityReferenceComposer({
enabled: false,
workspaceId: "workspace-1",
sessionId: "session-1",
}),
);
expect(result.current.suggestion).toBeUndefined();
});
});
@@ -0,0 +1,98 @@
"use client";
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useEntityReferenceSearch } from "@/hooks/use-entity-reference-search";
import type { EntityReference } from "@/lib/types/entity-reference";
import {
createEntityReferenceSuggestion,
handleEntityReferenceMenuKeyDown,
} from "./tiptap-entity-reference-suggestion";
import type { MenuState } from "./tiptap-suggestion";
import { selectableEntityReferences } from "./entity-reference-groups";
const EMPTY_REFERENCE_MENU: MenuState<EntityReference> = {
isOpen: false,
items: [],
query: "",
clientRect: null,
command: null,
};
type UseEntityReferenceComposerOptions = {
enabled: boolean;
workspaceId: string | null;
sessionId: string | null;
};
export function useEntityReferenceComposer({
enabled,
workspaceId,
sessionId,
}: UseEntityReferenceComposerOptions) {
const [menu, setMenu] = useState<MenuState<EntityReference>>(EMPTY_REFERENCE_MENU);
const [selectedIndex, setSelectedIndex] = useState(0);
const searchEnabled =
enabled && Boolean(workspaceId) && menu.isOpen && Boolean(menu.query.trim());
const search = useEntityReferenceSearch({
workspaceId,
sessionId,
query: menu.query,
enabled: searchEnabled,
});
const items = useMemo(() => selectableEntityReferences(search.groups), [search.groups]);
const clampedSelectedIndex = Math.min(selectedIndex, Math.max(0, items.length - 1));
const itemsRef = useRef(items);
const selectedIndexRef = useRef(clampedSelectedIndex);
const commandRef = useRef(menu.command);
useLayoutEffect(() => {
itemsRef.current = items;
selectedIndexRef.current = clampedSelectedIndex;
commandRef.current = menu.command;
});
useEffect(() => {
void Promise.resolve().then(() => setSelectedIndex(0));
}, [items]);
useEffect(() => {
void Promise.resolve().then(() => setMenu(EMPTY_REFERENCE_MENU));
}, [enabled, sessionId, workspaceId]);
const selectReference = useCallback((reference: EntityReference) => {
commandRef.current?.(reference);
setMenu(EMPTY_REFERENCE_MENU);
}, []);
const onKeyDown = useCallback(
(event: KeyboardEvent) =>
handleEntityReferenceMenuKeyDown({
event,
items: itemsRef.current,
selectedIndex: selectedIndexRef.current,
setSelectedIndex,
onSelect: selectReference,
}),
[selectReference],
);
const suggestion = useMemo(
() => createEntityReferenceSuggestion(setMenu, onKeyDown),
[onKeyDown],
);
const close = useCallback(() => setMenu(EMPTY_REFERENCE_MENU), []);
const hasWorkspace = Boolean(workspaceId);
return {
suggestion: enabled ? suggestion : undefined,
isOpen: enabled && hasWorkspace && menu.isOpen,
clientRect: menu.clientRect,
query: menu.query,
groups: search.groups,
isSearching: search.isSearching,
error: search.error,
retry: search.retry,
selectedIndex: clampedSelectedIndex,
setSelectedIndex,
selectReference,
close,
};
}
@@ -1,5 +1,11 @@
import { describe, expect, it } from "vitest";
import { TIPTAP_EDITOR_TEXT_SIZE_CLASS, decideSubmitShortcut } from "./use-tiptap-editor";
import { Extension } from "@tiptap/core";
import {
TIPTAP_EDITOR_TEXT_SIZE_CLASS,
buildEditorExtensions,
decideSubmitShortcut,
} from "./use-tiptap-editor";
import * as tiptapEditor from "./use-tiptap-editor";
import { decideHistoryNav } from "./tiptap-editor-history";
describe("TIPTAP_EDITOR_TEXT_SIZE_CLASS", () => {
@@ -10,6 +16,44 @@ describe("TIPTAP_EDITOR_TEXT_SIZE_CLASS", () => {
});
});
describe("editor extensions", () => {
it("exposes the extension builder for editor-contract verification", () => {
expect(typeof (tiptapEditor as Record<string, unknown>).buildEditorExtensions).toBe("function");
});
it("installs the separate entityReference atom", () => {
const extensions = buildEditorExtensions({
mentionSuggestion: {},
slashSuggestion: {},
submitKeymap: Extension.create({ name: "submit-test" }),
historyKeymap: Extension.create({ name: "history-test" }),
});
expect(extensions.map((extension) => extension.name)).toContain("entityReference");
});
it("registers the # suggestion plugin independently from @ and slash", () => {
const entityReferenceSuggestion = { char: "#" };
const build = buildEditorExtensions as unknown as (args: {
mentionSuggestion: object;
slashSuggestion: object;
entityReferenceSuggestion: object;
submitKeymap: Extension;
historyKeymap: Extension;
}) => ReturnType<typeof buildEditorExtensions>;
const extensions = build({
mentionSuggestion: { char: "@" },
slashSuggestion: { char: "/" },
entityReferenceSuggestion,
submitKeymap: Extension.create({ name: "submit-test" }),
historyKeymap: Extension.create({ name: "history-test" }),
});
const contextMention = extensions.find((extension) => extension.name === "contextMention");
expect(contextMention?.options.suggestions).toContain(entityReferenceSuggestion);
});
});
describe("decideSubmitShortcut", () => {
describe("submitKey=enter", () => {
it("submits on Enter when no suggestion menu is open", () => {
@@ -10,9 +10,7 @@ import History from "@tiptap/extension-history";
import { Plugin, PluginKey } from "@tiptap/pm/state";
import { matchesShortcut } from "@/lib/keyboard/utils";
import { getShortcut, type StoredShortcutOverrides } from "@/lib/keyboard/shortcut-overrides";
import { Node as ProseMirrorNode } from "@tiptap/pm/model";
import { Decoration, DecorationSet } from "@tiptap/pm/view";
import { Extension, isNodeEmpty } from "@tiptap/core";
import { Extension } from "@tiptap/core";
import { useHistoryKeymap } from "./tiptap-editor-history";
import Code from "@tiptap/extension-code";
import CodeBlockLowlight from "@tiptap/extension-code-block-lowlight";
@@ -20,13 +18,22 @@ import { common, createLowlight } from "lowlight";
import { cn } from "@/lib/utils";
import { useAppStore } from "@/components/state-provider";
import { getChatDraftContent, setChatDraftContent } from "@/lib/local-storage";
import { getMarkdownText, textToHtml, handleEditorPaste } from "./tiptap-helpers";
import {
extractEntityReferences,
getMarkdownText,
textToHtml,
handleEditorPaste,
} from "./tiptap-helpers";
import { CodeBlockView } from "./tiptap-code-block-view";
import { DynamicPlaceholder, updateDynamicPlaceholder } from "./tiptap-dynamic-placeholder";
import { EntityReferenceNode } from "./tiptap-entity-reference-extension";
import { ContextMention } from "./tiptap-mention-extension";
import { SlashCommandNode } from "./tiptap-slash-command-extension";
import type { ContextFile } from "@/lib/state/context-files-store";
import type { TaskMentionData } from "@/hooks/use-inline-mention";
import type { SlashCommand } from "./slash-command-types";
import type { EntityReference } from "@/lib/types/entity-reference";
import type { MessageHistoryEntry } from "./message-history";
export type TipTapInputHandle = {
focus: () => void;
@@ -39,70 +46,12 @@ export type TipTapInputHandle = {
insertText: (text: string, from: number, to: number) => void;
getMentions: () => ContextFile[];
getTaskMentions: () => TaskMentionData[];
getEntityReferences: () => EntityReference[];
};
const lowlightInstance = createLowlight(common);
export const TIPTAP_EDITOR_TEXT_SIZE_CLASS = "text-base leading-relaxed lg:text-sm";
/**
* Custom Placeholder extension that reads the current placeholder from
* editor.storage instead of from the captured options object. TipTap's
* extension.options is a getter returning a fresh object each call, so the
* built-in Placeholder plugin's closure captures a stale options snapshot.
* This wrapper uses editor.storage.dynamicPlaceholder.text as the live source.
*/
const DynamicPlaceholder = Extension.create({
name: "dynamicPlaceholder",
addStorage() {
return { text: "" };
},
addProseMirrorPlugins() {
const editor = this.editor;
return [
new Plugin({
key: new PluginKey("dynamicPlaceholder"),
props: {
decorations: ({ doc, selection }) => {
if (!editor.isEditable && !editor.isEmpty) return null;
const { anchor } = selection;
const decorations: InstanceType<typeof Decoration>[] = [];
const isEmptyDoc = editor.isEmpty;
doc.descendants((node: ProseMirrorNode, pos: number) => {
const hasAnchor = anchor >= pos && anchor <= pos + node.nodeSize;
const isEmpty = !node.isLeaf && isNodeEmpty(node);
if (hasAnchor && isEmpty) {
const classes = ["is-empty"];
if (isEmptyDoc) classes.push("is-editor-empty");
decorations.push(
Decoration.node(pos, pos + node.nodeSize, {
class: classes.join(" "),
// eslint-disable-next-line @typescript-eslint/no-explicit-any
"data-placeholder": (editor.storage as any).dynamicPlaceholder.text,
}),
);
}
return false;
});
return DecorationSet.create(doc, decorations);
},
},
}),
];
},
});
/** Update the dynamic placeholder text and trigger a redecoration. Extracted to a
* standalone function so that the eslint react-hooks/immutability rule does not
* flag it as a mutation of the `editor` hook argument. */
function updateDynamicPlaceholder(ed: ReturnType<typeof useEditor>, text: string) {
if (!ed) return;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(ed.storage as any).dynamicPlaceholder.text = text;
ed.view.dispatch(ed.state.tr);
}
type UseTipTapEditorOptions = {
value: string;
onChange: (value: string) => void;
@@ -121,6 +70,8 @@ type UseTipTapEditorOptions = {
mentionSuggestion: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
slashSuggestion: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
entityReferenceSuggestion?: any;
slashCommands: readonly SlashCommand[];
/** True when a slash/@ suggestion menu is open with selectable items. Enter
* must defer to the suggestion plugin so the highlighted item is inserted
@@ -129,7 +80,7 @@ type UseTipTapEditorOptions = {
/** Returns the user's previous messages for this session, newest-first. The
* caller maintains the actual list; the editor reads it on each keypress so
* ArrowUp/ArrowDown navigate the latest history without prop churn. */
getHistory: () => readonly string[];
getHistory: () => readonly MessageHistoryEntry[];
/** Open the Ctrl+R fuzzy search overlay. The overlay lives in the parent
* component (so it can position itself relative to the editor) — the editor
* only knows when to open it. */
@@ -192,11 +143,13 @@ function useTipTapRefs(opts: UseTipTapEditorOptions) {
};
}
function buildEditorExtensions(args: {
export function buildEditorExtensions(args: {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
mentionSuggestion: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
slashSuggestion: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
entityReferenceSuggestion?: any;
submitKeymap: Extension;
historyKeymap: Extension;
}) {
@@ -214,8 +167,13 @@ function buildEditorExtensions(args: {
}).configure({ lowlight: lowlightInstance }),
DynamicPlaceholder,
SlashCommandNode,
EntityReferenceNode,
ContextMention.configure({
suggestions: [args.mentionSuggestion, args.slashSuggestion],
suggestions: [
args.mentionSuggestion,
args.slashSuggestion,
...(args.entityReferenceSuggestion ? [args.entityReferenceSuggestion] : []),
],
}),
args.submitKeymap,
args.historyKeymap,
@@ -285,6 +243,7 @@ export function useTipTapEditor(opts: UseTipTapEditorOptions) {
extensions: buildEditorExtensions({
mentionSuggestion: opts.mentionSuggestion,
slashSuggestion: opts.slashSuggestion,
entityReferenceSuggestion: opts.entityReferenceSuggestion,
submitKeymap: SubmitKeymap,
historyKeymap: historyController.extension,
}),
@@ -587,6 +546,7 @@ function useEditorImperativeHandle(
});
return mentions;
},
getEntityReferences: () => (editor ? extractEntityReferences(editor.getJSON()) : []),
}),
[editor, onChange, isSyncingRef],
);
@@ -9,6 +9,7 @@ import { buildSubmitMessage } from "./chat/chat-input-area";
import {
ChatInputContainer,
type ChatInputContainerHandle,
type ChatSubmitPayload,
type MessageAttachment,
} from "./chat/chat-input-container";
import type { useChatPanelState } from "./chat/use-chat-panel-state";
@@ -23,13 +24,7 @@ import type { AppState } from "@/lib/state/store";
const PLAN_CONTEXT_PATH = "plan:context";
export type PassthroughSubmitHandler = (
content: string,
reviewComments?: DiffComment[],
attachments?: MessageAttachment[],
inlineMentions?: ContextFile[],
inlineTaskMentions?: TaskMentionData[],
) => Promise<void>;
export type PassthroughSubmitHandler = (payload: ChatSubmitPayload) => Promise<void>;
export function PassthroughComposerPanel({
refHandle,
@@ -67,6 +62,8 @@ export function PassthroughComposerPanel({
onSubmit={onSubmit}
sessionId={panelState.resolvedSessionId}
taskId={taskId}
workspaceId={null}
entityReferencesEnabled={false}
taskTitle={panelState.task?.title}
taskDescription={panelState.taskDescription ?? ""}
planModeEnabled={panelState.planModeEnabled}
@@ -294,13 +291,13 @@ export function useSendPassthroughMessage({
const storeApi = useAppStoreApi();
return useCallback(
async (
content: string,
reviewComments?: DiffComment[],
attachments?: MessageAttachment[],
inlineMentions?: ContextFile[],
inlineTaskMentions?: TaskMentionData[],
) => {
async ({
message: content,
reviewComments,
attachments,
inlineMentions,
inlineTaskMentions,
}: ChatSubmitPayload) => {
if (!taskId || !sessionId) {
toast({ title: "Session not ready", variant: "error" });
throw new Error("Session not ready");
@@ -204,9 +204,9 @@ vi.mock("./chat/chat-input-container", async () => {
}
if (event.key === "Enter") {
event.preventDefault();
const result = (props.onSubmit as (message: string) => Promise<void> | void)?.(
value,
);
const result = (
props.onSubmit as (payload: { message: string }) => Promise<void> | void
)?.({ message: value });
if (result && typeof result.then === "function") {
void result.catch(() => undefined);
}
@@ -160,7 +160,7 @@ export function PassthroughToolbar({
<CommentsPanel
comments={pendingComments}
openFile={openFile}
onSend={() => handleSendMessage("")}
onSend={() => handleSendMessage({ message: "" })}
/>
)}
@@ -1,17 +1,19 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, render } from "@testing-library/react";
import { sessionId as toSessionId, taskId as toTaskId, type TaskSession } from "@/lib/types/http";
import type { ChatSubmitPayload } from "./chat/chat-input-container";
import type { EntityReference } from "@/lib/types/entity-reference";
const mocks = vi.hoisted(() => ({
getWebSocketClient: vi.fn(),
onSend: null as null | ((content: string) => Promise<void>),
onSend: null as null | ((payload: ChatSubmitPayload) => Promise<void>),
}));
vi.mock("@/lib/ws/connection", () => ({
getWebSocketClient: mocks.getWebSocketClient,
}));
vi.mock("./task-chat-panel", () => ({
TaskChatPanel: ({ onSend }: { onSend: (content: string) => Promise<void> }) => {
TaskChatPanel: ({ onSend }: { onSend: (payload: ChatSubmitPayload) => Promise<void> }) => {
mocks.onSend = onSend;
return <div data-testid="preview-chat" />;
},
@@ -38,7 +40,7 @@ describe("PreviewSessionBody send failures", () => {
mocks.getWebSocketClient.mockReturnValue(null);
render(<PreviewSessionBody session={session} taskId="task-1" />);
await expect(mocks.onSend?.("hello")).rejects.toMatchObject({
await expect(mocks.onSend?.({ message: "hello" })).rejects.toMatchObject({
name: "MessageSendError",
code: "connection-unavailable",
message: "Connection unavailable. Reconnect and try again.",
@@ -50,6 +52,41 @@ describe("PreviewSessionBody send failures", () => {
mocks.getWebSocketClient.mockReturnValue({ request: vi.fn().mockRejectedValue(error) });
render(<PreviewSessionBody session={session} taskId="task-1" />);
await expect(mocks.onSend?.("hello")).rejects.toBe(error);
await expect(mocks.onSend?.({ message: "hello" })).rejects.toBe(error);
});
it("forwards attachments and entity references through preview direct send", async () => {
const request = vi.fn().mockResolvedValue(undefined);
mocks.getWebSocketClient.mockReturnValue({ request });
const reference: EntityReference = {
version: 1,
ref: "mention:v1:github:issue:acme%2Frepo:42",
provider: "github",
kind: "issue",
id: "42",
key: "acme/repo#42",
title: "Fix composer references",
url: "https://github.com/acme/repo/issues/42",
scope: "acme/repo",
};
render(<PreviewSessionBody session={session} taskId="task-1" />);
await mocks.onSend?.({
message: "reference",
attachments: [{ type: "image", data: "base64", mime_type: "image/png" }],
entityReferences: [reference],
});
expect(request).toHaveBeenCalledWith(
"message.add",
{
task_id: "task-1",
session_id: "session-1",
content: "reference",
attachments: [{ type: "image", data: "base64", mime_type: "image/png" }],
entity_references: [reference],
},
30000,
);
});
});
@@ -10,9 +10,9 @@ import { useSessionResumption } from "@/hooks/domains/session/use-session-resump
import { useTaskSessions } from "@/hooks/use-task-sessions";
import type { UseEnsureTaskSessionResult } from "@/hooks/domains/session/use-ensure-task-session";
import type { AgentProfileOption } from "@/lib/state/slices";
import { MessageSendError } from "@/lib/chat/message-send-error";
import type { TaskSession } from "@/lib/types/http";
import { getWebSocketClient } from "@/lib/ws/connection";
import { sendMessageRequest } from "@/hooks/use-message-handler";
import type { ChatSubmitPayload } from "./chat/chat-input-container";
import { EnsureSessionErrorEmptyState } from "./ensure-session-error";
import { PassthroughToolbar } from "./passthrough-toolbar";
import { TaskChatPanel } from "./task-chat-panel";
@@ -151,19 +151,17 @@ function SessionAgentLogo({ profile }: { profile: AgentProfileOption | null | un
export function PreviewSessionBody({ session, taskId }: { session: TaskSession; taskId: string }) {
const handleSendMessage = useCallback(
async (content: string) => {
const client = getWebSocketClient();
if (!client) {
throw new MessageSendError(
"connection-unavailable",
"Connection unavailable. Reconnect and try again.",
);
}
await client.request(
"message.add",
{ task_id: taskId, session_id: session.id, content },
10000,
);
async (payload: ChatSubmitPayload) => {
await sendMessageRequest({
taskId,
resolvedSessionId: session.id,
finalMessage: payload.message,
modelToSend: undefined,
planMode: false,
hasReviewComments: !!payload.reviewComments?.length,
attachments: payload.attachments,
entityReferences: payload.entityReferences,
});
},
[taskId, session.id],
);
+6 -2
View File
@@ -3,7 +3,11 @@
import { useCallback, useEffect, useMemo, useRef, useState, memo, type RefObject } from "react";
import { PanelRoot, PanelBody } from "./panel-primitives";
import { useSettingsData } from "@/hooks/domains/settings/use-settings-data";
import { type ChatInputContainerHandle } from "@/components/task/chat/chat-input-container";
import {
type ChatInputContainerHandle,
type ChatSubmitPayload,
type ChatSubmitResult,
} from "@/components/task/chat/chat-input-container";
import { MessageList } from "@/components/task/chat/message-list";
import { useIsTaskArchived } from "./task-archived-context";
import { useChatPanelState } from "./chat/use-chat-panel-state";
@@ -119,7 +123,7 @@ function useSessionAgentIdentity(sessionId: string | null | undefined): {
}
type TaskChatPanelProps = {
onSend?: (message: string) => void;
onSend?: (payload: ChatSubmitPayload) => ChatSubmitResult;
sessionId?: string | null;
taskId?: string | null;
onOpenFile?: (path: string) => void;