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
1 change: 0 additions & 1 deletion apps/web/src/components/chat/MessagesTimeline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1690,7 +1690,6 @@ const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: Time
row.kind === "assistant-meta"
? "group/assistant"
: null,
"group/sub-thread-row",
)}
data-timeline-row-id={row.id}
data-timeline-row-kind={row.kind}
Expand Down
3 changes: 2 additions & 1 deletion apps/web/src/components/chat/TimelineAssistantRows.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts"
import { useAtomValue } from "@effect/atom-react";
import { AsyncResult, Atom } from "effect/reactivity";
import { vcsEnvironment } from "../../state/vcs";
import { SubThreadReplyLine } from "../../fork/subThreads/SubThreadReplyLine";
import { SubThreadMetaReply, SubThreadReplyLine } from "../../fork/subThreads/SubThreadReplyLine";
import { AgentMessageDivider } from "../../fork/displayMode/AgentMessageDivider";
import { EditedMark } from "../../fork/displayMode/EditedMark";

Expand Down Expand Up @@ -291,6 +291,7 @@ function AssistantMessageMeta({
</TooltipPopup>
</Tooltip>
)}
<SubThreadMetaReply messageId={message.id} />
</div>
);
}
Expand Down
52 changes: 38 additions & 14 deletions apps/web/src/fork/subThreads/SubThreadReplyLine.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -92,40 +92,64 @@ function ReplyLine(props: {
}

/**
* The Reply slot's height with a mouse: the button's 16px less the row's bottom padding, so the
* button stays inside the row, which the list clips. Mirrors TimelineRowContent's message padding:
* pb-1 when grouped with the next row, pb-2 for an agent message with no meta, else pb-4.
* Height of the Reply slot with a mouse. The Reply button is 16px tall, and the list clips
* anything outside the row, so the slot is 16px minus the row's bottom padding. For an agent
* message with no meta row (the Copy and time line), TimelineRowContent sets pb-1 (4px) when
* grouped with the next row and pb-2 (8px) otherwise, giving h-3 or h-2.
*/
const fineSlotHeight = (row: Extract<TimelineRow, { kind: "message" }>) =>
row.groupedWithNext
? "h-3"
: row.message.role === "assistant" && !row.showAssistantMeta
? "h-2"
: "h-0";
row.groupedWithNext ? "h-3" : "h-2";

/**
* At the end of one of the agent's main-list rows that has no reply yet: a Reply button, since the
* user follows up on what the agent said. With a mouse it shows while the pointer is on the row, in
* the row's bottom padding and a slot that tops it up. On a touch screen it always shows and has its
* own height, so it stays clear of the next row.
* Reply button under an agent's main-list message with no replies yet and no meta row (the line
* with Copy and the time). Rows with a meta row use SubThreadMetaReply instead. With a mouse, it
* shows on row hover or focus and sits in the row's bottom padding plus a slot. On touch, it
* always shows with its own height so it clears the next row.
*/
export function SubThreadReplyButton(props: {
readonly row: Extract<TimelineRow, { kind: "message" }>;
}) {
const subThread = useRowSubThread(props.row.id);
if (subThread === null || props.row.message.role === "user" || subThread.summary.replies > 0)
if (
subThread === null ||
props.row.message.role === "user" ||
props.row.showAssistantMeta ||
subThread.summary.replies > 0
)
return null;
const { threadRef, summary } = subThread;
return (
<div className={cn("relative flex pointer-coarse:h-auto", fineSlotHeight(props.row))}>
<button
type="button"
onClick={() => openSubThread(threadRef, summary.first)}
className="absolute top-0 left-0 z-10 inline-flex items-center gap-1 rounded-md bg-background px-1.5 text-muted-foreground text-xs opacity-0 outline-none hover:bg-accent hover:text-foreground focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset group-hover/sub-thread-row:opacity-100 pointer-coarse:static pointer-coarse:py-0.5 pointer-coarse:opacity-100"
className="absolute top-0 left-0 z-10 inline-flex items-center gap-1 rounded-md bg-background px-1.5 text-muted-foreground text-xs opacity-0 outline-none hover:bg-accent hover:text-foreground focus-visible:opacity-100 focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset group-hover/assistant:opacity-100 pointer-coarse:static pointer-coarse:py-0.5 pointer-coarse:opacity-100"
>
<ReplyIcon className="size-3" />
Reply
</button>
</div>
);
}

/**
* Reply button at the end of an agent message's meta row, right of the time. It renders only when
* that message starts a main-list sub-thread with no replies yet. It has no visibility rules of
* its own. It shows and hides with the meta row.
*/
export function SubThreadMetaReply(props: { readonly messageId: string }) {
const subThread = useRowSubThread(props.messageId);
if (subThread === null || subThread.summary.replies > 0) return null;
const { threadRef, summary } = subThread;
return (
// As tall as the meta row's xs buttons, in the time's 12px text at every width.
<button
type="button"
onClick={() => openSubThread(threadRef, summary.first)}
className="inline-flex h-7 shrink-0 items-center gap-1 rounded-md px-1.5 text-muted-foreground text-xs outline-none hover:bg-accent hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset sm:h-6"
>
<ReplyIcon className="size-3" />
Reply
</button>
);
}
155 changes: 155 additions & 0 deletions apps/web/src/fork/subThreads/subThreadReplyButton.browser.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
import { createMemoryHistory } from "@tanstack/react-router";
import { MessageId, TurnItemId } from "@t3tools/contracts";
import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings";
import { CHAT_REPLIES_DISPLAY_MODE } from "@t3tools/shared/displayModes";
import type * as Context from "effect/Context";
import { expect, it, vi } from "vite-plus/test";
import { page, userEvent } from "vite-plus/test/browser";

import { AppRoot } from "~/AppRoot";
// Layout asserts need the app's styles.
import "~/index.css";
// The route loads ChatView lazily, and its first transform takes seconds; see ChatView.browser.test.tsx.
import "~/components/ChatView";
import { __setClientSettingsForTests } from "~/hooks/useSettings";
import { getRouter } from "~/router";
import {
assistantItem,
ENVIRONMENT_ID,
installFakeEnvironment,
threadWithHistory,
type FakeDriver,
} from "../../../test/fakeEnvironment";
import { render } from "../../../test/render";
import { replyContextField } from "./subThreadReply";

vi.mock(
"../../../../../packages/client-runtime/src/connection/driver.ts",
async (importOriginal) => {
const [actual, { fakeDriver }, Layer] = await Promise.all([
importOriginal<{ readonly ConnectionDriver: Context.Key<unknown, FakeDriver> }>(),
import("../../../test/fakeEnvironment"),
import("effect/Layer"),
]);
return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) };
},
);

vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({
...(await original()),
trackRpcRequestSent: () => {},
}));

/**
* A one-turn thread whose agent also sent "The deploy is done.", which has no replies yet, or with
* `replied`, the user's reply "Which deploy?".
*/
function threadWithAgentSend(name: string, replied = false) {
const history = threadWithHistory(name, 1);
const {
messageId: _id,
text: _text,
streaming: _streaming,
...item
} = assistantItem(history.id, history.runs[0]!.id, `${name}-news`, 2, "");
const news = {
...item,
type: "dynamic_tool" as const,
toolName: "mcp__t3-code__send_to_user",
input: { text: "The deploy is done.", new_sub_thread: true },
output: { ok: true },
};
const reply = {
...item,
id: TurnItemId.make(`${name}-reply`),
ordinal: 3,
type: "user_message" as const,
messageId: MessageId.make(`${name}-reply`),
text: "Which deploy?",
attachments: [],
inputIntent: "turn_start" as const,
createdBy: "user" as const,
creationSource: "web" as const,
...replyContextField(news.id),
};
return { ...history, items: [...history.items, news, ...(replied ? [reply] : [])] };
}

const thread = threadWithAgentSend("reply-inline");
const replied = threadWithAgentSend("reply-inline-replied", true);
const threads = [thread, replied];
const settings = {
threadDisplayModes: Object.fromEntries(threads.map((t) => [t.id, CHAT_REPLIES_DISPLAY_MODE.id])),
};

async function openThread(threadId: string, width: number) {
const environment = installFakeEnvironment(threads, { settings });
__setClientSettingsForTests({
...DEFAULT_CLIENT_SETTINGS,
onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
});
await page.viewport(width, 834);
const router = getRouter(
createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${threadId}`] }),
);
try {
await router.load();
const app = await render(<AppRoot router={router} />, { router: false });
return {
[Symbol.asyncDispose]: async () => {
await app[Symbol.asyncDispose]();
environment[Symbol.dispose]();
},
};
} catch (error) {
environment[Symbol.dispose]();
throw error;
}
}

/** The agent message's Reply button, and the time in the same message row. */
async function replyAndTime() {
const reply = page.getByRole("button", { name: "Reply", exact: true });
await expect.element(reply).toBeInTheDocument();
const row = reply.element().closest<HTMLElement>('[data-timeline-row-kind="message"]');
expect(row?.dataset.messageRole).toBe("assistant");
const time = row!.querySelector<HTMLElement>("p.tabular-nums");
expect(time).not.toBeNull();
return { reply: reply.element() as HTMLElement, time: time!, row: row! };
}

it.each([1194, 361])(
"an agent message's Reply sits right of its time, on the one meta row, at %ipx",
async (width) => {
await using _app = await openThread(thread.id, width);
const { reply, time, row } = await replyAndTime();

const replyBox = reply.getBoundingClientRect();
const timeBox = time.getBoundingClientRect();
const middle = (box: DOMRect) => box.top + box.height / 2;
expect(Math.abs(middle(replyBox) - middle(timeBox))).toBeLessThan(2);
expect(replyBox.left).toBeGreaterThanOrEqual(timeBox.right);
// Nothing of the row is drawn below the meta row.
expect(replyBox.bottom).toBeLessThanOrEqual(row.getBoundingClientRect().bottom);
// Reply and the time are items of the same flex row.
expect(reply.parentElement).toBe(time.parentElement);
expect(getComputedStyle(reply.parentElement!).display).toBe("flex");
},
);

it("Enter on a focused Reply opens that message's replies", async () => {
await using _app = await openThread(thread.id, 1194);
const { reply } = await replyAndTime();
reply.focus();
await userEvent.keyboard("{Enter}");
const first = thread.items.at(-1)!.id;
await vi.waitFor(() =>
expect(document.querySelector(`[data-sub-thread-view="${first}"]`)).not.toBeNull(),
);
});

it("a message that has a reply shows its reply line and no Reply button", async () => {
await using _app = await openThread(replied.id, 1194);
await expect.element(page.getByRole("button", { name: /1 reply/ })).toBeInTheDocument();
expect(page.getByRole("button", { name: "Reply", exact: true }).elements()).toHaveLength(0);
});
Loading