Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(issues): order thread replies by send time, not by trigger (MUL-7628) (#8746)

Bohan Jiang18d9c41b1a51
diff --git a/packages/views/issues/components/comment-card.tsx b/packages/views/issues/components/comment-card.tsx
index 0559db6c59..757c262ea1 100644
--- a/packages/views/issues/components/comment-card.tsx
+++ b/packages/views/issues/components/comment-card.tsx
@@ -2,7 +2,7 @@
import { Fragment, memo, useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { useQuery } from "@tanstack/react-query";
-import { CheckCircle2, ChevronRight, ListChevronsDownUp, Copy, Link2, Loader2, MessageSquarePlus, MoreHorizontal, Pencil, RotateCcw, Trash2 } from "lucide-react";
+import { CheckCircle2, ChevronRight, CornerUpLeft, ListChevronsDownUp, Copy, Link2, Loader2, MessageSquarePlus, MoreHorizontal, Pencil, RotateCcw, Trash2 } from "lucide-react";
import { toast } from "sonner";
import { Card } from "@multica/ui/components/ui/card";
import { Button, buttonVariants } from "@multica/ui/components/ui/button";
@@ -51,7 +51,8 @@ import { CommentsFoldBar } from "./resolved-thread-bar";
import { deriveThreadResolution } from "./thread-utils";
import { RevisionConflictCompare } from "./revision-conflict-compare";
import { InlineCommentRun, PlacedInlineCommentRun, useInlineCommentRunState, type InlineCommentRunState } from "./inline-comment-run";
-import { EMPTY_COMMENT_RUNS, type CommentRun } from "./comment-runs";
+import { EMPTY_COMMENT_RUNS, orderThreadWithRuns, type CommentRun, type ThreadRunSlot } from "./comment-runs";
+import { descriptionPreview } from "./description-preview";
import { useCommentAnnotations } from "./use-comment-annotations";
import { useRunCommentMotion } from "./use-run-comment-motion";
@@ -133,6 +134,8 @@ interface CommentCardProps {
onResolveToggle?: (commentId: string, resolved: boolean) => void;
/** Copy a deep link (`#comment-…`) to a single comment in this thread. */
onCopyLink?: (commentId: string) => void;
+ /** Scroll to and flash a comment in this thread. */
+ onJumpToComment?: (commentId: string) => void;
/**
* When non-null, the thread root is currently rendered as a resolved-but-
* expanded card. Pass a "Collapse" affordance into the header so the user
@@ -660,6 +663,7 @@ function ActiveSupplementReceipt({ issueId, entry }: { issueId: string; entry: T
function CommentRow({
runHeader,
runMetadata,
+ replyTo,
issueId,
entry,
currentUserId,
@@ -676,6 +680,7 @@ function CommentRow({
}: {
runHeader?: ReactNode;
runMetadata?: ReactNode;
+ replyTo?: ReactNode;
issueId: string;
entry: TimelineEntry;
currentUserId?: string;
@@ -845,6 +850,7 @@ function CommentRow({
/>
</div>
</StickyHeaderShell>
+ {replyTo && <div className="pl-12 pr-4 max-md:pl-3 max-md:pr-3 pb-1.5">{replyTo}</div>}
{edit.editing ? (
<div
@@ -958,12 +964,31 @@ function CommentRow({
);
}
+/** Names the input a run answers once other rows separate the two (MUL-7628). */
+function ReplyToQuote({ entry, onJump }: { entry: TimelineEntry; onJump?: (commentId: string) => void }) {
+ const { t } = useT("issues");
+ const { getActorName } = useActorName();
+ const label = t(($) => $.comment.replying_to, {
+ name: entry.actor_name || getActorName(entry.actor_type, entry.actor_id),
+ preview: descriptionPreview(entry.content ?? ""),
+ });
+ return (
+ <button type="button" disabled={!onJump} onClick={() => onJump?.(entry.id)} title={label}
+ className="flex max-w-full min-w-0 items-center gap-1.5 rounded-xs text-left text-caption text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:hover:text-muted-foreground">
+ <CornerUpLeft aria-hidden className="size-3 shrink-0" />
+ <span className="min-w-0 truncate">{label}</span>
+ </button>
+ );
+}
+
/** A run without a persisted reply still belongs to the agent, never its trigger author. */
-export function AgentRunComment({ run, standalone = false, commentProps, entering = false }: {
+export function AgentRunComment({ run, standalone = false, commentProps, entering = false, replyTo }: {
run: CommentRun;
standalone?: boolean;
entering?: boolean;
commentProps?: CommentCardProps;
+ /** The input this run answers, shown when the thread no longer places the two together. */
+ replyTo?: ReactNode;
}) {
const viewState = useInlineCommentRunState();
const replyEntry = commentProps?.entry;
@@ -985,10 +1010,11 @@ export function AgentRunComment({ run, standalone = false, commentProps, enterin
<CommentRow {...commentProps}
isHighlighted={commentProps.highlightedCommentId === reply?.id}
isResolution={!!reply?.resolved_at}
+ replyTo={replyTo}
runHeader={<PlacedInlineCommentRun run={run} viewState={viewState} presentation="header" />}
runMetadata={<PlacedInlineCommentRun run={run} viewState={viewState} />} />
) : <div className="px-4 max-md:px-3">
- <InlineCommentRun run={run} viewState={viewState} showIdentity />
+ <InlineCommentRun run={run} viewState={viewState} showIdentity replyTo={replyTo} />
</div>}
</div>
);
@@ -1022,6 +1048,7 @@ function CommentCardImpl({
onCreateSubIssue,
onResolveToggle,
onCopyLink,
+ onJumpToComment,
onCollapseResolved,
expandedResolvedIds,
onResolvedExpandChange,
@@ -1065,35 +1092,25 @@ function CommentCardImpl({
// over. Every tombstone has at least one live descendant (the server prunes
// one that loses its last reply), so no content hides behind this.
const visibleReplies = allNestedReplies.filter((reply) => !isDeletedComment(reply));
- // A run anchored here renders in one slot after its input, ending with its
- // reply (the run's latest comment). The rest of what the run posted in this
- // thread joins that slot in posting order; left in the chronological list,
- // it would render after the reply it preceded (MUL-7548).
- const slottedRuns = runs.filter((run) => run.hasReply && run.anchorCommentId && run.commentId !== entry.id);
- const runOutputs = new Map(slottedRuns.map((run) => [run.task.id,
- allNestedReplies.filter((reply) => reply.actor_type === "agent" && reply.source_task_id === run.task.id)]));
- const slottedReplyIds = new Set(slottedRuns.flatMap((run) =>
- [run.commentId, ...(runOutputs.get(run.task.id) ?? []).map((reply) => reply.id)]));
const renderRuns = (commentId: string, presentation: "inline" | "header" = "inline") => runs.filter((run) => run.commentId === commentId && run.hasReply
&& (!run.anchorCommentId || run.anchorCommentId === commentId || replyFolded))
.map((run) => <PlacedInlineCommentRun key={run.task.id} run={run} presentation={presentation} viewState={run.commentId === entry.id ? runViewState : undefined} />);
- const renderAnchoredRuns = (commentId: string) => runs.filter((run) => run.anchorCommentId === commentId
- && !(replyFolded && run.hasReply))
- .map((run) => {
- const reply = run.hasReply ? allNestedReplies.find((entry) => entry.id === run.commentId) : undefined;
- return <Fragment key={run.task.id}>
- {runOutputs.get(run.task.id)?.filter((output) => output.id !== run.commentId).map(renderReply)}
- <AgentRunComment run={run} entering={enteringRunIds?.has(run.task.id)} commentProps={reply ? {
- issueId, entry: reply, replies: [], currentUserId, canModerate, onReply, onEdit, onDelete,
- onToggleReaction, onCreateSubIssue, onResolveToggle, onCopyLink, highlightedCommentId, enteringRunIds,
- } : undefined} />{reply && reply.id !== commentId && renderAnchoredRuns(reply.id)}</Fragment>;
- });
+ // A run slot renders the run's latest comment, or its activity until it
+ // posts one.
+ const renderThreadRow = (row: TimelineEntry | ThreadRunSlot) => "run" in row ? (
+ <AgentRunComment key={row.run.task.id} run={row.run} entering={enteringRunIds?.has(row.run.task.id)}
+ replyTo={row.replyTo && <ReplyToQuote entry={row.replyTo} onJump={onJumpToComment} />}
+ commentProps={row.reply ? {
+ issueId, entry: row.reply, replies: [], currentUserId, canModerate, onReply, onEdit, onDelete,
+ onToggleReaction, onCreateSubIssue, onResolveToggle, onCopyLink, highlightedCommentId, enteringRunIds,
+ } : undefined} />
+ ) : renderReply(row);
const renderReply = (reply: TimelineEntry) => (
<Fragment key={reply.id}>
- {/* A tombstone keeps its place in the walk — runs anchored to
- it still render — but contributes no row of its own. */}
+ {/* A tombstone keeps its place in the thread but contributes no row
+ of its own. */}
{!isDeletedComment(reply) && (
<div
id={`comment-${reply.id}`}
@@ -1121,7 +1138,6 @@ function CommentCardImpl({
/>
</div>
)}
- {renderAnchoredRuns(reply.id)}
</Fragment>
);
@@ -1147,6 +1163,12 @@ function CommentCardImpl({
const resolutionReply = replyResolutionId
? allNestedReplies.find((r) => r.id === replyResolutionId) ?? null
: null;
+ // Replies and run slots in the order they happened (MUL-7628). Folded, the
+ // resolution stays visible along with any run that has not replied yet.
+ const threadRows = replyFolded
+ ? orderThreadWithRuns(entry, resolutionReply ? [resolutionReply] : [], runs.filter((run) => !run.hasReply
+ && (run.anchorCommentId === entry.id || run.anchorCommentId === replyResolutionId)))
+ : orderThreadWithRuns(entry, allNestedReplies, runs);
// Pin the root comment's header to the timeline's scroll parent while the
// thread is open, so a LONG root comment keeps its author + actions visible
@@ -1466,7 +1488,6 @@ function CommentCardImpl({
to mirror the body Panel's collapse visibility. */}
{open && (
<>
- {renderAnchoredRuns(entry.id)}
{replyFolded ? (
<>
{/* reply-mode folded: other replies behind a bar, resolution pinned below */}
@@ -1478,36 +1499,7 @@ function CommentCardImpl({
/>
</div>
)}
- {resolutionReply && (
- <>
- <div
- id={`comment-${resolutionReply.id}`}
- className={cn(
- "border-t border-border/50 transition-colors duration-700",
- highlightedCommentId === resolutionReply.id && highlightedCommentBackgroundClass,
- )}
- >
- <CommentRow
- issueId={issueId}
- entry={resolutionReply}
- runHeader={renderRuns(resolutionReply.id, "header")}
- runMetadata={renderRuns(resolutionReply.id)}
- currentUserId={currentUserId}
- canModerate={canModerate}
- isResolution
- isHighlighted={highlightedCommentId === resolutionReply.id}
- hasReplies={repliedToIds.has(resolutionReply.id)}
- onEdit={onEdit}
- onDelete={onDelete}
- onToggleReaction={onToggleReaction}
- onCreateSubIssue={onCreateSubIssue}
- onResolveToggle={onResolveToggle}
- onCopyLink={onCopyLink}
- />
- </div>
- {renderAnchoredRuns(resolutionReply.id)}
- </>
- )}
+ {threadRows.map(renderThreadRow)}
</>
) : (
<>
@@ -1524,7 +1516,7 @@ function CommentCardImpl({
</button>
)}
{/* Replies — chronological; the resolution keeps its place with a badge */}
- {allNestedReplies.filter((reply) => !slottedReplyIds.has(reply.id)).map(renderReply)}
+ {threadRows.map(renderThreadRow)}
{/* Reply input */}
<div className="border-t border-border/50 px-4 max-md:px-3 py-2.5">
diff --git a/packages/views/issues/components/comment-runs.test.ts b/packages/views/issues/components/comment-runs.test.ts
index 2806a43671..9d948a5ae1 100644
--- a/packages/views/issues/components/comment-runs.test.ts
+++ b/packages/views/issues/components/comment-runs.test.ts
@@ -1,7 +1,8 @@
// @vitest-environment node
import { describe, expect, it } from "vitest";
import type { AgentTask, TimelineEntry } from "@multica/core/types";
-import { commentRunOutput, buildCommentRunView, orderTimelineWithRuns, type CommentRun } from "./comment-runs";
+import { commentRunOutput, buildCommentRunView, orderThreadWithRuns, orderTimelineWithRuns, type CommentRun } from "./comment-runs";
+import { collectThreadReplies } from "./thread-utils";
const groupCommentRuns = (...args: Parameters<typeof buildCommentRunView>) => buildCommentRunView(...args).runs;
@@ -400,3 +401,107 @@ describe("orderTimelineWithRuns", () => {
.toEqual(["zzz-task", "ccc-comment"]);
});
});
+
+describe("orderThreadWithRuns", () => {
+ const at = (time: string) => `2026-09-23T${time}Z`;
+ // Build the thread the way IssueDetail does, then label each row: a reply
+ // by id, a run slot by what it renders (its latest comment or its
+ // activity), followed by the input it quotes.
+ const thread = (tasks: AgentTask[], timeline: TimelineEntry[]) => {
+ const view = buildCommentRunView(tasks, timeline);
+ const byParent = new Map<string, TimelineEntry[]>();
+ for (const entry of view.timeline) {
+ if (entry.parent_id) byParent.set(entry.parent_id, [...(byParent.get(entry.parent_id) ?? []), entry]);
+ }
+ const root = view.timeline.find((entry) => !entry.parent_id)!;
+ return orderThreadWithRuns(root, collectThreadReplies(root.id, byParent), view.runs.get(root.id) ?? [])
+ .map((row) => !("run" in row) ? row.id
+ : (row.reply?.id ?? `run:${row.run.task.id}`) + (row.replyTo ? ` ↩ ${row.replyTo.id}` : ""));
+ };
+ const answer = (id: string, run: AgentTask, created_at: string, parent_id?: string) =>
+ comment(id, { actor_type: "agent", source_task_id: run.id, created_at, parent_id });
+ const asked = (id: string, trigger: TimelineEntry, overrides: Partial<AgentTask> = {}) =>
+ task(id, { status: "completed", created_at: trigger.created_at, trigger_comment_id: trigger.id,
+ delivered_comment_ids: [trigger.id], ...overrides });
+
+ // The MUL-7349 thread: Elon was asked first but replied last, and his
+ // review used to render right under the request, above everything after it.
+ it("orders agent replies by when they were sent and quotes an input that is not directly above", () => {
+ const root = comment("design", { created_at: at("08:00:00") });
+ const askElon = comment("ask-elon", { parent_id: root.id, created_at: at("08:15:32") });
+ const askSteve = comment("ask-steve", { parent_id: root.id, created_at: at("08:15:41") });
+ const elon = asked("elon", askElon);
+ const steve = asked("steve", askSteve);
+ const timeline = [root, askElon, askSteve, answer("fixed", steve, at("08:23:41"), root.id),
+ answer("review", elon, at("08:32:29"), root.id), comment("follow-up", { parent_id: root.id, created_at: at("08:35:05") })];
+ expect(thread([elon, steve], timeline))
+ .toEqual(["ask-elon", "ask-steve", "fixed", "review ↩ ask-elon", "follow-up"]);
+ });
+
+ it("reads as before when one agent answers the comment directly above", () => {
+ const root = comment("root", { created_at: at("10:00:00") });
+ const ask = comment("ask", { parent_id: root.id, created_at: at("10:01:00") });
+ const run = asked("run", ask);
+ expect(thread([run], [root, ask, answer("answer", run, at("10:05:00"))])).toEqual(["ask", "answer"]);
+ const rootRun = asked("root-run", root);
+ expect(thread([rootRun], [root, answer("root-answer", rootRun, at("10:05:00"))])).toEqual(["root-answer"]);
+ });
+
+ it("keeps a working run after its input until it replies", () => {
+ const root = comment("root", { created_at: at("10:00:00") });
+ const later = comment("later", { parent_id: root.id, created_at: at("10:02:00") });
+ const run = asked("run", root, { status: "running", started_at: at("10:00:05") });
+ expect(thread([run], [root, later])).toEqual(["run:run", "later"]);
+ expect(thread([run], [root, later, answer("answer", run, at("10:04:00"))])).toEqual(["later", "answer ↩ root"]);
+ });
+
+ it("keeps parallel working runs with their inputs until each replies", () => {
+ const root = comment("root", { created_at: at("10:00:00") });
+ const askA = comment("ask-a", { parent_id: root.id, created_at: at("10:01:00") });
+ const askB = comment("ask-b", { parent_id: root.id, created_at: at("10:02:00") });
+ const a = asked("a", askA, { status: "running" });
+ const b = asked("b", askB, { status: "running" });
+ expect(thread([a, b], [root, askA, askB])).toEqual(["ask-a", "run:a", "ask-b", "run:b"]);
+ const answerB = answer("answer-b", b, at("10:05:00"));
+ expect(thread([a, b], [root, askA, askB, answerB])).toEqual(["ask-a", "run:a", "ask-b", "answer-b"]);
+ expect(thread([a, b], [root, askA, askB, answerB, answer("answer-a", a, at("10:06:00"))]))
+ .toEqual(["ask-a", "ask-b", "answer-b", "answer-a ↩ ask-a"]);
+ });
+
+ it("keeps working runs on one input in enqueue order, after that input's other runs", () => {
+ const root = comment("root", { created_at: at("10:00:00") });
+ const ask = comment("ask", { parent_id: root.id, created_at: at("10:01:00") });
+ const first = asked("first", ask, { status: "running" });
+ const second = asked("second", ask, { status: "queued", delivered_comment_ids: [] });
+ expect(thread([first, second], [root, ask, comment("later", { parent_id: root.id, created_at: at("10:02:00") })]))
+ .toEqual(["ask", "run:first", "run:second ↩ ask", "later"]);
+ });
+
+ // MUL-7548 kept one run's comments together at its latest one; each now
+ // reads at its own time, so a comment written in between stays between.
+ it("places each comment a run posts at its own time", () => {
+ const root = comment("root", { created_at: at("10:00:00") });
+ const run = asked("run", root);
+ const progress = answer("progress", run, at("10:01:00"));
+ const final = answer("final", run, at("10:03:00"));
+ expect(thread([run], [root, progress, final])).toEqual(["progress", "final"]);
+ const aside = comment("aside", { parent_id: root.id, created_at: at("10:02:00") });
+ expect(thread([run], [root, progress, aside, final])).toEqual(["progress", "aside", "final ↩ root"]);
+ });
+
+ it("settles a run that ended without replying at the time it ended", () => {
+ const root = comment("root", { created_at: at("10:00:00") });
+ const failed = asked("failed", root, { status: "failed", started_at: at("10:00:10"), completed_at: at("10:05:00") });
+ const timeline = [root, comment("before", { parent_id: root.id, created_at: at("10:01:00") }),
+ comment("after", { parent_id: root.id, created_at: at("10:10:00") })];
+ expect(thread([failed], timeline)).toEqual(["before", "run:failed ↩ root", "after"]);
+ });
+
+ it("does not quote a deleted input", () => {
+ const root = comment("root", { created_at: at("10:00:00") });
+ const ask = comment("ask", { parent_id: root.id, created_at: at("10:01:00"), content: "", deleted_at: at("10:03:00") });
+ const run = asked("run", ask);
+ const timeline = [root, ask, comment("kept", { parent_id: ask.id, created_at: at("10:02:00") }), answer("answer", run, at("10:05:00"))];
+ expect(thread([run], timeline)).toEqual(["ask", "kept", "answer"]);
+ });
+});
diff --git a/packages/views/issues/components/comment-runs.ts b/packages/views/issues/components/comment-runs.ts
index 8dc0d7e0a8..b866b7d9e1 100644
--- a/packages/views/issues/components/comment-runs.ts
+++ b/packages/views/issues/components/comment-runs.ts
@@ -1,4 +1,5 @@
import type { AgentTask, TimelineEntry } from "@multica/core/types";
+import { isDeletedComment } from "@multica/core/issues/comment-deletion";
export interface CommentRun {
task: AgentTask;
@@ -33,7 +34,7 @@ function isObsoleteCommentRun(task: AgentTask): boolean {
&& !task.dispatched_at && !task.started_at && !task.delivered_comment_ids?.length;
}
-/** Place each run after its latest covered input; associate replies by task identity. */
+/** Anchor each run on its latest covered input; associate replies by task identity. */
export function buildCommentRunView(
tasks: readonly AgentTask[],
timeline: readonly TimelineEntry[],
@@ -111,12 +112,13 @@ export function buildCommentRunView(
anchorId = source.trigger_comment_id && ids.includes(source.trigger_comment_id)
? source.trigger_comment_id
: latestCandidateId() ?? ids.find((id) => !!id);
- // A same-thread batch belongs after its latest covered input, so the
- // timeline reads "these comments → this run". Before claim, a newly
- // coalesced trigger moves the queued block down. After claim, `ids` comes
- // from delivered_comment_ids and freezes the running block at the actual
- // delivery boundary. Wait for missing comments instead of guessing their
- // thread; historical batches spanning several threads retain their trigger.
+ // A same-thread batch answers its latest covered input: the comment its
+ // reply hangs under and quotes when the two are apart (MUL-7628). Before
+ // claim, a newly coalesced trigger moves the anchor down. After claim,
+ // `ids` comes from delivered_comment_ids and freezes the anchor at the
+ // actual delivery boundary. Wait for missing comments instead of guessing
+ // their thread; historical batches spanning several threads retain their
+ // trigger.
const root = candidates[0] && threadRoot(candidates[0].id);
if (root && candidates.length === ids.filter(Boolean).length
&& candidates.every((entry) => threadRoot(entry.id) === root)) {
@@ -194,11 +196,14 @@ export function buildCommentRunView(
}
/**
- * Where a standalone run block sits in the timeline.
+ * Where a run block sits among comments — in the top-level timeline, or among
+ * one thread's replies.
*
* Once a run publishes a reply, the reply's own time owns the slot (MUL-7211).
* This keeps the card's timestamp in chronological order even after a long
- * queue wait or execution. A run that ended without a reply sorts when it ended.
+ * queue wait or execution, and in a thread it lets two agents asked in a row
+ * read in the order they replied (MUL-7628). A run that ended without a reply
+ * sorts when it ended.
*
* Until then, an active run keeps its enqueue-time slot (MUL-7632). Parking it
* at the live end would insert every later comment above an already visible
@@ -208,7 +213,7 @@ function publishedReply(run: CommentRun, entryById: ReadonlyMap<string, Timeline
return run.hasReply && run.commentId ? entryById.get(run.commentId) : undefined;
}
-function standaloneRunSortTime(run: CommentRun, entryById: ReadonlyMap<string, TimelineEntry>): number {
+function runSortTime(run: CommentRun, entryById: ReadonlyMap<string, TimelineEntry>): number {
const reply = publishedReply(run, entryById);
if (reply) return Date.parse(reply.created_at);
if (isActiveCommentRun(run.task)) return Date.parse(run.task.created_at);
@@ -216,19 +221,20 @@ function standaloneRunSortTime(run: CommentRun, entryById: ReadonlyMap<string, T
}
/**
- * Merge standalone runs into the top-level timeline in reading order.
+ * Merge runs into a list of comments in reading order: standalone runs into
+ * the top-level timeline, or a thread's runs into its replies.
*
- * A run that published a reply REPLACES that comment's own top-level slot —
- * the block renders the comment card, so leaving both would double it.
+ * A run that published a reply REPLACES that comment's own slot — the block
+ * renders the comment, so leaving both would double it.
*/
export function orderTimelineWithRuns(
- topLevel: readonly TimelineEntry[],
- standaloneRuns: readonly CommentRun[],
+ entries: readonly TimelineEntry[],
+ runs: readonly CommentRun[],
entryById: ReadonlyMap<string, TimelineEntry>,
): (TimelineEntry | CommentRun)[] {
- const slotted = new Set(standaloneRuns.filter((run) => run.hasReply).map((run) => run.commentId));
+ const slotted = new Set(runs.filter((run) => run.hasReply).map((run) => run.commentId));
const sortTime = (item: TimelineEntry | CommentRun): number =>
- "task" in item ? standaloneRunSortTime(item, entryById) : Date.parse(item.created_at);
+ "task" in item ? runSortTime(item, entryById) : Date.parse(item.created_at);
// Ties are ordinary, not exotic: the API serializes timestamps to whole
// seconds (util.TimestampToString), so a reply and the comment next to it
// routinely share one. Break them on the row that OWNS the slot — the reply
@@ -237,10 +243,68 @@ export function orderTimelineWithRuns(
// invariant sortTimelineEntriesAsc holds for the flat cache.
const slotRow = (item: TimelineEntry | CommentRun): { created_at: string; id: string } =>
"task" in item ? publishedReply(item, entryById) ?? item.task : item;
- return [...topLevel.filter((entry) => !slotted.has(entry.id)), ...standaloneRuns].sort((a, b) => {
+ return [...entries.filter((entry) => !slotted.has(entry.id)), ...runs].sort((a, b) => {
const left = sortTime(a), right = sortTime(b);
if (left !== right) return left < right ? -1 : 1;
const leftRow = slotRow(a), rightRow = slotRow(b);
return leftRow.created_at.localeCompare(rightRow.created_at) || leftRow.id.localeCompare(rightRow.id);
});
}
+
+/** A run's slot in a thread. */
+export interface ThreadRunSlot {
+ run: CommentRun;
+ /** The run's latest comment, which the slot renders once it exists. */
+ reply?: TimelineEntry;
+ /** The input the run answers, when other rows separate the two. */
+ replyTo?: TimelineEntry;
+}
+
+/**
+ * A thread's replies and runs in reading order. Every posted comment sits at
+ * its own time, a run's included (MUL-7211): two agents asked in a row read
+ * in the order they answered, and a run's progress reads before a comment
+ * written after it (MUL-7628). A run's slot is its latest comment. A run
+ * still working with nothing posted stays right after the input it answers
+ * — the latest one it covers — the way an active standalone run keeps its
+ * enqueue slot (MUL-7632). A run whose reply is the root heads the thread
+ * instead.
+ */
+export function orderThreadWithRuns(
+ root: TimelineEntry,
+ replies: readonly TimelineEntry[],
+ runs: readonly CommentRun[],
+): (TimelineEntry | ThreadRunSlot)[] {
+ const entryById = new Map([root, ...replies].map((entry) => [entry.id, entry]));
+ const threadRuns = runs.filter((run) => run.anchorCommentId && !(run.hasReply && run.commentId === root.id));
+ const working = new Set(threadRuns.filter((run) => !run.hasReply && isActiveCommentRun(run.task)));
+ const rows = orderTimelineWithRuns(replies, threadRuns.filter((run) => !working.has(run)), entryById);
+ // `runs` arrive in enqueue order: each working run goes after the row that
+ // shows its input (none for the root) and after earlier runs on that input.
+ for (const run of working) {
+ let index = rows.findIndex((item) => ("task" in item ? publishedReply(item, entryById)?.id : item.id) === run.anchorCommentId) + 1;
+ while (working.has(rows[index] as CommentRun) && (rows[index] as CommentRun).anchorCommentId === run.anchorCommentId) index += 1;
+ rows.splice(index, 0, run);
+ }
+ // The comment directly above a run, past the run's own earlier comments. A
+ // tombstone renders nothing; a run without a visible reply renders its
+ // activity block, which no input can be.
+ const commentAbove = (index: number, run: CommentRun): string | undefined => {
+ for (const item of rows.slice(0, index).reverse()) {
+ if ("task" in item) {
+ const reply = publishedReply(item, entryById);
+ return reply && !isDeletedComment(reply) ? reply.id : undefined;
+ }
+ if (!isDeletedComment(item) && item.source_task_id !== run.task.id) return item.id;
+ }
+ return root.id;
+ };
+ return rows.map((item, index) => {
+ if (!("task" in item)) return item;
+ const reply = publishedReply(item, entryById);
+ const anchor = item.anchorCommentId ? entryById.get(item.anchorCommentId) : undefined;
+ const replyTo = anchor && anchor.id !== reply?.id && !isDeletedComment(anchor)
+ && anchor.id !== commentAbove(index, item) ? anchor : undefined;
+ return { run: item, reply, replyTo };
+ });
+}
diff --git a/packages/views/issues/components/inline-comment-run.tsx b/packages/views/issues/components/inline-comment-run.tsx
index 702596ba03..bd01ad126e 100644
--- a/packages/views/issues/components/inline-comment-run.tsx
+++ b/packages/views/issues/components/inline-comment-run.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useEffect, useId, useMemo, useState } from "react";
+import { useEffect, useId, useMemo, useState, type ReactNode } from "react";
import { AlertCircle, Brain, ChevronRight, CirclePause, Clock3, ExternalLink, Loader2, MessageSquare, MessageSquarePlus, RotateCcw, ScrollText, Send, Square, Terminal } from "lucide-react";
import { toast } from "sonner";
import { useWorkspaceId } from "@multica/core/hooks";
@@ -64,12 +64,14 @@ export function PlacedInlineCommentRun({ presentation = "inline", ...props }: Pa
return <InlineCommentRun {...props} presentation={presentation} />;
}
-export function InlineCommentRun({ run, className, viewState, showIdentity = false, presentation = "inline" }: {
+export function InlineCommentRun({ run, className, viewState, showIdentity = false, presentation = "inline", replyTo }: {
run: CommentRun;
className?: string;
viewState?: InlineCommentRunState;
showIdentity?: boolean;
presentation?: "inline" | "header";
+ /** The input this run answers, under its identity like a reply's. */
+ replyTo?: ReactNode;
}) {
const { task, hasReply } = run;
const { t } = useT("issues");
@@ -247,6 +249,7 @@ export function InlineCommentRun({ run, className, viewState, showIdentity = fal
</Button>}
</div>
<div className={cn(showIdentity && "pl-8")}>
+ {replyTo}
{supplementDraft?.open && <div className="mt-2 space-y-2 rounded-md border bg-muted/20 p-2"
onKeyDown={(event) => {
if (event.key === "Escape") {
diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsx
index 160c7509a3..0ce6bdcc1b 100644
--- a/packages/views/issues/components/issue-detail.test.tsx
+++ b/packages/views/issues/components/issue-detail.test.tsx
@@ -1410,7 +1410,7 @@ describe("IssueDetail (shared)", () => {
expect(within(replyBlock as HTMLElement).getByRole("button", { name: "Open full log" })).toBe(headerLog);
});
- it("replaces each queued run in place without moving replies behind later requests", async () => {
+ it("keeps each queued run after its request and moves it in place to its reply's time", async () => {
const root = mockTimeline[0]!;
const second = { ...root, id: "request-two", parent_id: root.id, content: "Second request", created_at: "2026-01-16T00:00:02Z" };
const third = { ...root, id: "request-three", parent_id: root.id, content: "Third request", created_at: "2026-01-16T00:00:04Z" };
@@ -1429,6 +1429,10 @@ describe("IssueDetail (shared)", () => {
</I18nProvider>);
await waitFor(() => expect(container.querySelectorAll('[data-run-slot-id]')).toHaveLength(3));
const slots = tasks.map((task) => container.querySelector(`[data-run-slot-id="${task.id}"]`)!);
+ const [secondRow, thirdRow] = [second, third].map((request) => container.querySelector(`#comment-${request.id}`)!);
+ expect(secondRow!.previousElementSibling).toBe(slots[0]);
+ expect(secondRow!.nextElementSibling).toBe(slots[1]);
+ expect(thirdRow!.nextElementSibling).toBe(slots[2]);
fireEvent.click(within(slots[0] as HTMLElement).getByRole("button", { name: /View activity/ }));
await within(slots[0] as HTMLElement).findByText("No activity recorded yet.");
for (const index of [0, 1]) {
@@ -1450,8 +1454,11 @@ describe("IssueDetail (shared)", () => {
}
expect(within(slots[0] as HTMLElement).getByRole("button", { name: "Open full log" })).toBeInTheDocument();
expect(within(slots[0] as HTMLElement).queryByRole("button", { name: /View activity/ })).not.toBeInTheDocument();
- expect(slots[0]!.nextElementSibling?.id).toBe("comment-request-two");
- expect(slots[1]!.nextElementSibling?.id).toBe("comment-request-three");
+ // Answers land at their own time, after the requests; the queued run
+ // stays with its request.
+ expect(thirdRow!.nextElementSibling).toBe(slots[2]);
+ expect(slots[2]!.nextElementSibling).toBe(slots[0]);
+ expect(slots[0]!.nextElementSibling).toBe(slots[1]);
expect(container.querySelector(`[data-run-slot-id="${tasks[2]!.id}"]`)).toBe(slots[2]);
expect(within(slots[2] as HTMLElement).getByText("Waiting for an available agent.")).toBeInTheDocument();
});
@@ -1472,6 +1479,42 @@ describe("IssueDetail (shared)", () => {
expect(container.querySelector(`#comment-${root.id}`)?.querySelector(`[data-run-id="${second.id}"]`)).not.toBeNull();
});
+ // MUL-7628: Elon was asked first but replied last; his review used to render
+ // under the request, above the rest of the thread.
+ it("orders thread replies by send time and quotes the request a late reply answers", async () => {
+ const root = mockTimeline[0]!;
+ const request = (id: string, content: string, created_at: string): TimelineEntry =>
+ ({ ...root, id, parent_id: root.id, content, created_at, updated_at: created_at });
+ const askElon = request("ask-elon", "Review the code", "2026-01-16T00:15:32Z");
+ const askSteve = request("ask-steve", "CI is failing", "2026-01-16T00:15:41Z");
+ const run = (id: string, trigger: TimelineEntry): AgentTask => ({
+ id, agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "issue-1", status: "completed", priority: 0,
+ created_at: trigger.created_at, started_at: trigger.created_at, dispatched_at: trigger.created_at,
+ completed_at: "2026-01-16T00:40:00Z", result: null, error: null,
+ trigger_comment_id: trigger.id, delivered_comment_ids: [trigger.id],
+ });
+ const elon = run("ba2e8d1c-7f9b-4e2a-9c1d-123456789ab0", askElon);
+ const steve = run("ba2e8d1c-7f9b-4e2a-9c1d-123456789ab1", askSteve);
+ const answer = (id: string, task: AgentTask, content: string, created_at: string): TimelineEntry =>
+ ({ ...mockTimeline[1]!, id, parent_id: root.id, source_task_id: task.id, content, created_at, updated_at: created_at });
+ mockApiObj.listTimeline.mockResolvedValue([root, askElon, askSteve,
+ answer("steve-fixed", steve, "Fixed the CI failure", "2026-01-16T00:23:41Z"),
+ answer("elon-review", elon, "Review complete", "2026-01-16T00:32:29Z"),
+ request("follow-up", "Fix it, then ask for another review", "2026-01-16T00:35:05Z")]);
+ mockApiObj.listTasksByIssue.mockResolvedValue([elon, steve]);
+ const { container } = renderIssueDetail();
+
+ await screen.findByText("Review complete");
+ const order = ["ask-elon", "ask-steve", "steve-fixed", "elon-review", "follow-up"].map((id) => `comment-${id}`);
+ expect(Array.from(container.querySelectorAll("[id]"), (element) => element.id).filter((id) => order.includes(id)))
+ .toEqual(order);
+ const review = container.querySelector("#comment-elon-review") as HTMLElement;
+ const quote = within(review).getByRole("button", { name: "Replying to Test User: Review the code" });
+ expect(within(container.querySelector("#comment-steve-fixed") as HTMLElement).queryByText(/Replying to/)).toBeNull();
+ fireEvent.click(quote);
+ expect(container.querySelector("#comment-ask-elon")?.className).toContain(highlightedCommentBackgroundClass);
+ });
+
it.each(["failed", "cancelled"] as const)("keeps a %s run outside the user reply that triggered it", async (status) => {
const root = mockTimeline[0]!;
const trigger = { ...root, id: "user-reply", parent_id: root.id, content: "Please try this task" };
@@ -3056,6 +3099,8 @@ describe("IssueDetail (shared)", () => {
// MUL-7548 regression: a comment-triggered run that posts several comments
// used to render its latest one first — the run slot after the trigger held
// only the latest, and the earlier ones followed it (or stayed top-level).
+ // Each comment reads at its own time, so a reply written between two of the
+ // run's comments stays between them (MUL-7628).
it.each([
{ placement: "top-level", parentId: null },
{ placement: "in the trigger's thread", parentId: "confirm" },
@@ -3071,6 +3116,11 @@ describe("IssueDetail (shared)", () => {
created_at: "2026-01-17T00:00:00Z", updated_at: "2026-01-17T00:00:00Z", comment_type: "comment",
},
agentComment("step2", "Step 2 done", "2026-01-17T00:10:00Z"),
+ {
+ type: "comment", id: "aside", actor_type: "member", actor_id: "user-1",
+ content: "Check the tests too", parent_id: "confirm",
+ created_at: "2026-01-17T00:15:00Z", updated_at: "2026-01-17T00:15:00Z", comment_type: "comment",
+ },
agentComment("step3", "Step 3 done", "2026-01-17T00:20:00Z"),
]);
mockApiObj.listTasksByIssue.mockResolvedValue([{
@@ -3086,8 +3136,8 @@ describe("IssueDetail (shared)", () => {
await screen.findByText("Step 3 done");
const rendered = Array.from(container.querySelectorAll("[id^='comment-']")).map((el) => el.id)
- .filter((id) => ["comment-confirm", "comment-step2", "comment-step3"].includes(id));
- expect(rendered).toEqual(["comment-confirm", "comment-step2", "comment-step3"]);
+ .filter((id) => ["comment-confirm", "comment-step2", "comment-aside", "comment-step3"].includes(id));
+ expect(rendered).toEqual(["comment-confirm", "comment-step2", "comment-aside", "comment-step3"]);
});
});
diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsx
index 527cced445..3c808adb65 100644
--- a/packages/views/issues/components/issue-detail.tsx
+++ b/packages/views/issues/components/issue-detail.tsx
@@ -1831,33 +1831,41 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
},
[],
);
+ // Flash the landed comment the same way inbox deep-links do, so the eye has
+ // an anchor after the instant jump. (Folded resolved bars don't take the
+ // highlight prop — the scroll itself is the feedback there.)
+ const flashJumpTarget = useCallback((commentId: string) => {
+ setHighlightedId(commentId);
+ if (jumpFlashTimerRef.current !== null) window.clearTimeout(jumpFlashTimerRef.current);
+ jumpFlashTimerRef.current = window.setTimeout(() => setHighlightedId(null), 2000);
+ }, []);
+ // Jump to a mounted comment: any row in flat mode, or a reply inside a
+ // rendered thread. Drive the container's scrollTop directly — never native
+ // scrollIntoView, which also scrolls the desktop shell (#3929).
+ const jumpToComment = useCallback(
+ (commentId: string) => {
+ const el = document.getElementById(`comment-${commentId}`);
+ const container = scrollContainerEl;
+ if (!el || !container) return;
+ const c = container.getBoundingClientRect();
+ const e = el.getBoundingClientRect();
+ container.scrollTop = Math.max(0, container.scrollTop + (e.top - c.top) - 16);
+ flashJumpTarget(commentId);
+ },
+ [scrollContainerEl, flashJumpTarget],
+ );
const jumpToThread = useCallback(
(threadId: string) => {
- if (isFlatTimeline) {
- // Flat mode mounts every row, so the anchor is always in the DOM.
- // Drive the container's scrollTop directly — never native
- // scrollIntoView, which also scrolls the desktop shell (#3929).
- const el = document.getElementById(`comment-${threadId}`);
- const container = scrollContainerEl;
- if (!el || !container) return;
- const c = container.getBoundingClientRect();
- const e = el.getBoundingClientRect();
- container.scrollTop = Math.max(0, container.scrollTop + (e.top - c.top) - 16);
- } else {
- // Virtualized mode: the target row may not be mounted, so scroll by
- // index and let Virtuoso mount it. Offset leaves a small top gap.
- const index = items.findIndex((it) => it.id === threadId);
- if (index < 0) return;
- virtuosoRef.current?.scrollToIndex({ index, align: "start", offset: -16 });
- }
- // Flash the landed thread the same way inbox deep-links do, so the eye
- // has an anchor after the instant jump. (Folded resolved bars don't
- // take the highlight prop — the scroll itself is the feedback there.)
- setHighlightedId(threadId);
- if (jumpFlashTimerRef.current !== null) window.clearTimeout(jumpFlashTimerRef.current);
- jumpFlashTimerRef.current = window.setTimeout(() => setHighlightedId(null), 2000);
+ // Flat mode mounts every row, so the anchor is always in the DOM.
+ if (isFlatTimeline) return jumpToComment(threadId);
+ // Virtualized mode: the target row may not be mounted, so scroll by
+ // index and let Virtuoso mount it. Offset leaves a small top gap.
+ const index = items.findIndex((it) => it.id === threadId);
+ if (index < 0) return;
+ virtuosoRef.current?.scrollToIndex({ index, align: "start", offset: -16 });
+ flashJumpTarget(threadId);
},
- [isFlatTimeline, items, scrollContainerEl],
+ [isFlatTimeline, items, jumpToComment, flashJumpTarget],
);
const {
@@ -2758,7 +2766,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
onReplyAccepted: scrollToTimelineBottom, onEdit: editComment, onDelete: deleteComment,
onToggleReaction: handleToggleReaction, onCreateSubIssue: openCommentSubIssue,
onResolveToggle: handleResolveToggle,
- onCopyLink: actions.copyCommentLink,
+ onCopyLink: actions.copyCommentLink, onJumpToComment: jumpToComment,
onCollapseResolved: reply.resolved_at ? () => toggleResolvedExpand(reply.id, false) : undefined,
expandedResolvedIds: expandedResolved, onResolvedExpandChange: toggleResolvedExpand,
highlightedCommentId: highlightedId,
@@ -2797,6 +2805,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr
onCreateSubIssue={openCommentSubIssue}
onResolveToggle={handleResolveToggle}
onCopyLink={actions.copyCommentLink}
+ onJumpToComment={jumpToComment}
onCollapseResolved={isResolved ? () => toggleResolvedExpand(item.id, false) : undefined}
expandedResolvedIds={expandedResolved}
onResolvedExpandChange={toggleResolvedExpand}
diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.json
index 009f51bc9b..372d0147ae 100644
--- a/packages/views/locales/en/issues.json
+++ b/packages/views/locales/en/issues.json
@@ -568,6 +568,7 @@
"delete_failed": "Failed to delete comment",
"reply_count_one": "{{count}} reply",
"reply_count_other": "{{count}} replies",
+ "replying_to": "Replying to {{name}}: {{preview}}",
"leave_comment_placeholder": "Leave a comment...",
"send_tooltip": "Send",
"trigger_source_issue_assignee": "assignee",
diff --git a/packages/views/locales/fr/issues.json b/packages/views/locales/fr/issues.json
index 120a352e3b..c85762bd78 100644
--- a/packages/views/locales/fr/issues.json
+++ b/packages/views/locales/fr/issues.json
@@ -568,6 +568,7 @@
"delete_failed": "Échec de la suppression du commentaire",
"reply_count_one": "{{count}} réponse",
"reply_count_other": "{{count}} réponses",
+ "replying_to": "En réponse à {{name}} : {{preview}}",
"leave_comment_placeholder": "Laisser un commentaire...",
"send_tooltip": "Envoyer",
"trigger_source_issue_assignee": "assigné",
diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.json
index 10b838b35f..d5740d0638 100644
--- a/packages/views/locales/ja/issues.json
+++ b/packages/views/locales/ja/issues.json
@@ -557,6 +557,7 @@
"send_reply_failed": "返信を送信できませんでした",
"delete_failed": "コメントを削除できませんでした",
"reply_count_other": "返信 {{count}} 件",
+ "replying_to": "{{name}} への返信: {{preview}}",
"leave_comment_placeholder": "コメントを残す...",
"send_tooltip": "送信",
"trigger_source_issue_assignee": "担当",
diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.json
index 474d9cb74b..be22974c67 100644
--- a/packages/views/locales/ko/issues.json
+++ b/packages/views/locales/ko/issues.json
@@ -557,6 +557,7 @@
"send_reply_failed": "답글을 보내지 못했습니다",
"delete_failed": "댓글을 삭제하지 못했습니다",
"reply_count_other": "답글 {{count}}개",
+ "replying_to": "{{name}}에게 답글: {{preview}}",
"leave_comment_placeholder": "댓글 남기기...",
"send_tooltip": "보내기",
"trigger_source_issue_assignee": "담당자",
diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.json
index dd5b378cad..93bf39a6b5 100644
--- a/packages/views/locales/zh-Hans/issues.json
+++ b/packages/views/locales/zh-Hans/issues.json
@@ -557,6 +557,7 @@
"send_reply_failed": "发送回复失败",
"delete_failed": "删除评论失败",
"reply_count_other": "{{count}} 条回复",
+ "replying_to": "回复 {{name}}:{{preview}}",
"leave_comment_placeholder": "留下评论...",
"send_tooltip": "发送",
"trigger_source_issue_assignee": "assignee",