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
74 changes: 74 additions & 0 deletions apps/web/src/components/ChatView.agents.browser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -1445,6 +1445,80 @@ describe("ChatView (full app): agent browser tabs and rooms", () => {
}
});

it("keeps short-titled tabs on the row where they fit, instead of behind +N", async () => {
const titles = ["UI", "DB", "QA", "CI", "Ops", "Docs", "Perf", "Auth"];
const children = titles.map((_, index) => `thread-short-${index}` as ThreadId);
const base = children.reduce(
(snapshot, child) => addThreadToSnapshot(snapshot, child),
createSnapshotForTargetUser({
targetMessageId: "msg-user-short-family" as MessageId,
targetText: "short family target",
}),
);
const mounted = await mountChatView({
viewport: DEFAULT_VIEWPORT,
snapshot: {
...base,
projects: base.projects.map((project) => ({ ...project, leadThreadId: THREAD_ID })),
threads: base.threads.map((thread) => {
const index = children.indexOf(thread.id);
return index === -1
? thread
: {
...thread,
title: titles[index]!,
parentThreadId: THREAD_ID,
attachedToParent: true,
createdAt: isoAt(10 + index),
};
}),
},
});
const row = () => document.querySelector<HTMLElement>('[data-testid="family-tabs"]');
try {
await vi.waitFor(
() => expect(row()?.querySelectorAll('[role="tab"]')).toHaveLength(1 + titles.length),
{ timeout: 10_000 },
);
// Nine tabs at the 96px floor would not fit; at their own widths they do, none cut.
const onRow = () => [
...row()!.querySelectorAll<HTMLElement>(
'[role="tab"], [data-testid="family-tabs-overflow"]',
),
];
const unclipped = () =>
onRow().every((item) => {
const label = item.querySelector<HTMLElement>("span.truncate") ?? item;
return label.scrollWidth <= label.clientWidth;
});
const inside = () =>
onRow().every(
(item) =>
item.getBoundingClientRect().right <= row()!.getBoundingClientRect().right + 0.5,
);
expect(row()!.clientWidth).toBeLessThan((1 + titles.length) * 96);
expect(row()!.querySelector('[data-testid="family-tabs-overflow"]')).toBeNull();
expect(unclipped()).toBe(true);
expect(inside()).toBe(true);

// A larger browser font: the row measures what it draws, so what shows still fits whole.
document.documentElement.style.fontSize = "24px";
try {
await vi.waitFor(
() => expect(row()!.querySelector('[data-testid="family-tabs-overflow"]')).not.toBeNull(),
{ timeout: 5_000 },
);
await nextFrames(3);
expect(unclipped()).toBe(true);
expect(inside()).toBe(true);
} finally {
document.documentElement.style.fontSize = "";
}
} finally {
await mounted.cleanup();
}
});

it("names the thread that started this one, in the header and on its request", async () => {
const base = createSnapshotForTargetUser({
targetMessageId: "msg-user-started-by" as MessageId,
Expand Down
169 changes: 142 additions & 27 deletions apps/web/src/components/chat/FamilyTabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import { buildThreadRouteParams } from "../../threadRoutes";
import { Menu, MenuItem, MenuPopup, MenuTrigger } from "../ui/menu";
import { LeadChatCard, LeadChatSuggestion } from "./LeadChatHints";
import {
FAMILY_TAB_MIN_WIDTH_PX,
type FamilyTab,
type FamilyTabs as FamilyTabsModel,
familyTabsOf,
Expand All @@ -50,8 +51,85 @@ export function useFamilyTabsShown(threadKey: string | null): boolean {
);
}

/** What "+N" takes on the row, its own width. */
const OVERFLOW_PX = 44;
/** A tab's box, shared by the drawn tabs and their measured copies so the two match. */
const TAB_BOX_CLASS = "flex h-6 items-center gap-1.5 rounded-md px-2 text-xs";
/** The "+N" button's box, shared the same way. */
const OVERFLOW_BOX_CLASS = "relative flex h-6 shrink-0 items-center rounded-md px-2 text-xs";

/** What a tab shows as its title: the lead's is "Lead". */
function tabText(tab: FamilyTab): string {
return tab.kind === "parent" && tab.lead ? "Lead" : tab.shortTitle;
}

/** The row as drawn: its width inside the padding, the gap between tabs, and each tab's own width. */
interface RowMeasure {
readonly rowPx: number;
readonly gapPx: number;
/** Each tab at its title's full length, up to the 200px cap, by key. */
readonly tabPx: ReadonlyMap<string, number>;
/** "+N" with the most digits it can need. */
readonly overflowPx: number;
}

function sameRowMeasure(left: RowMeasure | null, right: RowMeasure): boolean {
return (
left !== null &&
left.rowPx === right.rowPx &&
left.gapPx === right.gapPx &&
left.overflowPx === right.overflowPx &&
left.tabPx.size === right.tabPx.size &&
[...right.tabPx].every(([key, px]) => left.tabPx.get(key) === px)
);
}

/**
* Reads the row and the hidden copies of its tabs (`measureRef`): what fits
* is decided before a tab is drawn, and one behind "+N" isn't drawn at all.
* The copies are the tabs' own markup and classes, so a larger browser font,
* a theme's font, or a font that loads late shows up as a resize the
* observer reports. Null until the row is on screen, and on a phone.
*/
function useRowMeasure(
rowRef: React.RefObject<HTMLDivElement | null>,
measureRef: React.RefObject<HTMLDivElement | null>,
enabled: boolean,
tabKeys: string,
): RowMeasure | null {
const [measure, setMeasure] = useState<RowMeasure | null>(null);
useLayoutEffect(() => {
const row = rowRef.current;
const layer = measureRef.current;
if (!enabled || row === null || layer === null) return;
// The copies of these tabs, by key, and the copy of "+N".
const copies = tabKeys.split("\n").flatMap((key) => {
const copy = layer.querySelector<HTMLElement>(`[data-measure-key="${CSS.escape(key)}"]`);
return copy === null ? [] : [[key, copy] as const];
});
const overflowCopy = layer.querySelector<HTMLElement>("[data-measure-overflow]");
const read = () => {
const style = getComputedStyle(row);
const next: RowMeasure = {
rowPx:
row.getBoundingClientRect().width -
parseFloat(style.paddingLeft) -
parseFloat(style.paddingRight) -
parseFloat(style.borderLeftWidth) -
parseFloat(style.borderRightWidth),
gapPx: parseFloat(style.columnGap) || 0,
tabPx: new Map(copies.map(([key, copy]) => [key, copy.getBoundingClientRect().width])),
overflowPx: overflowCopy?.getBoundingClientRect().width ?? 0,
};
setMeasure((previous) => (sameRowMeasure(previous, next) ? previous : next));
};
read();
const observer = new ResizeObserver(read);
observer.observe(row);
for (const [, copy] of copies) observer.observe(copy);
if (overflowCopy !== null) observer.observe(overflowCopy);
return () => observer.disconnect();
}, [enabled, measureRef, rowRef, tabKeys]);
return enabled ? measure : null;
}

/**
* The row for `threadRef`'s family, or nothing when it has none. While it
Expand Down Expand Up @@ -127,17 +205,13 @@ const FamilyTabRow = memo(function FamilyTabRow({
}) {
const isMobile = useIsMobile();
const rowRef = useRef<HTMLDivElement | null>(null);
const [rowPx, setRowPx] = useState<number | null>(null);
useLayoutEffect(() => {
const row = rowRef.current;
if (row === null || isMobile) return;
setRowPx(row.clientWidth);
const observer = new ResizeObserver(([entry]) => {
if (entry) setRowPx(Math.round(entry.contentRect.width));
});
observer.observe(row);
return () => observer.disconnect();
}, [isMobile]);
const measureRef = useRef<HTMLDivElement | null>(null);
const measure = useRowMeasure(
rowRef,
measureRef,
!isMobile,
family.tabs.map((tab) => tab.key).join("\n"),
);

// On a phone the row scrolls sideways instead, with the open tab in view.
const openTabRef = useRef<HTMLButtonElement | null>(null);
Expand All @@ -149,13 +223,19 @@ const FamilyTabRow = memo(function FamilyTabRow({
}, [openKey, isMobile]);

const { shown, hidden } =
isMobile || rowPx === null
measure === null
? { shown: family.tabs, hidden: [] as readonly FamilyTab[] }
: fitFamilyTabs({
tabs: family.tabs,
openKey: family.openKey,
rowPx,
overflowPx: OVERFLOW_PX,
rowPx: measure.rowPx,
overflowPx: measure.overflowPx,
gapPx: measure.gapPx,
// A short tab costs its own width; a long one the shared floor; the lead never shrinks.
floorPx: (tab) => {
const px = measure.tabPx.get(tab.key) ?? FAMILY_TAB_MIN_WIDTH_PX;
return tab.kind === "parent" && tab.lead ? px : Math.min(px, FAMILY_TAB_MIN_WIDTH_PX);
},
});

// The parent, open and not leading yet, may be offered as the lead (LeadChatSuggestion).
Expand All @@ -178,10 +258,32 @@ const FamilyTabRow = memo(function FamilyTabRow({
data-testid="family-tabs"
data-family-key={family.familyKey}
className={cn(
"flex min-w-0 shrink-0 items-center gap-0.5 border-b border-border px-3 py-1 sm:px-5",
"relative flex min-w-0 shrink-0 items-center gap-0.5 border-b border-border px-3 py-1 sm:px-5",
isMobile && "overflow-x-auto [scrollbar-width:none]",
)}
>
{isMobile ? null : (
// Every tab and "+N" at full width, unseen, for useRowMeasure.
<div
ref={measureRef}
aria-hidden="true"
inert
className="pointer-events-none invisible absolute top-0 left-0 flex h-0 w-max overflow-hidden"
>
{family.tabs.map((tab) => (
<span
key={tab.key}
data-measure-key={tab.key}
className={cn(TAB_BOX_CLASS, "max-w-50 shrink-0")}
>
<FamilyTabFace tab={tab} />
</span>
))}
<span data-measure-overflow className={OVERFLOW_BOX_CLASS}>
+{family.tabs.length}
</span>
</div>
)}
{shown.map((tab) => (
<FamilyTabButton
key={tab.key}
Expand Down Expand Up @@ -248,7 +350,8 @@ const FamilyTabButton = memo(function FamilyTabButton({
data-family-tab-kind={tab.kind}
disabled={tab.threadRef === null}
className={cn(
"flex h-6 items-center gap-1.5 rounded-md px-2 text-xs transition-colors focus-ring",
TAB_BOX_CLASS,
"transition-colors focus-ring",
// As wide as its title up to a 200px cap, packed to the left. When the
// row is crowded, every tab starts from the same 200px basis, so the
// longest titles give way first and all end up the same width (toward
Expand All @@ -267,6 +370,20 @@ const FamilyTabButton = memo(function FamilyTabButton({
}}
{...touchHold}
>
<FamilyTabFace tab={tab} />
</button>
);
return isLeadTab && tab.threadRef !== null ? (
<LeadChatCard threadRef={tab.threadRef} renderTrigger={tabButton} />
) : (
tabButton(null)
);
});

/** A tab's mark (the lead's crown, a child's status dot or check) and title. */
function FamilyTabFace({ tab }: { tab: FamilyTab }) {
return (
<>
{tab.kind === "parent" ? (
tab.lead ? (
<CrownIcon aria-hidden="true" className="size-3 shrink-0" />
Expand All @@ -282,15 +399,10 @@ const FamilyTabButton = memo(function FamilyTabButton({
)}
/>
)}
<span className="min-w-0 truncate">{isLeadTab ? "Lead" : tab.shortTitle}</span>
</button>
);
return isLeadTab && tab.threadRef !== null ? (
<LeadChatCard threadRef={tab.threadRef} renderTrigger={tabButton} />
) : (
tabButton(null)
<span className="min-w-0 truncate">{tabText(tab)}</span>
</>
);
});
}

/** "+N": the tabs that don't fit, with their status; amber while one needs the user. */
function FamilyTabOverflow({
Expand All @@ -306,7 +418,10 @@ function FamilyTabOverflow({
<Menu>
<MenuTrigger
data-testid="family-tabs-overflow"
className="relative flex h-6 shrink-0 items-center rounded-md px-2 text-xs text-muted-foreground transition-colors hover:text-foreground focus-ring"
className={cn(
OVERFLOW_BOX_CLASS,
"text-muted-foreground transition-colors hover:text-foreground focus-ring",
)}
>
+{hidden.length}
{needsYouDot !== null ? (
Expand Down
37 changes: 28 additions & 9 deletions apps/web/src/components/chat/familyTabs.logic.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,18 +126,37 @@ describe("fitting the row", () => {
inbox: null,
});
const tabs = ["a", "b", "c", "d", "e", "f"].map((key) => tab(key, key === "f"));
const fit = (openKey: string, rowPx: number, floors: Record<string, number> = {}, gapPx = 0) =>
fitFamilyTabs({
tabs,
openKey,
rowPx,
overflowPx: 40,
gapPx,
floorPx: (entry) => floors[entry.key] ?? 100,
});
const keys = (list: readonly FamilyTab[]) => list.map((entry) => entry.key);

it("keeps every tab while they fit at the floor, else moves the last behind +N", () => {
expect(fitFamilyTabs({ tabs, openKey: "a", rowPx: 600, overflowPx: 40 }).hidden).toEqual([]);
const tight = fitFamilyTabs({ tabs, openKey: "a", rowPx: 340, overflowPx: 40 });
expect(tight.shown.map((entry) => entry.key)).toEqual(["a", "b", "c"]);
expect(tight.hidden.map((entry) => entry.key)).toEqual(["d", "e", "f"]);
it("keeps every tab while they fit at their floors, else moves the last behind +N", () => {
expect(fit("a", 600).hidden).toEqual([]);
// Two pixels between tabs: six 100px tabs no longer fit in 600.
expect(keys(fit("a", 600, {}, 2).hidden)).toEqual(["f"]);
const tight = fit("a", 340);
expect(keys(tight.shown)).toEqual(["a", "b", "c"]);
expect(keys(tight.hidden)).toEqual(["d", "e", "f"]);
expect(tight.hidden.some((entry) => entry.needsYou)).toBe(true);
});

it("always keeps the open thread's tab on the row", () => {
const tight = fitFamilyTabs({ tabs, openKey: "e", rowPx: 340, overflowPx: 40 });
expect(tight.shown.map((entry) => entry.key)).toEqual(["a", "b", "e"]);
expect(tight.hidden.map((entry) => entry.key)).toEqual(["c", "d", "f"]);
it("charges a short title only its own width", () => {
const short = { a: 60, b: 30, c: 30, d: 30, e: 30, f: 30 };
expect(fit("a", 220, short).hidden).toEqual([]);
});

it("always keeps the parent's tab and the open thread's on the row", () => {
const tight = fit("e", 340);
expect(keys(tight.shown)).toEqual(["a", "b", "e"]);
expect(keys(tight.hidden)).toEqual(["c", "d", "f"]);
// Too narrow for both: neither gives way.
expect(keys(fit("e", 150).shown)).toEqual(["a", "e"]);
});
});
Loading
Loading