fix(orchestrator): Order thread lineage by creation time (#5310)

This commit is contained in:
Mike Olson authored and Julius Marminge committed 2026-08-14 11:23:31 +02:00
1 parent f682f0a6e6
commit d8257507a8
4 files changed
+478 -140

No files matched your search

@@ -0,0 +1,49 @@
import { describe, expect, it } from "vite-plus/test";
import { renderToStaticMarkup } from "react-dom/server";
import { resolveThreadLineageWindow, ThreadLineageRowList } from "./ThreadRelationshipsControl";
const rows = Array.from({ length: 20 }, (_, index) => `row-${index}`);
function renderRowList(visibleCount: number) {
const { visibleRows, hiddenCount } = resolveThreadLineageWindow(rows, visibleCount);
return renderToStaticMarkup(
<ThreadLineageRowList hiddenCount={hiddenCount} onShowMore={() => {}}>
{visibleRows.map((row) => (
<li key={row}>{row}</li>
))}
</ThreadLineageRowList>,
);
}
describe("thread lineage row list", () => {
it("shows six rows before the first expansion", () => {
const { visibleRows, hiddenCount } = resolveThreadLineageWindow(rows, 6);
expect(visibleRows).toEqual(rows.slice(0, 6));
expect(hiddenCount).toBe(14);
});
it("offers one page at a time", () => {
expect(renderRowList(6)).toContain("Show 12 more");
expect(renderRowList(6 + 12)).toContain("Show 2 more");
});
it("omits the expansion affordance when everything fits", () => {
const markup = renderRowList(rows.length);
expect(markup).not.toContain("more");
expect(resolveThreadLineageWindow(rows.slice(0, 6), 6).hiddenCount).toBe(0);
});
it("keeps the rows in a bounded, labelled scroll region and the button outside it", () => {
const markup = renderRowList(6);
const list = /<ul([^>]*)>/.exec(markup)?.[1] ?? "";
expect(list).toContain('aria-label="Related threads"');
expect(list).toContain("max-h-[13.5rem]");
expect(list).toContain("overflow-y-auto");
expect(list).toContain("overscroll-contain");
expect(markup.indexOf("</ul>")).toBeLessThan(markup.indexOf("<button"));
});
});
@@ -1,7 +1,9 @@
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
import {
deriveThreadRelationshipGraph,
immediateThreadRelationships,
isParentThreadRelationship,
orderWebThreadLineageRows,
resolveMergeBackTargetThreadId,
type ThreadRelationshipEdge,
} from "@t3tools/client-runtime/state/thread-relationships";
@@ -19,9 +21,10 @@ import {
GitMergeIcon,
LoaderCircleIcon,
MoreHorizontalIcon,
PlusIcon,
UnplugIcon,
} from "lucide-react";
import { useState } from "react";
import { useCallback, useMemo, useRef, useState, type ReactNode } from "react";
import { useArchivedThreadSnapshots } from "../../lib/archivedThreadsState";
import { buildThreadRouteParams } from "../../threadRoutes";
@@ -44,6 +47,56 @@ import {
const THREAD_RELATIONSHIP_ICON_CLASS = "size-4 shrink-0 text-muted-foreground";
// Lineage paging: a busy thread can accumulate dozens of forks and subagents,
// and the panel it lives in already scrolls. Show a workable window, keep the
// rest behind Show more, and bound what is shown so the sections below Lineage
// stay reachable.
const THREAD_LINEAGE_INITIAL_COUNT = 6;
const THREAD_LINEAGE_PAGE_COUNT = 12;
export function resolveThreadLineageWindow<Row>(
rows: ReadonlyArray<Row>,
visibleCount: number,
): { readonly visibleRows: ReadonlyArray<Row>; readonly hiddenCount: number } {
const visibleRows = rows.slice(0, visibleCount);
return { visibleRows, hiddenCount: rows.length - visibleRows.length };
}
export function ThreadLineageRowList(props: {
readonly hiddenCount: number;
readonly onShowMore: () => void;
readonly children: ReactNode;
}) {
return (
<>
{/*
Bounded rather than free-growing so Lineage cannot push the rest of the
thread details panel out of view. Plain overflow, not a ScrollArea
component: this sits inside an already scrolling panel, where a
max-height-only virtual viewport measures badly. Every row is a focusable
button, so keyboard users reach and scroll the region through the rows
themselves and the container needs no extra tab stop of its own.
*/}
<ul
aria-label="Related threads"
className="m-0 max-h-[13.5rem] list-none overflow-y-auto overscroll-contain p-0"
>
{props.children}
</ul>
{props.hiddenCount > 0 ? (
<button
type="button"
onClick={props.onShowMore}
className="flex h-9 w-full cursor-pointer items-center gap-2.5 rounded-lg px-2.5 text-left text-[13px] font-medium text-muted-foreground/70 hover:bg-black/[0.055] hover:text-foreground/80 dark:hover:bg-white/[0.075]"
>
<PlusIcon aria-hidden className="-mx-0.5 size-4 shrink-0" />
Show {Math.min(props.hiddenCount, THREAD_LINEAGE_PAGE_COUNT)} more
</button>
) : null}
</>
);
}
function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: ThreadId) {
if (edge.kind === "transfer") return "Context transfer";
if (edge.kind === "subagent") {
@@ -52,21 +105,6 @@ function relationshipLabel(edge: ThreadRelationshipEdge, currentThreadId: Thread
return edge.sourceThreadId === currentThreadId ? "Fork" : "Parent thread";
}
function isParentRelationship(edge: ThreadRelationshipEdge, currentThreadId: ThreadId): boolean {
return edge.kind !== "transfer" && edge.targetThreadId === currentThreadId;
}
function relationshipSortKey(input: {
readonly edge: ThreadRelationshipEdge;
readonly threadId: ThreadId;
readonly currentThreadId: ThreadId;
readonly mergeTargetThreadId: ThreadId | null;
}): number {
if (isParentRelationship(input.edge, input.currentThreadId)) return 0;
if (input.threadId === input.mergeTargetThreadId) return 1;
return 2;
}
function statusDotClass(status: string | null): string {
if (status === "running" || status === "in_progress") return "bg-info";
if (status === "failed" || status === "error") return "bg-destructive";
@@ -89,42 +127,51 @@ export function ThreadRelationshipsPanel(props: {
const ref = scopeThreadRef(props.environmentId, props.threadId);
const projection = useThreadProjection(ref)?.projection ?? null;
const threadShells = useThreadShells();
const activeShells = threadShells.filter(
(thread) => thread.environmentId === props.environmentId,
);
const archived = useArchivedThreadSnapshots([props.environmentId]);
const archivedShells = archived.snapshots.find(
(entry) => entry.environmentId === props.environmentId,
)?.snapshot.threads;
const shells: ReadonlyArray<OrchestrationV2ThreadShell> = [
...activeShells.map((thread) => thread.source),
...(archivedShells ?? []),
];
const graph = deriveThreadRelationshipGraph({ threads: shells, projection });
const graph = useMemo(() => {
const shells: ReadonlyArray<OrchestrationV2ThreadShell> = [
...threadShells
.filter((thread) => thread.environmentId === props.environmentId)
.map((thread) => thread.source),
...(archivedShells ?? []),
];
return deriveThreadRelationshipGraph({ threads: shells, projection });
}, [archivedShells, projection, props.environmentId, threadShells]);
const navigate = useNavigate();
const mergeBack = useAtomCommand(threadEnvironment.mergeBack);
const stopSession = useAtomCommand(threadEnvironment.stopSession);
const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
const latestMergeBackRun = projection === null ? null : resolveLatestMergeBackRun(projection);
const mergeTargetThreadId = resolveMergeBackTargetThreadId(projection);
const relationshipRows = immediateThreadRelationships(graph, props.threadId).toSorted(
(left, right) =>
relationshipSortKey({
edge: left.edge,
threadId: left.threadId,
currentThreadId: props.threadId,
mergeTargetThreadId,
}) -
relationshipSortKey({
edge: right.edge,
threadId: right.threadId,
const relationshipRows = useMemo(
() =>
orderWebThreadLineageRows({
graph,
rows: immediateThreadRelationships(graph, props.threadId),
currentThreadId: props.threadId,
mergeTargetThreadId,
}),
[graph, mergeTargetThreadId, props.threadId],
);
const canMerge = mergeTargetThreadId !== null && latestMergeBackRun !== null;
const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
const [visibleCount, setVisibleCount] = useState(THREAD_LINEAGE_INITIAL_COUNT);
const lineageResetKey = scopedThreadKey(ref);
const lastLineageResetKeyRef = useRef(lineageResetKey);
if (lastLineageResetKeyRef.current !== lineageResetKey) {
lastLineageResetKeyRef.current = lineageResetKey;
setVisibleCount(THREAD_LINEAGE_INITIAL_COUNT);
}
const showMore = useCallback(
() => setVisibleCount((count) => count + THREAD_LINEAGE_PAGE_COUNT),
[],
);
const { visibleRows, hiddenCount } = resolveThreadLineageWindow(relationshipRows, visibleCount);
if (relationshipRows.length === 0) {
return null;
}
@@ -206,113 +253,51 @@ export function ThreadRelationshipsPanel(props: {
</div>
</div>
{relationshipRows.length > 0 ? (
<ul className="m-0 list-none p-0">
{relationshipRows.map(({ threadId, edge }) => {
const node = graph.nodes.get(threadId);
const isSubagent = edge.kind === "subagent";
const isMergeTarget = threadId === mergeTargetThreadId;
const isParent = isParentRelationship(edge, props.threadId);
const RelationshipIcon = isParent
? CornerLeftUpIcon
: isSubagent
? BotIcon
: GitForkIcon;
const relationship = relationshipLabel(edge, props.threadId);
const threadTitle = relationshipThreadTitle({
title: node?.thread?.title ?? threadId,
isSubagent,
});
const relationshipContent = (
<>
<span className="relative -mx-0.5 grid size-4 shrink-0 place-items-center">
<RelationshipIcon className={THREAD_RELATIONSHIP_ICON_CLASS} />
<span
className={cn(
"absolute -bottom-1 -right-1 size-2 rounded-full border-2 border-card",
statusDotClass(edge.status),
)}
aria-hidden="true"
/>
<ThreadLineageRowList hiddenCount={hiddenCount} onShowMore={showMore}>
{visibleRows.map(({ threadId, edge }) => {
const node = graph.nodes.get(threadId);
const isSubagent = edge.kind === "subagent";
const isMergeTarget = threadId === mergeTargetThreadId;
const isParent = isParentThreadRelationship(edge, props.threadId);
const RelationshipIcon = isParent ? CornerLeftUpIcon : isSubagent ? BotIcon : GitForkIcon;
const relationship = relationshipLabel(edge, props.threadId);
const threadTitle = relationshipThreadTitle({
title: node?.thread?.title ?? threadId,
isSubagent,
});
const relationshipContent = (
<>
<span className="relative -mx-0.5 grid size-4 shrink-0 place-items-center">
<RelationshipIcon className={THREAD_RELATIONSHIP_ICON_CLASS} />
<span
className={cn(
"absolute -bottom-1 -right-1 size-2 rounded-full border-2 border-card",
statusDotClass(edge.status),
)}
aria-hidden="true"
/>
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-[13px] font-medium leading-4 text-foreground/85">
{threadTitle}
</span>
<span className="min-w-0 flex-1">
<span className="block truncate text-[13px] font-medium leading-4 text-foreground/85">
{threadTitle}
</span>
</span>
<ArrowRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
</>
);
return (
<li key={threadId} className="group flex h-9 items-center rounded-lg">
{isMergeTarget ? (
<div className={THREAD_DETAILS_PANEL_LINK_SPLIT_GROUP_CLASS}>
<Tooltip>
<TooltipTrigger
render={
<Button
size="sm"
variant="ghost"
className={THREAD_DETAILS_PANEL_LINK_SPLIT_PRIMARY_CLASS}
disabled={node?.missing === true}
onClick={() => openThread(threadId)}
/>
}
>
{relationshipContent}
</TooltipTrigger>
<TooltipPopup side="left">
{node?.missing
? "This related thread is unavailable"
: `Open ${relationship.toLowerCase()} in this chat`}
</TooltipPopup>
</Tooltip>
<span
aria-hidden="true"
className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS}
/>
<Tooltip>
<TooltipTrigger
render={
<Button
size="sm"
variant="ghost"
className={THREAD_DETAILS_PANEL_LINK_SPLIT_SECONDARY_CLASS}
aria-label={
parentTitle
? `Merge back to ${parentTitle}`
: "Merge back to source conversation"
}
disabled={!canMerge || busyAction !== null}
onClick={() => void merge()}
>
{busyAction === "merge" ? (
<LoaderCircleIcon className="size-3 animate-spin" />
) : (
<GitMergeIcon className="size-3" />
)}
</Button>
}
/>
<TooltipPopup side="left">
{latestMergeBackRun === null
? "Complete a run in this fork before merging it back"
: parentTitle
? `Merge this conversation back into ${parentTitle}`
: "Merge this conversation back into its source"}
</TooltipPopup>
</Tooltip>
</div>
) : (
</span>
<ArrowRightIcon className="size-3 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100" />
</>
);
return (
<li key={threadId} className="group flex h-9 items-center rounded-lg">
{isMergeTarget ? (
<div className={THREAD_DETAILS_PANEL_LINK_SPLIT_GROUP_CLASS}>
<Tooltip>
<TooltipTrigger
render={
<Button
size="sm"
variant="ghost"
className={THREAD_DETAILS_PANEL_LINK_SPLIT_PRIMARY_CLASS}
disabled={node?.missing === true}
onClick={() => openThread(threadId)}
className={THREAD_DETAILS_PANEL_LINK_ROW_CLASS}
/>
}
>
@@ -324,12 +309,65 @@ export function ThreadRelationshipsPanel(props: {
: `Open ${relationship.toLowerCase()} in this chat`}
</TooltipPopup>
</Tooltip>
)}
</li>
);
})}
</ul>
) : null}
<span aria-hidden="true" className={THREAD_DETAILS_PANEL_SPLIT_SEPARATOR_CLASS} />
<Tooltip>
<TooltipTrigger
render={
<Button
size="sm"
variant="ghost"
className={THREAD_DETAILS_PANEL_LINK_SPLIT_SECONDARY_CLASS}
aria-label={
parentTitle
? `Merge back to ${parentTitle}`
: "Merge back to source conversation"
}
disabled={!canMerge || busyAction !== null}
onClick={() => void merge()}
>
{busyAction === "merge" ? (
<LoaderCircleIcon className="size-3 animate-spin" />
) : (
<GitMergeIcon className="size-3" />
)}
</Button>
}
/>
<TooltipPopup side="left">
{latestMergeBackRun === null
? "Complete a run in this fork before merging it back"
: parentTitle
? `Merge this conversation back into ${parentTitle}`
: "Merge this conversation back into its source"}
</TooltipPopup>
</Tooltip>
</div>
) : (
<Tooltip>
<TooltipTrigger
render={
<Button
size="sm"
variant="ghost"
disabled={node?.missing === true}
onClick={() => openThread(threadId)}
className={THREAD_DETAILS_PANEL_LINK_ROW_CLASS}
/>
}
>
{relationshipContent}
</TooltipTrigger>
<TooltipPopup side="left">
{node?.missing
? "This related thread is unavailable"
: `Open ${relationship.toLowerCase()} in this chat`}
</TooltipPopup>
</Tooltip>
)}
</li>
);
})}
</ThreadLineageRowList>
</section>
);
}
@@ -1,9 +1,11 @@
import { describe, expect, it } from "vite-plus/test";
import { ThreadId } from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
import {
deriveThreadRelationshipGraph,
immediateThreadRelationships,
orderWebThreadLineageRows,
relatedThreadIds,
resolveMergeBackTargetThreadId,
walkThreadRelationships,
@@ -200,3 +202,194 @@ describe("thread relationships", () => {
).toBeNull();
});
});
const current = ThreadId.make("thread-current");
function forkShell(input: {
readonly id: ThreadId;
readonly parentThreadId: ThreadId | null;
readonly createdAt?: string;
readonly updatedAt?: string;
readonly status?: string;
}) {
return {
id: input.id,
title: input.id,
status: input.status ?? "completed",
archivedAt: null,
forkedFrom:
input.parentThreadId === null
? null
: { type: "run", threadId: input.parentThreadId, runId: `run-${input.id}` },
lineage: {
rootThreadId: input.parentThreadId ?? input.id,
parentThreadId: input.parentThreadId,
relationshipToParent: input.parentThreadId === null ? null : "fork",
},
createdAt: input.createdAt === undefined ? undefined : DateTime.makeUnsafe(input.createdAt),
updatedAt: DateTime.makeUnsafe(input.updatedAt ?? "2026-06-20T00:00:00.000Z"),
};
}
function orderedLineageIds(input: {
readonly threads: ReadonlyArray<unknown>;
readonly mergeTargetThreadId?: ThreadId | null;
readonly projection?: unknown;
}): ReadonlyArray<ThreadId> {
const graph = deriveThreadRelationshipGraph({
threads: input.threads as never,
projection: (input.projection ?? null) as never,
});
return orderWebThreadLineageRows({
graph,
rows: immediateThreadRelationships(graph, current),
currentThreadId: current,
mergeTargetThreadId: input.mergeTargetThreadId ?? null,
}).map(({ threadId }) => threadId);
}
describe("web thread lineage ordering", () => {
it("orders sibling forks newest created first", () => {
const oldest = ThreadId.make("thread-fork-oldest");
const middle = ThreadId.make("thread-fork-middle");
const newest = ThreadId.make("thread-fork-newest");
expect(
orderedLineageIds({
threads: [
forkShell({ id: current, parentThreadId: null, createdAt: "2026-06-01T00:00:00.000Z" }),
forkShell({
id: oldest,
parentThreadId: current,
createdAt: "2026-06-02T00:00:00.000Z",
}),
forkShell({
id: middle,
parentThreadId: current,
createdAt: "2026-06-03T00:00:00.000Z",
}),
forkShell({
id: newest,
parentThreadId: current,
createdAt: "2026-06-04T00:00:00.000Z",
}),
],
}),
).toEqual([newest, middle, oldest]);
});
it("does not reorder when related-thread activity arrives", () => {
const first = ThreadId.make("thread-fork-a");
const second = ThreadId.make("thread-fork-b");
const third = ThreadId.make("thread-fork-c");
const before = orderedLineageIds({
threads: [
forkShell({ id: current, parentThreadId: null, createdAt: "2026-06-01T00:00:00.000Z" }),
forkShell({ id: first, parentThreadId: current, createdAt: "2026-06-02T00:00:00.000Z" }),
forkShell({ id: second, parentThreadId: current, createdAt: "2026-06-03T00:00:00.000Z" }),
forkShell({ id: third, parentThreadId: current, createdAt: "2026-06-04T00:00:00.000Z" }),
],
});
// The shell snapshot arrives ordered by `updated_at`, and a client-side
// `thread.updated` re-appends the shell it replaces, so both the input
// order and the mutable timestamps move under us while the panel is open.
const after = orderedLineageIds({
threads: [
forkShell({
id: second,
parentThreadId: current,
createdAt: "2026-06-03T00:00:00.000Z",
updatedAt: "2026-07-30T00:00:00.000Z",
status: "running",
}),
forkShell({ id: third, parentThreadId: current, createdAt: "2026-06-04T00:00:00.000Z" }),
forkShell({ id: current, parentThreadId: null, createdAt: "2026-06-01T00:00:00.000Z" }),
forkShell({
id: first,
parentThreadId: current,
createdAt: "2026-06-02T00:00:00.000Z",
updatedAt: "2026-07-31T00:00:00.000Z",
status: "failed",
}),
],
});
expect(before).toEqual([third, second, first]);
expect(after).toEqual(before);
});
it("pins the parent first and a distinct merge-back target second", () => {
// The panel keeps its two action rows in place regardless of creation time:
// parent first, then a merge-back target that is not the parent. The two
// diverge while a shell update and its projection disagree about the fork
// source, which is exactly when a moving row would misfire a merge.
const parent = ThreadId.make("thread-parent");
const mergeTarget = ThreadId.make("thread-merge-target");
const newestFork = ThreadId.make("thread-newest-fork");
expect(
orderedLineageIds({
threads: [
forkShell({ id: parent, parentThreadId: null, createdAt: "2026-06-01T00:00:00.000Z" }),
forkShell({
id: current,
parentThreadId: parent,
createdAt: "2026-06-02T00:00:00.000Z",
}),
forkShell({
id: mergeTarget,
parentThreadId: current,
createdAt: "2026-06-03T00:00:00.000Z",
}),
forkShell({
id: newestFork,
parentThreadId: current,
createdAt: "2026-06-09T00:00:00.000Z",
}),
],
mergeTargetThreadId: mergeTarget,
}),
).toEqual([parent, mergeTarget, newestFork]);
});
it("sinks missing nodes and shells without a decoded createdAt", () => {
const missingTransfer = ThreadId.make("thread-missing-transfer");
const undated = ThreadId.make("thread-undated-fork");
const dated = ThreadId.make("thread-dated-fork");
expect(
orderedLineageIds({
threads: [
forkShell({ id: current, parentThreadId: null, createdAt: "2026-06-01T00:00:00.000Z" }),
forkShell({ id: undated, parentThreadId: current }),
forkShell({ id: dated, parentThreadId: current, createdAt: "2026-06-02T00:00:00.000Z" }),
],
projection: {
thread: { id: current },
subagents: [],
contextTransfers: [
{ sourceThreadId: current, targetThreadId: missingTransfer, status: "completed" },
],
},
}),
).toEqual([dated, missingTransfer, undated]);
});
it("breaks equal creation times by thread id", () => {
const first = ThreadId.make("thread-fork-a");
const second = ThreadId.make("thread-fork-b");
const third = ThreadId.make("thread-fork-c");
expect(
orderedLineageIds({
threads: [
forkShell({ id: current, parentThreadId: null, createdAt: "2026-06-01T00:00:00.000Z" }),
forkShell({ id: third, parentThreadId: current, createdAt: "2026-06-02T00:00:00.000Z" }),
forkShell({ id: first, parentThreadId: current, createdAt: "2026-06-02T00:00:00.000Z" }),
forkShell({ id: second, parentThreadId: current, createdAt: "2026-06-02T00:00:00.000Z" }),
],
}),
).toEqual([first, second, third]);
});
});
@@ -3,6 +3,7 @@ import type {
OrchestrationV2ThreadShell,
ThreadId,
} from "@t3tools/contracts";
import * as DateTime from "effect/DateTime";
export type ThreadRelationshipKind = "parent" | "fork" | "subagent" | "transfer";
@@ -176,3 +177,60 @@ export function immediateThreadRelationships(
return rows;
}
/** True when `edge` reaches `currentThreadId` from its parent or owning agent. */
export function isParentThreadRelationship(
edge: ThreadRelationshipEdge,
currentThreadId: ThreadId,
): boolean {
return edge.kind !== "transfer" && edge.targetThreadId === currentThreadId;
}
function threadCreatedAtMillis(node: ThreadRelationshipNode | undefined): number | null {
// `createdAt` is typed as a DateTime, but the value reaches here from a
// decoded shell that may be missing (a related thread we have no shell for).
const createdAt: unknown = node?.thread?.createdAt;
if (!DateTime.isDateTime(createdAt)) return null;
const millis = DateTime.toEpochMillis(createdAt);
return Number.isFinite(millis) ? millis : null;
}
/**
* Orders the web thread-details Lineage rows for display.
*
* Web-specific by design: the panel pins the parent row first and a distinct
* merge-back target second so their actions stay where the user expects, and
* only then falls back to newest-created-first. Mobile does not share that
* exception, so this is not the canonical relationship order and should not be
* reused as one.
*
* Ordering below the pins is `createdAt` descending, which is immutable, so
* rows never move when messages or status changes arrive on a related thread.
* Threads whose shell is missing (or whose `createdAt` did not decode) sink to
* the bottom. Ties break by thread id ascending so the order is total.
*/
export function orderWebThreadLineageRows(input: {
readonly graph: ThreadRelationshipGraph;
readonly rows: ReadonlyArray<ThreadRelationshipWalkRow>;
readonly currentThreadId: ThreadId;
readonly mergeTargetThreadId: ThreadId | null;
}): ReadonlyArray<ThreadRelationshipWalkRow> {
const pinRank = (row: ThreadRelationshipWalkRow): number => {
if (isParentThreadRelationship(row.edge, input.currentThreadId)) return 0;
if (row.threadId === input.mergeTargetThreadId) return 1;
return 2;
};
return input.rows.toSorted((left, right) => {
const rankDelta = pinRank(left) - pinRank(right);
if (rankDelta !== 0) return rankDelta;
const leftCreatedAt = threadCreatedAtMillis(input.graph.nodes.get(left.threadId));
const rightCreatedAt = threadCreatedAtMillis(input.graph.nodes.get(right.threadId));
if (leftCreatedAt !== rightCreatedAt) {
if (leftCreatedAt === null) return 1;
if (rightCreatedAt === null) return -1;
return rightCreatedAt - leftCreatedAt;
}
return left.threadId < right.threadId ? -1 : left.threadId > right.threadId ? 1 : 0;
});
}