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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -246,3 +246,25 @@ Board selection stored per project via `jiraBoard` field on `OrchestrationProjec
- `ComposerPromptSegment` union includes `"jira-context"` type alongside `"terminal-context"`
- `ComposerCommandItem` union includes `"jira-task"` type for menu autocomplete
- `Project` type in `types.ts` includes `jiraBoard: JiraBoardReference | null`

## Reply to Selection (Quoted Context)

MarCode supports replying to specific text selections within assistant messages. Users can select text in an agent response, click "Reply" in a floating toolbar, and the selected text is quoted as structured context in the composer.

### Architecture

- **`apps/web/src/lib/quotedContext.ts`** — `QuotedContext` type, prompt assembly (`appendQuotedContextsToPrompt`), extraction (`extractLeadingQuotedContexts`), dedup, truncation (5000 char limit).
- **`apps/web/src/components/chat/SelectionReplyToolbar.tsx`** — Floating toolbar that appears on text selection within assistant messages. Renders via `createPortal` to `document.body`. Detects code block selections and extracts language.
- **`apps/web/src/components/chat/QuotedContextInlineChip.tsx`** — Visual chip rendered in the composer above the editor showing quoted text preview with remove button. Uses violet color scheme.
- **`apps/web/src/components/chat/UserMessageQuotedContextLabel.tsx`** — Expandable label in the message timeline showing quoted context when a sent message includes it.
- **`apps/web/src/components/chat/MessagesTimeline.tsx`** — `AssistantMessageContentWithReply` wraps assistant message content with a ref for selection tracking and renders `SelectionReplyToolbar`.

### Key Patterns

- `QuotedContext` is stored in `composerDraftStore` as `quotedContexts: QuotedContext[]` on `ComposerThreadDraftState`.
- Quoted context blocks are **prepended** to the prompt (unlike terminal/jira which are appended) as `<quoted_context message_id="..." language="...">` XML blocks.
- `extractLeadingQuotedContexts()` parses leading quoted blocks from stored message text for timeline display.
- Keyboard shortcut: `Cmd/Ctrl+Shift+R` to reply to current selection, `Escape` to dismiss toolbar.
- Quoted contexts are **not** persisted to localStorage (transient draft state) — they are cleared on thread switch or send.
- Selection spanning multiple messages captures only text from the message where selection started.
- Truncation at 5000 chars with `...[truncated]` suffix.
5 changes: 4 additions & 1 deletion apps/web/src/components/ChatView.logic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ export function deriveComposerSendState(options: {
imageCount: number;
terminalContexts: ReadonlyArray<TerminalContextDraft>;
jiraTaskContexts?: ReadonlyArray<JiraTaskDraft>;
quotedContextCount?: number;
}): {
trimmedPrompt: string;
sendableTerminalContexts: TerminalContextDraft[];
Expand All @@ -187,6 +188,7 @@ export function deriveComposerSendState(options: {
const expiredTerminalContextCount =
options.terminalContexts.length - sendableTerminalContexts.length;
const jiraTaskContexts = options.jiraTaskContexts ?? [];
const quotedContextCount = options.quotedContextCount ?? 0;
return {
trimmedPrompt,
sendableTerminalContexts,
Expand All @@ -195,7 +197,8 @@ export function deriveComposerSendState(options: {
trimmedPrompt.length > 0 ||
options.imageCount > 0 ||
sendableTerminalContexts.length > 0 ||
jiraTaskContexts.length > 0,
jiraTaskContexts.length > 0 ||
quotedContextCount > 0,
};
}

Expand Down
55 changes: 53 additions & 2 deletions apps/web/src/components/ChatView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,13 @@ import {
parseJiraUrl,
removeInlineJiraContextPlaceholder,
} from "../lib/jiraContext";
import {
appendQuotedContextsToPrompt,
formatQuotedContextPreview,
formatQuotedContextTooltip,
type QuotedContext,
} from "../lib/quotedContext";
import { QuotedContextInlineChip } from "./chat/QuotedContextInlineChip";
import {
jiraConnectionStatusQueryOptions,
jiraIssueSearchQueryOptions,
Expand Down Expand Up @@ -409,6 +416,7 @@ interface SubmitComposerTurnInput {
images: ComposerImageAttachment[];
terminalContexts: TerminalContextDraft[];
jiraTaskContexts: JiraTaskDraft[];
quotedContexts: QuotedContext[];
expiredTerminalContextCount: number;
clearComposerDraft: boolean;
}
Expand Down Expand Up @@ -684,15 +692,23 @@ export default function ChatView({ threadId }: ChatViewProps) {
const composerImages = composerDraft.images;
const composerTerminalContexts = composerDraft.terminalContexts;
const composerJiraTaskContexts = composerDraft.jiraTaskContexts;
const composerQuotedContexts = composerDraft.quotedContexts;
const composerSendState = useMemo(
() =>
deriveComposerSendState({
prompt,
imageCount: composerImages.length,
terminalContexts: composerTerminalContexts,
jiraTaskContexts: composerJiraTaskContexts,
quotedContextCount: composerQuotedContexts.length,
}),
[composerImages.length, composerTerminalContexts, composerJiraTaskContexts, prompt],
[
composerImages.length,
composerTerminalContexts,
composerJiraTaskContexts,
composerQuotedContexts.length,
prompt,
],
);
const nonPersistedComposerImageIds = composerDraft.nonPersistedImageIds;
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
Expand All @@ -719,9 +735,13 @@ export default function ChatView({ threadId }: ChatViewProps) {
const addComposerDraftJiraTaskContext = useComposerDraftStore(
(store) => store.addJiraTaskContext,
);
const addComposerDraftQuotedContext = useComposerDraftStore((store) => store.addQuotedContext);
const removeComposerDraftJiraTaskContext = useComposerDraftStore(
(store) => store.removeJiraTaskContext,
);
const removeComposerDraftQuotedContext = useComposerDraftStore(
(store) => store.removeQuotedContext,
);
const clearComposerDraftPersistedAttachments = useComposerDraftStore(
(store) => store.clearPersistedAttachments,
);
Expand Down Expand Up @@ -3134,14 +3154,19 @@ export default function ChatView({ threadId }: ChatViewProps) {
const composerImagesSnapshot = [...input.images];
const composerTerminalContextsSnapshot = [...input.terminalContexts];
const composerJiraTaskContextsSnapshot = [...input.jiraTaskContexts];
const composerQuotedContextsSnapshot = [...input.quotedContexts];
const cleanedPromptForSend = replaceInlineJiraPlaceholdersWithLabels(
input.prompt,
composerJiraTaskContextsSnapshot,
);
const messageTextForSend = appendJiraContextsToPrompt(
const withTerminalAndJira = appendJiraContextsToPrompt(
appendTerminalContextsToPrompt(cleanedPromptForSend, composerTerminalContextsSnapshot),
composerJiraTaskContextsSnapshot,
);
const messageTextForSend = appendQuotedContextsToPrompt(
withTerminalAndJira,
composerQuotedContextsSnapshot,
);
const messageIdForSend = newMessageId();
const messageCreatedAt = new Date().toISOString();
const outgoingMessageText = formatOutgoingPrompt({
Expand Down Expand Up @@ -3457,6 +3482,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
imageCount: composerImages.length,
terminalContexts: composerTerminalContexts,
jiraTaskContexts: composerJiraTaskContexts,
quotedContextCount: composerQuotedContexts.length,
});
if (showPlanFollowUpPrompt && activeProposedPlan) {
const followUp = resolvePlanFollowUpSubmission({
Expand Down Expand Up @@ -3509,6 +3535,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
images: [...composerImages],
terminalContexts: [...sendableComposerTerminalContexts],
jiraTaskContexts: [...composerJiraTaskContexts],
quotedContexts: [...composerQuotedContexts],
expiredTerminalContextCount,
clearComposerDraft: true,
});
Expand Down Expand Up @@ -4304,6 +4331,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
[groupId]: !existing[groupId],
}));
}, []);
const onReplyToSelection = useCallback(
(context: QuotedContext) => {
if (!activeThread) return;
addComposerDraftQuotedContext(activeThread.id, context);
focusComposer();
},
[activeThread, addComposerDraftQuotedContext, focusComposer],
);
const onSubagentSelect = useCallback((taskId: string) => {
setSelectedSubagentTaskId(taskId);
}, []);
Expand Down Expand Up @@ -4452,6 +4487,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
images: imagesToSend,
terminalContexts: [],
jiraTaskContexts: [],
quotedContexts: [],
expiredTerminalContextCount: 0,
clearComposerDraft: false,
});
Expand Down Expand Up @@ -4627,6 +4663,7 @@ export default function ChatView({ threadId }: ChatViewProps) {
onRemoveEditingUserMessageImage={onRemoveEditingUserMessageImage}
onCancelEditUserMessage={discardUserMessageEditSession}
onSubmitEditUserMessage={onSubmitEditUserMessage}
onReplyToSelection={onReplyToSelection}
/>
</div>

Expand Down Expand Up @@ -4789,6 +4826,20 @@ export default function ChatView({ threadId }: ChatViewProps) {
))}
</div>
)}
{!isComposerApprovalState &&
pendingUserInputs.length === 0 &&
composerQuotedContexts.length > 0 && (
<div className="mb-2 flex flex-wrap gap-1">
{composerQuotedContexts.map((ctx) => (
<QuotedContextInlineChip
key={ctx.id}
preview={formatQuotedContextPreview(ctx)}
tooltipText={formatQuotedContextTooltip(ctx)}
onRemove={() => removeComposerDraftQuotedContext(threadId, ctx.id)}
/>
))}
</div>
)}
<ComposerPromptEditor
ref={composerEditorRef}
value={
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ async function mountMenu(props?: { modelSelection?: ModelSelection; prompt?: str
persistedAttachments: [],
terminalContexts: [],
jiraTaskContexts: [],
quotedContexts: [],
modelSelectionByProvider: {
[provider]: {
provider,
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/components/chat/MessagesTimeline.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ describe("MessagesTimeline", () => {
onRemoveEditingUserMessageImage={() => {}}
onCancelEditUserMessage={() => {}}
onSubmitEditUserMessage={() => {}}
onReplyToSelection={() => {}}
/>,
);

Expand Down Expand Up @@ -164,6 +165,7 @@ describe("MessagesTimeline", () => {
onRemoveEditingUserMessageImage={() => {}}
onCancelEditUserMessage={() => {}}
onSubmitEditUserMessage={() => {}}
onReplyToSelection={() => {}}
/>,
);

Expand Down
54 changes: 48 additions & 6 deletions apps/web/src/components/chat/MessagesTimeline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@
import { cn } from "~/lib/utils";
import { extractTrailingJiraContexts, type ParsedJiraContextEntry } from "~/lib/jiraContext";
import { JiraTaskInlineChip } from "./JiraTaskInlineChip";
import { SelectionReplyToolbar } from "./SelectionReplyToolbar";
import {
extractLeadingQuotedContexts,
type ParsedQuotedContextEntry,

Check warning on line 75 in apps/web/src/components/chat/MessagesTimeline.tsx

View workflow job for this annotation

GitHub Actions / Format, Lint, Typecheck, Test, Browser Test, Build

eslint(no-unused-vars)

Type 'ParsedQuotedContextEntry' is imported but never used.
type QuotedContext,
} from "~/lib/quotedContext";
import { UserMessageQuotedContextLabel } from "./UserMessageQuotedContextLabel";
import { type TimestampFormat } from "@marcode/contracts/settings";
import { formatTimestamp } from "../../timestampFormat";
import {
Expand Down Expand Up @@ -115,6 +122,7 @@
onRemoveEditingUserMessageImage: (imageId: string) => void;
onCancelEditUserMessage: () => void;
onSubmitEditUserMessage: () => void | Promise<void>;
onReplyToSelection: (context: QuotedContext) => void;
onVirtualizerSnapshot?: (snapshot: {
totalSize: number;
measurements: ReadonlyArray<{
Expand Down Expand Up @@ -163,6 +171,7 @@
onRemoveEditingUserMessageImage,
onCancelEditUserMessage,
onSubmitEditUserMessage,
onReplyToSelection,
onVirtualizerSnapshot,
}: MessagesTimelineProps) {
const timelineRootRef = useRef<HTMLDivElement | null>(null);
Expand Down Expand Up @@ -463,11 +472,17 @@
</div>
)}
<div className="group/msg min-w-0 px-1 py-0.5">
<ChatMarkdown
text={messageText}
cwd={markdownCwd}
isStreaming={Boolean(row.message.streaming)}
/>
<AssistantMessageContentWithReply
messageId={row.message.id}
turnId={row.message.turnId ?? null}
onReplyToSelection={onReplyToSelection}
>
<ChatMarkdown
text={messageText}
cwd={markdownCwd}
isStreaming={Boolean(row.message.streaming)}
/>
</AssistantMessageContentWithReply>
{(() => {
const turnSummary = turnDiffSummaryByAssistantMessageId.get(row.message.id);
if (!turnSummary) return null;
Expand Down Expand Up @@ -867,7 +882,10 @@
}

const userImages = props.message.attachments ?? [];
const displayedUserMessage = deriveDisplayedUserMessageState(props.message.text);
const quotedExtracted = extractLeadingQuotedContexts(props.message.text);
const afterQuotedText =
quotedExtracted.contextCount > 0 ? quotedExtracted.promptText : props.message.text;
const displayedUserMessage = deriveDisplayedUserMessageState(afterQuotedText);
const terminalContexts = displayedUserMessage.contexts;
const jiraExtracted = extractTrailingJiraContexts(displayedUserMessage.visibleText);
const visibleText =
Expand Down Expand Up @@ -917,6 +935,9 @@
))}
</div>
)}
{quotedExtracted.contexts.length > 0 && (
<UserMessageQuotedContextLabel contexts={quotedExtracted.contexts} />
)}
{(visibleText.trim().length > 0 || terminalContexts.length > 0) && (
<UserMessageBody
text={visibleText}
Expand Down Expand Up @@ -1066,6 +1087,27 @@
);
});

const AssistantMessageContentWithReply = memo(function AssistantMessageContentWithReply(props: {
messageId: MessageId;
turnId: TurnId | null;
children: ReactNode;
onReplyToSelection: (context: QuotedContext) => void;
}) {
const containerRef = useRef<HTMLDivElement | null>(null);

return (
<div ref={containerRef} className="relative">
{props.children}
<SelectionReplyToolbar
messageId={props.messageId}
turnId={props.turnId}
containerRef={containerRef}
onReply={props.onReplyToSelection}
/>
</div>
);
});

function workToneIcon(tone: TimelineWorkEntry["tone"]): {
icon: LucideIcon;
className: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,7 @@ function createBaseTimelineProps(input: {
onRemoveEditingUserMessageImage: () => {},
onCancelEditUserMessage: () => {},
onSubmitEditUserMessage: () => {},
onReplyToSelection: () => {},
...(input.onVirtualizerSnapshot ? { onVirtualizerSnapshot: input.onVirtualizerSnapshot } : {}),
};
}
Expand Down
56 changes: 56 additions & 0 deletions apps/web/src/components/chat/QuotedContextInlineChip.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { QuoteIcon, XIcon } from "lucide-react";

import { cn } from "~/lib/utils";
import {
COMPOSER_INLINE_CHIP_CLASS_NAME,
COMPOSER_INLINE_CHIP_ICON_CLASS_NAME,
COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME,
COMPOSER_INLINE_CHIP_DISMISS_BUTTON_CLASS_NAME,
} from "../composerInlineChip";
import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";

interface QuotedContextInlineChipProps {
preview: string;
tooltipText: string;
onRemove?: () => void;
}

export function QuotedContextInlineChip(props: QuotedContextInlineChipProps) {
const { preview, tooltipText, onRemove } = props;

return (
<Tooltip>
<TooltipTrigger
render={
<span
className={cn(
COMPOSER_INLINE_CHIP_CLASS_NAME,
"border-violet-500/30 bg-violet-500/12 text-violet-300 dark:border-violet-400/25 dark:bg-violet-400/10 dark:text-violet-300",
)}
>
<QuoteIcon className={cn(COMPOSER_INLINE_CHIP_ICON_CLASS_NAME, "size-3.5")} />
<span className={cn(COMPOSER_INLINE_CHIP_LABEL_CLASS_NAME, "max-w-[200px]")}>
{preview}
</span>
{onRemove && (
<button
type="button"
className={COMPOSER_INLINE_CHIP_DISMISS_BUTTON_CLASS_NAME}
onClick={(e) => {
e.stopPropagation();
onRemove();
}}
aria-label="Remove quoted context"
>
<XIcon className="size-2.5" />
</button>
)}
</span>
}
/>
<TooltipPopup side="top" className="max-w-80 whitespace-pre-wrap leading-tight">
{tooltipText}
</TooltipPopup>
</Tooltip>
);
}
Loading
Loading