πͺ’ Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(trace): the compact timeline is the Timeline, and the old one is gone (#16689)
Nikita Kabardin94eae03c1a48
diff --git a/web/src/__tests__/server/organization-feature-flags.servertest.ts b/web/src/__tests__/server/organization-feature-flags.servertest.tsindex 06af6722f2..756bf76d04 100644--- a/web/src/__tests__/server/organization-feature-flags.servertest.ts+++ b/web/src/__tests__/server/organization-feature-flags.servertest.ts@@ -65,12 +65,12 @@ describe("organization feature preview defaults", () => {const admin = await prepare("cloud:core", Role.ADMIN);await prisma.user.update({where: { id: admin.actor.id },- data: { featureFlags: ["compactTimeline"] },+ data: { featureFlags: ["modernSession"] },});await expect(admin.caller.organizations.setFeatureFlagOrgDefault({orgId: admin.org.id,- flag: "compactTimeline",+ flag: "modernSession",enabled: true,}),).resolves.toMatchObject({ enabled: true });@@ -79,7 +79,7 @@ describe("organization feature preview defaults", () => {await expect(member.caller.organizations.setFeatureFlagOrgDefault({orgId: member.org.id,- flag: "compactTimeline",+ flag: "modernSession",enabled: true,}),).rejects.toMatchObject({ code: "FORBIDDEN" });@@ -103,7 +103,7 @@ describe("organization feature preview defaults", () => {await expect(caller.organizations.setFeatureFlagOrgDefault({orgId: org.id,- flag: "compactTimeline",+ flag: "modernSession",enabled: true,}),).rejects.toMatchObject({ code: "PRECONDITION_FAILED" });@@ -171,7 +171,9 @@ describe("organization feature preview defaults", () => {const { caller, org } = await prepare();await prisma.organization.update({where: { id: org.id },- data: { featureFlagOrgDefaults: ["modernSession", "compactTimeline"] },+ data: {+ featureFlagOrgDefaults: ["modernSession", "futurePreview"],+ },});const member = await createUser({featureFlags: [@@ -201,8 +203,12 @@ describe("organization feature preview defaults", () => {members.memberships.find((membership) => membership.userId === member.id)?.featurePreviews,).toEqual({+ // The member's opt-out beats the organization default, and neither+ // default was copied onto the user (asserted above). `futurePreview` is+ // not a registered preview, so it is filtered out rather than surfacing+ // here. Asserting that two REGISTERED defaults resolve differently needs+ // a second preview; add that half back with the next one.modernSession: false,- compactTimeline: true,});});@@ -237,7 +243,7 @@ describe("organization feature preview defaults", () => {describe("organization member feature preview overrides", () => {it("persists an administrator's disable as a global user opt-out", async () => {const { caller, org } = await prepare();- const target = await createUser({ featureFlags: ["compactTimeline"] });+ const target = await createUser({ featureFlags: ["modernSession"] });await prisma.organizationMembership.create({data: { orgId: org.id, userId: target.id, role: Role.MEMBER },});@@ -245,7 +251,7 @@ describe("organization member feature preview overrides", () => {await caller.members.setUserFeaturePreviewEnabled({orgId: org.id,userId: target.id,- flag: "compactTimeline",+ flag: "modernSession",enabled: false,});@@ -255,7 +261,7 @@ describe("organization member feature preview overrides", () => {select: { featureFlags: true },}),).resolves.toEqual({- featureFlags: [getFeaturePreviewOptOutFlag("compactTimeline")],+ featureFlags: [getFeaturePreviewOptOutFlag("modernSession")],});});@@ -263,7 +269,7 @@ describe("organization member feature preview overrides", () => {const { caller, org } = await prepare();await prisma.organization.update({where: { id: org.id },- data: { featureFlagOrgDefaults: ["compactTimeline"] },+ data: { featureFlagOrgDefaults: ["modernSession"] },});const target = await createUser();const membership = await prisma.organizationMembership.create({@@ -273,7 +279,7 @@ describe("organization member feature preview overrides", () => {await caller.members.setUserFeaturePreviewEnabled({orgId: org.id,userId: target.id,- flag: "compactTimeline",+ flag: "modernSession",enabled: false,});@@ -287,12 +293,12 @@ describe("organization member feature preview overrides", () => {orderBy: { createdAt: "desc" },});expect(JSON.parse(auditEntry.before!)).toEqual({- flag: "compactTimeline",+ flag: "modernSession",override: "inherit",scope: "global",});expect(JSON.parse(auditEntry.after!)).toEqual({- flag: "compactTimeline",+ flag: "modernSession",override: "disabled",scope: "global",});@@ -312,7 +318,7 @@ describe("organization member feature preview overrides", () => {await caller.members.setUserFeaturePreviewEnabled({orgId: org.id,userId: target.id,- flag: "compactTimeline",+ flag: "modernSession",enabled: true,});@@ -326,12 +332,12 @@ describe("organization member feature preview overrides", () => {orderBy: { createdAt: "desc" },});expect(JSON.parse(auditEntry.before!)).toEqual({- flag: "compactTimeline",+ flag: "modernSession",override: "inherit",scope: "global",});expect(JSON.parse(auditEntry.after!)).toEqual({- flag: "compactTimeline",+ flag: "modernSession",override: "enabled",scope: "global",});@@ -403,7 +409,7 @@ describe("organization member feature preview overrides", () => {caller.members.setUserFeaturePreviewEnabled({orgId: org.id,userId: target.id,- flag: "compactTimeline",+ flag: "modernSession",enabled: true,}),).resolves.toMatchObject({ enabled: true });@@ -416,7 +422,7 @@ describe("organization member feature preview overrides", () => {it("does not expose raw or foreign-organization feature flag data", async () => {const { caller, org } = await prepare();const target = await createUser({- featureFlags: ["templateFlag", "compactTimeline"],+ featureFlags: ["templateFlag", "modernSession"],});await prisma.organizationMembership.create({data: { orgId: org.id, userId: target.id, role: Role.MEMBER },@@ -431,10 +437,9 @@ describe("organization member feature preview overrides", () => {(membership) => membership.userId === target.id,);- expect(row?.featurePreviews).toEqual({- modernSession: false,- compactTimeline: true,- });+ // The state map surfaces every preview; the raw `featureFlags` array stays+ // hidden, which is what this guards.+ expect(row?.featurePreviews).toEqual({ modernSession: true });expect(row?.user).not.toHaveProperty("featureFlags");expect(row).not.toHaveProperty("organizationIds");});diff --git a/web/src/components/grouped-score-badge.tsx b/web/src/components/grouped-score-badge.tsxindex 401c2bfecf..59957ed3ad 100644--- a/web/src/components/grouped-score-badge.tsx+++ b/web/src/components/grouped-score-badge.tsx@@ -24,7 +24,7 @@ import { ScoreTag, scoreLevelFromScore } from "@/src/components/score-tag";* has to RESERVE room for these badges buckets them identically β two copies of* the grouping rule are two chances to price a chip that never renders.*/-export const groupScoresByName = <+const groupScoresByName = <T extends WithStringifiedMetadata<ScoreDomain> | LastUserScore,>(scores: T[],diff --git a/web/src/features/feature-flags/available-flags.ts b/web/src/features/feature-flags/available-flags.tsindex d88ec0063b..9e81906642 100644--- a/web/src/features/feature-flags/available-flags.ts+++ b/web/src/features/feature-flags/available-flags.ts@@ -1,9 +1,6 @@import { assertUnreachable } from "@langfuse/shared";-export const featurePreviewFlags = [- "modernSession",- "compactTimeline",-] as const;+export const featurePreviewFlags = ["modernSession"] as const;export type FeaturePreviewFlag = (typeof featurePreviewFlags)[number];@@ -18,7 +15,6 @@ export const filterFeaturePreviewFlags = (export const featurePreviewLabels = {modernSession: "Compact Session View",- compactTimeline: "Compact Timeline",} satisfies Record<FeaturePreviewFlag, string>;export type FeaturePreviewAvailabilityContext = {@@ -33,10 +29,6 @@ export const isFeaturePreviewAvailable = (return context.v4BetaEnabled;}- if (flag === "compactTimeline") {- return true;- }-return assertUnreachable(flag);};diff --git a/web/src/features/feature-flags/components/OrganizationFeaturePreviewsSettings.clienttest.tsx b/web/src/features/feature-flags/components/OrganizationFeaturePreviewsSettings.clienttest.tsxindex 3a9afc8d4f..414065b075 100644--- a/web/src/features/feature-flags/components/OrganizationFeaturePreviewsSettings.clienttest.tsx+++ b/web/src/features/feature-flags/components/OrganizationFeaturePreviewsSettings.clienttest.tsx@@ -21,8 +21,13 @@ const mocks = vi.hoisted(() => ({experimentalFeaturesEnabled: false,userFeatureFlags: {modernSession: false,- compactTimeline: false,- },+ } as Record<string, boolean>,+ /**+ * Which previews are already organization defaults. Per-test, because a test+ * that needs a preview which is NOT yet a default cannot rely on the registry+ * happening to hold one β both surviving previews are defaults by fixture.+ */+ orgDefaults: ["modernSession"] as string[],updateSession: vi.fn().mockResolvedValue(undefined),}));@@ -118,7 +123,7 @@ vi.mock("@/src/utils/api", () => ({organizations: {getFeatureFlagOrgDefaults: {useQuery: () => ({- data: { defaults: ["modernSession"], memberCount: 3 },+ data: { defaults: mocks.orgDefaults, memberCount: 3 },isError: false,isPending: false,}),@@ -139,8 +144,8 @@ describe("OrganizationFeaturePreviewsSettings", () => {mocks.experimentalFeaturesEnabled = false;mocks.userFeatureFlags = {modernSession: false,- compactTimeline: false,};+ mocks.orgDefaults = ["modernSession"];mocks.mutate.mockImplementation((variables) => {mocks.mutationOptions?.onSuccess?.({}, variables);});@@ -172,18 +177,19 @@ describe("OrganizationFeaturePreviewsSettings", () => {});it("requires an admin to enable a preview personally before enabling the organization default", () => {+ // Not a default yet: an admin can always turn one OFF, so the lock only+ // shows on a row they would be turning ON.+ mocks.orgDefaults = [];render(<OrganizationFeaturePreviewsSettings orgId="org-1" />);- expect(- screen.getByRole("checkbox", {- name: "Toggle Compact Timeline organization default",- }),- ).toBeDisabled();+ // The contrast half β a row the admin HAS enabled personally stays live β+ // needs a second registered preview, and there is one between one preview+ // reaching GA and the next landing. Add it back with the next preview.expect(screen.getByRole("checkbox", {name: "Toggle Compact Session View organization default",}),- ).not.toBeDisabled();+ ).toBeDisabled();const personalEnablementRequirements = screen.getAllByText(/enable this preview in your personal feature preview settings/i,);@@ -193,7 +199,8 @@ describe("OrganizationFeaturePreviewsSettings", () => {});it("confirms an organization default change and captures metadata once", async () => {- mocks.userFeatureFlags.compactTimeline = true;+ mocks.userFeatureFlags.modernSession = true;+ mocks.orgDefaults = [];render(<OrganizationFeaturePreviewsSettings orgId="org-1" />);expect(@@ -201,7 +208,7 @@ describe("OrganizationFeaturePreviewsSettings", () => {).toBeInTheDocument();fireEvent.click(screen.getByRole("checkbox", {- name: "Toggle Compact Timeline organization default",+ name: "Toggle Compact Session View organization default",}),);expect(screen.getByText("Already enabled for you")).toBeInTheDocument();@@ -212,18 +219,19 @@ describe("OrganizationFeaturePreviewsSettings", () => {expect(mocks.mutate).toHaveBeenCalledWith({orgId: "org-1",- flag: "compactTimeline",+ flag: "modernSession",enabled: true,});await waitFor(() => expect(mocks.capture).toHaveBeenCalledTimes(1));expect(mocks.capture).toHaveBeenCalledWith("organization_settings:feature_flag_default_toggled",- { feature: "compactTimeline", isEnabled: true },+ { feature: "modernSession", isEnabled: true },);});it("does not capture analytics when a default change fails", () => {- mocks.userFeatureFlags.compactTimeline = true;+ mocks.userFeatureFlags.modernSession = true;+ mocks.orgDefaults = [];mocks.mutate.mockImplementation(() => {mocks.mutationOptions?.onError?.(new Error("denied"));});@@ -231,7 +239,7 @@ describe("OrganizationFeaturePreviewsSettings", () => {fireEvent.click(screen.getByRole("checkbox", {- name: "Toggle Compact Timeline organization default",+ name: "Toggle Compact Session View organization default",}),);fireEvent.click(screen.getByRole("button", { name: "Confirm" }));diff --git a/web/src/features/feature-flags/components/UserFeaturePreviewsPopover.clienttest.tsx b/web/src/features/feature-flags/components/UserFeaturePreviewsPopover.clienttest.tsxindex 767d4a99d9..e584216eb9 100644--- a/web/src/features/feature-flags/components/UserFeaturePreviewsPopover.clienttest.tsx+++ b/web/src/features/feature-flags/components/UserFeaturePreviewsPopover.clienttest.tsx@@ -123,7 +123,6 @@ describe("UserFeaturePreviewsControl", () => {userId: "user-1",featurePreviews: {modernSession: false,- compactTimeline: false,},management: {allowed: false,@@ -150,14 +149,13 @@ describe("UserFeaturePreviewsControl", () => {userId: "user-1",featurePreviews: {modernSession: false,- compactTimeline: false,},management: { allowed: true },});fireEvent.click(screen.getByRole("checkbox", {- name: "Toggle Compact Timeline for user",+ name: "Toggle Compact Session View for user",}),);@@ -165,7 +163,7 @@ describe("UserFeaturePreviewsControl", () => {{orgId: "org-1",userId: "user-1",- flag: "compactTimeline",+ flag: "modernSession",enabled: true,},expect.objectContaining({ onSettled: expect.any(Function) }),@@ -175,7 +173,7 @@ describe("UserFeaturePreviewsControl", () => {});expect(mocks.capture).toHaveBeenCalledWith("organization_settings:user_feature_flag_toggled",- { feature: "compactTimeline", isEnabled: true },+ { feature: "modernSession", isEnabled: true },);});@@ -186,21 +184,20 @@ describe("UserFeaturePreviewsControl", () => {userId: "user-1",featurePreviews: {modernSession: false,- compactTimeline: false,},management: { allowed: true },});- const compactTimeline = screen.getByRole("checkbox", {- name: "Toggle Compact Timeline for user",- });const sessions = screen.getByRole("checkbox", {name: "Toggle Compact Session View for user",});- fireEvent.click(compactTimeline);+ fireEvent.click(sessions);- expect(compactTimeline).toBeDisabled();- expect(sessions).not.toBeDisabled();+ // Its own row only. The counterpart assertion β that every OTHER row stays+ // interactive β needs a second registered preview, which the registry does+ // not have between one preview reaching GA and the next one landing. Add it+ // back with the next preview; `isToggling` is per-flag, not per-list.+ expect(sessions).toBeDisabled();});it("refetches without capturing analytics when the mutation fails", async () => {@@ -213,14 +210,13 @@ describe("UserFeaturePreviewsControl", () => {userId: "user-1",featurePreviews: {modernSession: false,- compactTimeline: false,},management: { allowed: true },});fireEvent.click(screen.getByRole("checkbox", {- name: "Toggle Compact Timeline for user",+ name: "Toggle Compact Session View for user",}),);diff --git a/web/src/features/feature-flags/types.ts b/web/src/features/feature-flags/types.tsindex 32c0ab9fa1..c470a211ab 100644--- a/web/src/features/feature-flags/types.ts+++ b/web/src/features/feature-flags/types.ts@@ -2,9 +2,8 @@ import { type availableFlags } from "./available-flags";export type Flag = (typeof availableFlags)[number];export type Flags = {- [key in Exclude<Flag, "modernSession" | "compactTimeline">]: boolean;+ [key in Exclude<Flag, "modernSession">]: boolean;} & {// Optional while older sessions and test fixtures roll across new flags.modernSession?: boolean;- compactTimeline?: boolean;};diff --git a/web/src/features/feature-flags/utils.clienttest.ts b/web/src/features/feature-flags/utils.clienttest.tsindex 0a49761cb2..318c8407c3 100644--- a/web/src/features/feature-flags/utils.clienttest.ts+++ b/web/src/features/feature-flags/utils.clienttest.ts@@ -17,7 +17,6 @@ describe("parseFlags", () => {});expect(flags.modernSession).toBe(true);- expect(flags.compactTimeline).toBe(true);});it("enables feature previews by default for ClickHouse team members", () => {@@ -27,7 +26,6 @@ describe("parseFlags", () => {});expect(flags.modernSession).toBe(true);- expect(flags.compactTimeline).toBe(true);});it("does not enable feature previews by default for other users", () => {@@ -37,18 +35,23 @@ describe("parseFlags", () => {});expect(flags.modernSession).toBe(false);- expect(flags.compactTimeline).toBe(false);});it("honors a Langfuse team member's explicit opt-out", () => {- const flags = parseFlags([getFeaturePreviewOptOutFlag("modernSession")], {- email: "[email protected]",- v4BetaEnabled: true,- });+ const flags = parseFlags(+ [getFeaturePreviewOptOutFlag("modernSession"), "templateFlag"],+ {+ email: "[email protected]",+ v4BetaEnabled: true,+ },+ );expect(flags.modernSession).toBe(false);- // Opting out of one preview leaves the others alone.- expect(flags.compactTimeline).toBe(true);+ // Scoped to its own flag: the opt-out is a STRING match, so a matcher that+ // is too loose would take neighbouring flags down with it. A non-preview+ // flag stands in for that here, which keeps the guard alive no matter how+ // many previews the registry happens to hold.+ expect(flags.templateFlag).toBe(true);});it("honors an explicit opt-out for every user", () => {@@ -64,19 +67,18 @@ describe("parseFlags", () => {});it("applies organization defaults without overriding a global opt-out", () => {- const enabled = parseFlagsWithOrganizationDefaults(- [],- ["compactTimeline"],- { email: "[email protected]", v4BetaEnabled: true },- );+ const enabled = parseFlagsWithOrganizationDefaults([], ["modernSession"], {+ email: "[email protected]",+ v4BetaEnabled: true,+ });const optedOut = parseFlagsWithOrganizationDefaults(- [getFeaturePreviewOptOutFlag("compactTimeline")],- ["compactTimeline"],+ [getFeaturePreviewOptOutFlag("modernSession")],+ ["modernSession"],{ email: "[email protected]", v4BetaEnabled: true },);- expect(enabled.compactTimeline).toBe(true);- expect(optedOut.compactTimeline).toBe(false);+ expect(enabled.modernSession).toBe(true);+ expect(optedOut.modernSession).toBe(false);});it("selects flags from only the active project organization", () => {@@ -84,7 +86,7 @@ describe("parseFlags", () => {email: "[email protected]",v4BetaEnabled: true,});- const enabledInFirstOrg = { ...personalFlags, compactTimeline: true };+ const enabledInFirstOrg = { ...personalFlags, modernSession: true };const user = {featureFlags: personalFlags,organizations: [@@ -103,15 +105,15 @@ describe("parseFlags", () => {expect(getContextualFeatureFlags(user, { projectId: "project-a" })- ?.compactTimeline,+ ?.modernSession,).toBe(true);expect(getContextualFeatureFlags(user, { projectId: "project-b" })- ?.compactTimeline,+ ?.modernSession,).toBe(false);expect(getContextualFeatureFlags(user, { organizationId: "org-a" })- ?.compactTimeline,+ ?.modernSession,).toBe(true);});});diff --git a/web/src/features/feature-previews/assets/compact-timeline-dark.svg b/web/src/features/feature-previews/assets/compact-timeline-dark.svgdeleted file mode 100644index 8f3616d69e..0000000000--- a/web/src/features/feature-previews/assets/compact-timeline-dark.svg+++ /dev/null@@ -1,112 +0,0 @@-<svg width="1200" height="700" viewBox="0 0 1200 700" fill="none" xmlns="http://www.w3.org/2000/svg">- <rect width="1200" height="700" fill="#0A0A0A"/>- <rect x="32" y="28" width="1136" height="644" rx="18" fill="#141414" stroke="#2A2A2A" stroke-width="2"/>- <rect x="32" y="28" width="1136" height="60" rx="18" fill="#0A0A0A"/>- <path d="M32 88H1168" stroke="#2A2A2A" stroke-width="2"/>- <rect x="56" y="48" width="20" height="20" rx="4" fill="#2A2A2A"/>- <rect x="88" y="52" width="20" height="12" rx="4" fill="#2A2A2A"/>- <rect x="120" y="52" width="96" height="12" rx="6" fill="#2A2A2A"/>- <path d="M32 128H1168" stroke="#2A2A2A" stroke-width="2"/>- <rect x="252" y="100" width="52" height="10" rx="5" fill="#2A2A2A"/>- <rect x="452" y="100" width="52" height="10" rx="5" fill="#2A2A2A"/>- <rect x="652" y="100" width="52" height="10" rx="5" fill="#2A2A2A"/>- <rect x="852" y="100" width="52" height="10" rx="5" fill="#2A2A2A"/>- <path d="M250 128V664" stroke="#2A2A2A" stroke-width="2"/>- <path d="M450 128V664" stroke="#2A2A2A" stroke-width="2"/>- <path d="M650 128V664" stroke="#2A2A2A" stroke-width="2"/>- <path d="M850 128V664" stroke="#2A2A2A" stroke-width="2"/>- <path d="M1050 128V664" stroke="#2A2A2A" stroke-width="2"/>- <rect x="60" y="128" width="1" height="536" fill="#2A2A2A"/>- <rect x="250" y="150" width="800" height="6" rx="3" fill="#A78BFA"/>- <rect x="70" y="150" width="6" height="6" rx="1" fill="#A78BFA"/>- <rect x="271" y="161" width="783" height="6" rx="3" fill="#818CF8"/>- <rect x="70" y="161" width="6" height="6" rx="1" fill="#818CF8"/>- <rect x="280" y="172" width="774" height="6" rx="3" fill="#FB923C"/>- <rect x="70" y="172" width="6" height="6" rx="1" fill="#FB923C"/>- <rect x="284" y="183" width="750" height="6" rx="3" fill="#A3E635"/>- <rect x="70" y="183" width="6" height="6" rx="1" fill="#A3E635"/>- <rect x="292" y="194" width="727" height="6" rx="3" fill="#2DD4BF"/>- <rect x="70" y="194" width="6" height="6" rx="1" fill="#2DD4BF"/>- <rect x="303" y="205" width="707" height="6" rx="3" fill="#F9A8D4"/>- <rect x="70" y="205" width="6" height="6" rx="1" fill="#F9A8D4"/>- <rect x="328" y="216" width="686" height="6" rx="3" fill="#FBBF24"/>- <rect x="70" y="216" width="6" height="6" rx="1" fill="#FBBF24"/>- <rect x="343" y="227" width="656" height="6" rx="3" fill="#F472B6"/>- <rect x="70" y="227" width="6" height="6" rx="1" fill="#F472B6"/>- <rect x="350" y="238" width="644" height="6" rx="3" fill="#F87171"/>- <rect x="70" y="238" width="6" height="6" rx="1" fill="#F87171"/>- <rect x="374" y="249" width="615" height="6" rx="3" fill="#A78BFA"/>- <rect x="70" y="249" width="6" height="6" rx="1" fill="#A78BFA"/>- <rect x="382" y="260" width="602" height="6" rx="3" fill="#818CF8"/>- <rect x="70" y="260" width="6" height="6" rx="1" fill="#818CF8"/>- <rect x="401" y="271" width="569" height="6" rx="3" fill="#FB923C"/>- <rect x="70" y="271" width="6" height="6" rx="1" fill="#FB923C"/>- <rect x="408" y="282" width="537" height="6" rx="3" fill="#A3E635"/>- <rect x="70" y="282" width="6" height="6" rx="1" fill="#A3E635"/>- <rect x="431" y="293" width="513" height="6" rx="3" fill="#2DD4BF"/>- <rect x="70" y="293" width="6" height="6" rx="1" fill="#2DD4BF"/>- <rect x="443" y="304" width="502" height="6" rx="3" fill="#F9A8D4"/>- <rect x="70" y="304" width="6" height="6" rx="1" fill="#F9A8D4"/>- <rect x="446" y="315" width="469" height="6" rx="3" fill="#FBBF24"/>- <rect x="70" y="315" width="6" height="6" rx="1" fill="#FBBF24"/>- <rect x="454" y="326" width="443" height="6" rx="3" fill="#F472B6"/>- <rect x="70" y="326" width="6" height="6" rx="1" fill="#F472B6"/>- <rect x="462" y="337" width="413" height="6" rx="3" fill="#F87171"/>- <rect x="70" y="337" width="6" height="6" rx="1" fill="#F87171"/>- <rect x="478" y="348" width="398" height="6" rx="3" fill="#A78BFA"/>- <rect x="70" y="348" width="6" height="6" rx="1" fill="#A78BFA"/>- <rect x="485" y="359" width="371" height="6" rx="3" fill="#818CF8"/>- <rect x="70" y="359" width="6" height="6" rx="1" fill="#818CF8"/>- <rect x="488" y="370" width="357" height="6" rx="3" fill="#FB923C"/>- <rect x="70" y="370" width="6" height="6" rx="1" fill="#FB923C"/>- <rect x="504" y="381" width="327" height="6" rx="3" fill="#A3E635"/>- <rect x="70" y="381" width="6" height="6" rx="1" fill="#A3E635"/>- <rect x="520" y="392" width="312" height="6" rx="3" fill="#2DD4BF"/>- <rect x="70" y="392" width="6" height="6" rx="1" fill="#2DD4BF"/>- <rect x="544" y="403" width="298" height="6" rx="3" fill="#F9A8D4"/>- <rect x="70" y="403" width="6" height="6" rx="1" fill="#F9A8D4"/>- <rect x="547" y="414" width="283" height="6" rx="3" fill="#FBBF24"/>- <rect x="70" y="414" width="6" height="6" rx="1" fill="#FBBF24"/>- <rect x="560" y="425" width="274" height="6" rx="3" fill="#F472B6"/>- <rect x="70" y="425" width="6" height="6" rx="1" fill="#F472B6"/>- <rect x="566" y="436" width="256" height="6" rx="3" fill="#F87171"/>- <rect x="70" y="436" width="6" height="6" rx="1" fill="#F87171"/>- <rect x="582" y="447" width="245" height="6" rx="3" fill="#A78BFA"/>- <rect x="70" y="447" width="6" height="6" rx="1" fill="#A78BFA"/>- <rect x="592" y="458" width="214" height="6" rx="3" fill="#818CF8"/>- <rect x="70" y="458" width="6" height="6" rx="1" fill="#818CF8"/>- <rect x="618" y="469" width="188" height="6" rx="3" fill="#FB923C"/>- <rect x="70" y="469" width="6" height="6" rx="1" fill="#FB923C"/>- <rect x="636" y="480" width="165" height="6" rx="3" fill="#A3E635"/>- <rect x="70" y="480" width="6" height="6" rx="1" fill="#A3E635"/>- <rect x="642" y="491" width="156" height="6" rx="3" fill="#2DD4BF"/>- <rect x="70" y="491" width="6" height="6" rx="1" fill="#2DD4BF"/>- <rect x="644" y="502" width="125" height="6" rx="3" fill="#F9A8D4"/>- <rect x="70" y="502" width="6" height="6" rx="1" fill="#F9A8D4"/>- <rect x="663" y="513" width="92" height="6" rx="3" fill="#FBBF24"/>- <rect x="70" y="513" width="6" height="6" rx="1" fill="#FBBF24"/>- <rect x="665" y="524" width="67" height="6" rx="3" fill="#F472B6"/>- <rect x="70" y="524" width="6" height="6" rx="1" fill="#F472B6"/>- <rect x="679" y="535" width="40" height="6" rx="3" fill="#F87171"/>- <rect x="70" y="535" width="6" height="6" rx="1" fill="#F87171"/>- <rect x="689" y="546" width="28" height="6" rx="3" fill="#A78BFA"/>- <rect x="70" y="546" width="6" height="6" rx="1" fill="#A78BFA"/>- <rect x="693" y="557" width="28" height="6" rx="3" fill="#818CF8"/>- <rect x="70" y="557" width="6" height="6" rx="1" fill="#818CF8"/>- <rect x="712" y="568" width="28" height="6" rx="3" fill="#FB923C"/>- <rect x="70" y="568" width="6" height="6" rx="1" fill="#FB923C"/>- <rect x="732" y="579" width="28" height="6" rx="3" fill="#A3E635"/>- <rect x="70" y="579" width="6" height="6" rx="1" fill="#A3E635"/>- <rect x="753" y="590" width="28" height="6" rx="3" fill="#2DD4BF"/>- <rect x="70" y="590" width="6" height="6" rx="1" fill="#2DD4BF"/>- <rect x="763" y="601" width="28" height="6" rx="3" fill="#F9A8D4"/>- <rect x="70" y="601" width="6" height="6" rx="1" fill="#F9A8D4"/>- <rect x="787" y="612" width="28" height="6" rx="3" fill="#FBBF24"/>- <rect x="70" y="612" width="6" height="6" rx="1" fill="#FBBF24"/>- <rect x="799" y="623" width="28" height="6" rx="3" fill="#F472B6"/>- <rect x="70" y="623" width="6" height="6" rx="1" fill="#F472B6"/>- <rect x="822" y="634" width="28" height="6" rx="3" fill="#F87171"/>- <rect x="70" y="634" width="6" height="6" rx="1" fill="#F87171"/>- <rect x="839" y="645" width="28" height="6" rx="3" fill="#A78BFA"/>- <rect x="70" y="645" width="6" height="6" rx="1" fill="#A78BFA"/>-</svg>diff --git a/web/src/features/feature-previews/assets/compact-timeline-light.svg b/web/src/features/feature-previews/assets/compact-timeline-light.svgdeleted file mode 100644index 7a06b86e25..0000000000--- a/web/src/features/feature-previews/assets/compact-timeline-light.svg+++ /dev/null@@ -1,112 +0,0 @@-<svg width="1200" height="700" viewBox="0 0 1200 700" fill="none" xmlns="http://www.w3.org/2000/svg">- <rect width="1200" height="700" fill="#F8FAFC"/>- <rect x="32" y="28" width="1136" height="644" rx="18" fill="#FFFFFF" stroke="#E2E8F0" stroke-width="2"/>- <rect x="32" y="28" width="1136" height="60" rx="18" fill="#F8FAFC"/>- <path d="M32 88H1168" stroke="#E2E8F0" stroke-width="2"/>- <rect x="56" y="48" width="20" height="20" rx="4" fill="#E2E8F0"/>- <rect x="88" y="52" width="20" height="12" rx="4" fill="#E2E8F0"/>- <rect x="120" y="52" width="96" height="12" rx="6" fill="#E2E8F0"/>- <path d="M32 128H1168" stroke="#E2E8F0" stroke-width="2"/>- <rect x="252" y="100" width="52" height="10" rx="5" fill="#E2E8F0"/>- <rect x="452" y="100" width="52" height="10" rx="5" fill="#E2E8F0"/>- <rect x="652" y="100" width="52" height="10" rx="5" fill="#E2E8F0"/>- <rect x="852" y="100" width="52" height="10" rx="5" fill="#E2E8F0"/>- <path d="M250 128V664" stroke="#E2E8F0" stroke-width="2"/>- <path d="M450 128V664" stroke="#E2E8F0" stroke-width="2"/>- <path d="M650 128V664" stroke="#E2E8F0" stroke-width="2"/>- <path d="M850 128V664" stroke="#E2E8F0" stroke-width="2"/>- <path d="M1050 128V664" stroke="#E2E8F0" stroke-width="2"/>- <rect x="60" y="128" width="1" height="536" fill="#E2E8F0"/>- <rect x="250" y="150" width="800" height="6" rx="3" fill="#7C3AED"/>- <rect x="70" y="150" width="6" height="6" rx="1" fill="#7C3AED"/>- <rect x="263" y="161" width="777" height="6" rx="3" fill="#6467F2"/>- <rect x="70" y="161" width="6" height="6" rx="1" fill="#6467F2"/>- <rect x="287" y="172" width="757" height="6" rx="3" fill="#EA580C"/>- <rect x="70" y="172" width="6" height="6" rx="1" fill="#EA580C"/>- <rect x="301" y="183" width="734" height="6" rx="3" fill="#84CC16"/>- <rect x="70" y="183" width="6" height="6" rx="1" fill="#84CC16"/>- <rect x="308" y="194" width="713" height="6" rx="3" fill="#0D9488"/>- <rect x="70" y="194" width="6" height="6" rx="1" fill="#0D9488"/>- <rect x="325" y="205" width="684" height="6" rx="3" fill="#F76EB3"/>- <rect x="70" y="205" width="6" height="6" rx="1" fill="#F76EB3"/>- <rect x="329" y="216" width="668" height="6" rx="3" fill="#D97706"/>- <rect x="70" y="216" width="6" height="6" rx="1" fill="#D97706"/>- <rect x="333" y="227" width="639" height="6" rx="3" fill="#E11D63"/>- <rect x="70" y="227" width="6" height="6" rx="1" fill="#E11D63"/>- <rect x="352" y="238" width="630" height="6" rx="3" fill="#DC2626"/>- <rect x="70" y="238" width="6" height="6" rx="1" fill="#DC2626"/>- <rect x="377" y="249" width="597" height="6" rx="3" fill="#7C3AED"/>- <rect x="70" y="249" width="6" height="6" rx="1" fill="#7C3AED"/>- <rect x="395" y="260" width="573" height="6" rx="3" fill="#6467F2"/>- <rect x="70" y="260" width="6" height="6" rx="1" fill="#6467F2"/>- <rect x="401" y="271" width="565" height="6" rx="3" fill="#EA580C"/>- <rect x="70" y="271" width="6" height="6" rx="1" fill="#EA580C"/>- <rect x="416" y="282" width="555" height="6" rx="3" fill="#84CC16"/>- <rect x="70" y="282" width="6" height="6" rx="1" fill="#84CC16"/>- <rect x="422" y="293" width="541" height="6" rx="3" fill="#0D9488"/>- <rect x="70" y="293" width="6" height="6" rx="1" fill="#0D9488"/>- <rect x="425" y="304" width="521" height="6" rx="3" fill="#F76EB3"/>- <rect x="70" y="304" width="6" height="6" rx="1" fill="#F76EB3"/>- <rect x="437" y="315" width="491" height="6" rx="3" fill="#D97706"/>- <rect x="70" y="315" width="6" height="6" rx="1" fill="#D97706"/>- <rect x="452" y="326" width="466" height="6" rx="3" fill="#E11D63"/>- <rect x="70" y="326" width="6" height="6" rx="1" fill="#E11D63"/>- <rect x="466" y="337" width="441" height="6" rx="3" fill="#DC2626"/>- <rect x="70" y="337" width="6" height="6" rx="1" fill="#DC2626"/>- <rect x="479" y="348" width="426" height="6" rx="3" fill="#7C3AED"/>- <rect x="70" y="348" width="6" height="6" rx="1" fill="#7C3AED"/>- <rect x="505" y="359" width="392" height="6" rx="3" fill="#6467F2"/>- <rect x="70" y="359" width="6" height="6" rx="1" fill="#6467F2"/>- <rect x="527" y="370" width="365" height="6" rx="3" fill="#EA580C"/>- <rect x="70" y="370" width="6" height="6" rx="1" fill="#EA580C"/>- <rect x="537" y="381" width="351" height="6" rx="3" fill="#84CC16"/>- <rect x="70" y="381" width="6" height="6" rx="1" fill="#84CC16"/>- <rect x="545" y="392" width="342" height="6" rx="3" fill="#0D9488"/>- <rect x="70" y="392" width="6" height="6" rx="1" fill="#0D9488"/>- <rect x="566" y="403" width="323" height="6" rx="3" fill="#F76EB3"/>- <rect x="70" y="403" width="6" height="6" rx="1" fill="#F76EB3"/>- <rect x="588" y="414" width="305" height="6" rx="3" fill="#D97706"/>- <rect x="70" y="414" width="6" height="6" rx="1" fill="#D97706"/>- <rect x="613" y="425" width="275" height="6" rx="3" fill="#E11D63"/>- <rect x="70" y="425" width="6" height="6" rx="1" fill="#E11D63"/>- <rect x="615" y="436" width="262" height="6" rx="3" fill="#DC2626"/>- <rect x="70" y="436" width="6" height="6" rx="1" fill="#DC2626"/>- <rect x="639" y="447" width="241" height="6" rx="3" fill="#7C3AED"/>- <rect x="70" y="447" width="6" height="6" rx="1" fill="#7C3AED"/>- <rect x="665" y="458" width="223" height="6" rx="3" fill="#6467F2"/>- <rect x="70" y="458" width="6" height="6" rx="1" fill="#6467F2"/>- <rect x="668" y="469" width="199" height="6" rx="3" fill="#EA580C"/>- <rect x="70" y="469" width="6" height="6" rx="1" fill="#EA580C"/>- <rect x="689" y="480" width="184" height="6" rx="3" fill="#84CC16"/>- <rect x="70" y="480" width="6" height="6" rx="1" fill="#84CC16"/>- <rect x="693" y="491" width="167" height="6" rx="3" fill="#0D9488"/>- <rect x="70" y="491" width="6" height="6" rx="1" fill="#0D9488"/>- <rect x="718" y="502" width="139" height="6" rx="3" fill="#F76EB3"/>- <rect x="70" y="502" width="6" height="6" rx="1" fill="#F76EB3"/>- <rect x="723" y="513" width="125" height="6" rx="3" fill="#D97706"/>- <rect x="70" y="513" width="6" height="6" rx="1" fill="#D97706"/>- <rect x="727" y="524" width="115" height="6" rx="3" fill="#E11D63"/>- <rect x="70" y="524" width="6" height="6" rx="1" fill="#E11D63"/>- <rect x="749" y="535" width="103" height="6" rx="3" fill="#DC2626"/>- <rect x="70" y="535" width="6" height="6" rx="1" fill="#DC2626"/>- <rect x="764" y="546" width="83" height="6" rx="3" fill="#7C3AED"/>- <rect x="70" y="546" width="6" height="6" rx="1" fill="#7C3AED"/>- <rect x="771" y="557" width="56" height="6" rx="3" fill="#6467F2"/>- <rect x="70" y="557" width="6" height="6" rx="1" fill="#6467F2"/>- <rect x="776" y="568" width="31" height="6" rx="3" fill="#EA580C"/>- <rect x="70" y="568" width="6" height="6" rx="1" fill="#EA580C"/>- <rect x="781" y="579" width="28" height="6" rx="3" fill="#84CC16"/>- <rect x="70" y="579" width="6" height="6" rx="1" fill="#84CC16"/>- <rect x="788" y="590" width="28" height="6" rx="3" fill="#0D9488"/>- <rect x="70" y="590" width="6" height="6" rx="1" fill="#0D9488"/>- <rect x="813" y="601" width="28" height="6" rx="3" fill="#F76EB3"/>- <rect x="70" y="601" width="6" height="6" rx="1" fill="#F76EB3"/>- <rect x="822" y="612" width="28" height="6" rx="3" fill="#D97706"/>- <rect x="70" y="612" width="6" height="6" rx="1" fill="#D97706"/>- <rect x="829" y="623" width="28" height="6" rx="3" fill="#E11D63"/>- <rect x="70" y="623" width="6" height="6" rx="1" fill="#E11D63"/>- <rect x="852" y="634" width="28" height="6" rx="3" fill="#DC2626"/>- <rect x="70" y="634" width="6" height="6" rx="1" fill="#DC2626"/>- <rect x="856" y="645" width="28" height="6" rx="3" fill="#7C3AED"/>- <rect x="70" y="645" width="6" height="6" rx="1" fill="#7C3AED"/>-</svg>diff --git a/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx b/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsxindex e7c1f4e3c7..3dbcf7cf43 100644--- a/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx+++ b/web/src/features/feature-previews/components/ControlledFeaturePreviewModal.tsx@@ -62,19 +62,6 @@ export function ControlledFeaturePreviewModal({onToggle: onToggle("modernSession"),isToggling: setFeaturePreviewEnabled.isPending,},- compactTimeline: {- enabled:- authSession.data?.user?.featureFlags.compactTimeline === true ||- authSession.data?.environment.enableExperimentalFeatures === true,- disabled:- authSession.data?.environment.enableExperimentalFeatures === true,- warningReason:- authSession.data?.environment.enableExperimentalFeatures === true- ? "This preview is enabled by LANGFUSE_ENABLE_EXPERIMENTAL_FEATURES, so a per-user opt-out does not disable it."- : undefined,- onToggle: onToggle("compactTimeline"),- isToggling: setFeaturePreviewEnabled.isPending,- },};return (diff --git a/web/src/features/feature-previews/components/FeaturePreviewModal.tsx b/web/src/features/feature-previews/components/FeaturePreviewModal.tsxindex 8a3945dfb2..a7b56de30f 100644--- a/web/src/features/feature-previews/components/FeaturePreviewModal.tsx+++ b/web/src/features/feature-previews/components/FeaturePreviewModal.tsx@@ -17,8 +17,6 @@ import {type FeaturePreviewFlag,} from "@/src/features/feature-flags/available-flags";-import compactTimelineDarkIllustration from "../assets/compact-timeline-dark.svg";-import compactTimelineLightIllustration from "../assets/compact-timeline-light.svg";import modernSessionDarkIllustration from "../assets/modern-session-dark.svg";import modernSessionLightIllustration from "../assets/modern-session-light.svg";@@ -68,19 +66,6 @@ const PREVIEW_REGISTRY: PreviewRegistryItem[] = [alt: "Compact Session View showing a trace minimap beside a continuous session conversation feed.",},},- {- flag: "compactTimeline",- description:- "See a whole trace at once β every observation a single dense line, coloured by type β then zoom and pan it like a map.",- details:- "The Compact Timeline replaces the trace panel's Timeline view. It fits the entire trace into the space available on both axes instead of scrolling: rows shrink to a single-pixel line, and colour carries the observation type where there is no room for a name. Scroll to pan, pinch to zoom both time and rows together, and double-click an observation to fly to it at a readable size β at which point the rows grow their names back and the tree gutter returns. Hovering the left edge peeks the names without moving the bars.",- feedbackUrl: "https://github.com/orgs/langfuse/discussions",- illustration: {- light: compactTimelineLightIllustration,- dark: compactTimelineDarkIllustration,- alt: "A whole trace as dense coloured lines, one per observation, cascading across a time axis.",- },- },];const FEATURE_PREVIEW_MODAL_TITLE = "Feature Preview";diff --git a/web/src/features/traces/components/Trace.tsx b/web/src/features/traces/components/Trace.tsxindex 838cf14aab..abc20ba9e3 100644--- a/web/src/features/traces/components/Trace.tsx+++ b/web/src/features/traces/components/Trace.tsx@@ -24,7 +24,7 @@ import { TracePanelNavigation } from "@/src/features/traces/components/TracePaneimport { TracePanelDetail } from "@/src/features/traces/components/TracePanelDetail";import { TracePanelNavigationLayoutDesktop } from "@/src/features/traces/components/TracePanelNavigationLayoutDesktop/TracePanelNavigationLayoutDesktop";import { TraceTree } from "@/src/features/traces/components/TraceTree";-import { TraceTimeline } from "@/src/features/traces/components/TraceTimeline/TraceTimeline";+import { TraceTimelineCompact } from "@/src/features/traces/components/TraceTimelineDense/TraceTimelineCompact";import { useIsMobile } from "@/src/hooks/use-mobile";import { useTraceComments } from "@/src/features/traces/hooks/useTraceComments";import { TraceGraphView } from "@/src/features/traces/components/TraceGraphView/TraceGraphView";@@ -252,7 +252,7 @@ function MobileTraceContent({ shouldShowGraph }: { shouldShowGraph: boolean }) {<TraceLayoutMobileshowGraph={shouldShowGraph}tree={<TraceTree />}- timeline={<TraceTimeline />}+ timeline={<TraceTimelineCompact />}graph={shouldShowGraph ? <TraceGraphView /> : null}info={<TracePanelDetail />}/>diff --git a/web/src/features/traces/components/TracePanelNavigation.tsx b/web/src/features/traces/components/TracePanelNavigation.tsxindex 7ad3bc13cd..c9edf49f31 100644--- a/web/src/features/traces/components/TracePanelNavigation.tsx+++ b/web/src/features/traces/components/TracePanelNavigation.tsx@@ -21,26 +21,13 @@ import { StringParam, useQueryParam } from "use-query-params";import { useSearch } from "@/src/features/traces/contexts/SearchContext";import { TraceTree } from "./TraceTree";import { TraceSearchList } from "./TraceSearchList";-import { TraceTimeline } from "./TraceTimeline/TraceTimeline";import { TraceTimelineCompact } from "./TraceTimelineDense/TraceTimelineCompact";import { useMemo } from "react";-import useIsFeatureEnabled from "@/src/features/feature-flags/hooks/useIsFeatureEnabled";-import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";export function TracePanelNavigation() {const { searchQuery } = useSearch();- const { trace } = useTraceData();const [viewMode] = useQueryParam("view", StringParam);- // The Compact Timeline feature preview changes what the Timeline view IS,- // rather than adding a third mode for the user to reason about. On by default- // for the Langfuse team (see receivesFeaturePreviewsByDefault), opt-in for- // everyone else. `enableForAdmins: false` so a self-hosted admin does not get- // it silently β the preview toggle is the way in.- const isCompactTimelineEnabled = useIsFeatureEnabled("compactTimeline", {- enableForAdmins: false,- projectId: trace.projectId,- });const hasQuery = searchQuery.trim().length > 0;const isTimelineView = viewMode === "timeline";@@ -51,14 +38,10 @@ export function TracePanelNavigation() {return <TraceSearchList />;}if (isTimelineView) {- return isCompactTimelineEnabled ? (- <TraceTimelineCompact />- ) : (- <TraceTimeline />- );+ return <TraceTimelineCompact />;}return <TraceTree />;- }, [hasQuery, isTimelineView, isCompactTimelineEnabled]);+ }, [hasQuery, isTimelineView]);return content;}diff --git a/web/src/features/traces/components/TraceTimeline/TimelineBar.stories.tsx b/web/src/features/traces/components/TraceTimeline/TimelineBar.stories.tsxdeleted file mode 100644index 2b64455e9a..0000000000--- a/web/src/features/traces/components/TraceTimeline/TimelineBar.stories.tsx+++ /dev/null@@ -1,541 +0,0 @@-import { expect, userEvent, waitFor } from "storybook/test";-import preview from "../../../../../.storybook/preview";-import { TimelineBar } from "./TimelineBar";-import {- MAX_SCORE_GROUPS,- SCORE_GROUP_GAP_PX,- overflowButtonWidth,- scoreBadgesWidth,-} from "../../fns/timeline/metricCluster";-import {- createTextMeasurer,- createTextMeasurerFrom,-} from "../../fns/timeline/textMeasurer";-import { resolveDensity } from "../../fns/timeline/density";-import {- makeRow,- makeTreeNode,- cost,- score,-} from "./__tests__/timeline.fixtures";--const meta = preview.meta({- component: TimelineBar,- args: {- row: makeRow(),- laneWidth: 640,- measurer: createTextMeasurer(),- // The same density layout() positions with β the cluster's gap and inset- // come from it, so a story that omitted it would measure a different bar.- density: resolveDensity({ pointer: "fine" }),- isSelected: false,- showDuration: true,- showCostTokens: false,- showScores: false,- showComments: false,- colorCodeMetrics: false,- },- // The bar positions itself absolutely on the time axis; host it in a- // row-height relative track so its left offset renders in context.- decorators: [- (Story) => (- <div className="bg-background relative h-[26px] w-[640px] rounded border">- <Story />- </div>- ),- ],-});--export const Default = meta.story({});--export const Selected = meta.story({- args: { isSelected: true },-});--export const ZeroDuration = meta.story({- args: {- row: makeRow({- node: makeTreeNode({- endTime: new Date("2024-01-01T00:00:00.000Z"),- latency: 0,- }),- width: 4,- durationMs: 0,- label: "0.00s",- labelX: 70,- }),- },-});--export const Streaming = meta.story({- args: {- row: makeRow({ width: 260, firstTokenX: 150, labelX: 326 }),- },-});--/** No room on either side of the bar, so nothing in the cluster fits. */-export const LabelHidden = meta.story({- args: {- row: makeRow({ x: 636, width: 4, labelPlacement: "hidden" }),- },-});--/**- * An in-flight span has no duration to label, but it can still have a comment,- * a cost or a score β and room in the lane to show them.- */-export const InFlightWithComments = meta.story({- name: "(Test) In Flight Span Keeps Its Icons",- args: {- showComments: true,- commentCount: 2,- row: makeRow({- node: makeTreeNode({ endTime: null, latency: undefined }),- width: 40,- durationMs: null,- label: "",- labelWidth: 0,- labelPlacement: "hidden",- }),- },- play: async ({ canvasElement }) => {- // `hidden` is layout()'s verdict on the duration LABEL. Reading it as a- // verdict on the whole cluster hid every icon on every in-flight span.- await waitFor(() =>- expect(canvasElement.querySelector("svg")).not.toBeNull(),- );- await expect(canvasElement.textContent).toContain("2");- },-});--/**- * A leftover budget that fits either the comment icon or the score badges, but- * not both. They are charged to one running budget, so the cluster still ends up- * narrower than the space it was given.- */-export const CrowdedCluster = meta.story({- name: "(Test) Crowded Cluster Never Clips",- args: {- showComments: true,- showScores: true,- commentCount: 3,- scores: [score("quality", 0.92), score("helpfulness", 0.71)],- // 90px of room after the bar: enough for the duration and then EITHER the- // comment icon (22px) or the score badges (48px), never both.- row: makeRow({ x: 60, width: 484, labelX: 550 }),- },- play: async ({ canvasElement }) => {- const cluster = canvasElement.querySelector<HTMLElement>(- "div[style*='max-width']",- );- if (!cluster) throw new Error("metric cluster not found");-- // Admitting the icon and the badges against the SAME leftover let both in,- // and their combined width was then clipped by the cluster's overflow box β- // the mid-content clipping this whole layout exists to remove. Charged to one- // running budget, the badges are dropped rather than half-drawn.- await expect(cluster.textContent).toContain("2.00s");- await expect(cluster.textContent).not.toContain("quality");- await expect(cluster.scrollWidth).toBeLessThanOrEqual(- cluster.clientWidth + 0.5,- );- // What was dropped stays reachable, counts and all: a narrow row used not to- // mention that a comment or a score existed at all.- await expect(cluster.title).toContain("3 comments");- await expect(cluster.title).toContain("2 scores");- },-});--/**- * Two real scores render 100-300px, not the 48px a flat reservation assumed. A- * lane with room for the duration and *almost* room for the badges is where that- * gap used to clip them mid-glyph.- */-export const ScoreBadgesArePricedFromTheirContent = meta.story({- name: "(Test) Score Badges Are Priced From Their Content",- args: {- showScores: true,- scores: [- score("helpfulness-of-the-answer", 0.71),- score("factual-accuracy", 0.92),- ],- row: makeRow({ x: 60, width: 420, labelX: 486 }),- },- play: async ({ canvasElement }) => {- const cluster = canvasElement.querySelector<HTMLElement>(- "div[style*='max-width']",- );- if (!cluster) throw new Error("metric cluster not found");- await expect(cluster.scrollWidth).toBeLessThanOrEqual(- cluster.clientWidth + 0.5,- );- // Either the badges fit whole, or they are not drawn β never half-drawn.- const showsBadges = cluster.textContent?.includes("factual-accuracy");- if (showsBadges) {- await expect(cluster.textContent).toContain("helpfulness");- } else {- await expect(cluster.title).toContain("2 scores");- }- },-});--/**- * A bar hard against the right edge: the duration fits on neither side, but the- * space BEFORE it is wide open. The cluster belongs there, not in the 0px after.- */-/**- * The widest a chip gets: a row that MIXES score levels grows a spelled-out pill- * per chip ("Observation", not a dot), and a value carrying both a comment and- * metadata grows two icons. Under-price any of those and the badges are admitted- * and then clipped β the one direction that must not happen.- */-export const AnnotatedMixedLevelScoresAreNeverClipped = meta.story({- name: "(Test) Annotated Mixed-Level Scores Are Never Clipped",- args: {- showScores: true,- scores: [- score("quality", 0.92, {- level: "observation",- comment: "looks right",- metadata: '{"model":"gpt-5.4"}',- }),- score("quality", 0.71, { level: "trace" }),- ],- row: makeRow({ x: 60, width: 300, labelX: 366 }),- },- play: async ({ canvasElement }) => {- const cluster = canvasElement.querySelector<HTMLElement>(- "div[style*='max-width']",- );- if (!cluster) throw new Error("metric cluster not found");- // Whole or absent, never half-drawn.- await expect(cluster.scrollWidth).toBeLessThanOrEqual(- cluster.clientWidth + 0.5,- );- if (cluster.textContent?.includes("quality")) {- // If it was admitted, everything it brings has to fit: the level pill too.- await expect(cluster.innerText).toMatch(/Observation|Trace/);- } else {- await expect(cluster.title).toContain("2 scores");- }- },-});--/**- * The invariant behind all of the above, asserted directly: what the cluster- * RESERVES for the badges is never less than what they render at.- *- * The two stories above can only catch a mispricing that changes the admit/drop- * decision at their one lane width, so three rounds of under-reservation- * (a flat 48px, a flat level pill, one gap instead of one per child) passed- * them. This one prices the same scores the bar prices, measures the DOM the- * badges actually produced, and compares the two numbers.- */-/**- * A measurer seeded from what the DOM is ACTUALLY setting the chips in, the way- * the app seeds one from a tick-label probe. Pricing text against a font nothing- * renders in would make a band assertion pass for the wrong reason.- */-const measurerFor = (element: HTMLElement) => {- const style = getComputedStyle(element);- return createTextMeasurerFrom(- document.createElement("canvas").getContext("2d"),- `${style.fontSize} ${style.fontFamily}`,- );-};--// Every width-bearing feature at once: two levels in one group (two pills), two-// values under one name (comma + separator), a value carrying BOTH a comment and-// metadata (two icons), and a name at the truncation limit.-const PRICED_SCORES = [- score("quality", 0.92, {- level: "observation",- comment: "looks right",- metadata: '{"model":"gpt-5.4"}',- }),- score("quality", 0.71, { level: "trace" }),- score("helpfulness-of-the-answer", 0.68, { level: "trace" }),-];--export const ScorePricingNeverUnderReserves = meta.story({- name: "(Test) Score Pricing Never Under-Reserves",- args: {- showScores: true,- scores: PRICED_SCORES,- laneWidth: 900,- row: makeRow({ x: 0, width: 120, labelX: 126 }),- },- play: async ({ canvasElement }) => {- const rendered = await waitFor(() => {- const el = canvasElement.querySelector<HTMLElement>(- "[data-testid='timeline-bar-scores']",- );- if (!el) throw new Error("the badges were not admitted at all");- return el;- });- const priced = scoreBadgesWidth(- PRICED_SCORES,- measurerFor(rendered),- MAX_SCORE_GROUPS,- );- // Under a clipping ancestor the box would report the SMALLER of natural and- // available, which would make any under-price look safe. Compare against a- // width that is actually the badges' own.- await expect(rendered.scrollWidth).toBeLessThanOrEqual(- rendered.clientWidth,- );- const actual = rendered.getBoundingClientRect().width;-- // Never below: the cluster's overflow box cuts whatever it over-admits.- await expect(priced).toBeGreaterThanOrEqual(actual);- // And within a few px above, which is what makes the line above bite: with- // loose slack anywhere in the sum, a whole missing term still "passes". The- // budget here is 2 chips' measurement margin plus the icons' rounding.- await expect(priced - actual).toBeLessThan(12);- },-});--// Thirteen distinct names, all the same shape, so the three admitted chips are-// interchangeable and the only variable left is the "+10" button. Categorical, so-// every chip is measured exactly and the band below is tight enough to be about-// the button rather than about the slack in three numeric values.-const MANY_SCORES = Array.from({ length: 13 }, (_, index) =>- score(`score-${String.fromCharCode(97 + index)}`, 0, {- stringValue: "good",- }),-);--/**- * The same invariant with the overflow button in play. A flat reservation for- * "+N" was fine until a node carried ten hidden groups and the button grew a- * second digit β which the cluster then clipped, having priced one.- */-export const OverflowButtonIsPricedFromItsDigits = meta.story({- name: "(Test) Overflow Button Is Priced From Its Digits",- args: {- showScores: true,- scores: MANY_SCORES,- row: makeRow({ x: 0, width: 120, labelX: 126 }),- },- play: async ({ canvasElement }) => {- const rendered = await waitFor(() => {- const el = canvasElement.querySelector<HTMLElement>(- "[data-testid='timeline-bar-scores']",- );- if (!el) throw new Error("the badges were not admitted at all");- return el;- });- // Ten hidden groups, so the button is two digits wide β the case a flat- // reservation got wrong.- await expect(rendered.textContent).toContain("+10");- await expect(rendered.scrollWidth).toBeLessThanOrEqual(- rendered.clientWidth,- );- const priced = scoreBadgesWidth(- MANY_SCORES,- measurerFor(rendered),- MAX_SCORE_GROUPS,- );- const actual = rendered.getBoundingClientRect().width;- await expect(priced).toBeGreaterThanOrEqual(actual);-- // And the button against ITS own box, which is the sharp version: a- // cluster-wide band cannot isolate this term, because pricing deliberately- // charges the WIDEST groups while the DOM renders the alphabetically first- // ones, and that difference is bigger than a digit.- const button = rendered.querySelector<HTMLElement>("button");- if (!button) throw new Error("no overflow button");- const charged =- overflowButtonWidth(10, measurerFor(rendered)) - SCORE_GROUP_GAP_PX;- const drawn = button.getBoundingClientRect().width;- await expect(charged).toBeGreaterThanOrEqual(drawn);- // A wider ceiling than the chips get: this term carries an explicit margin,- // because its measurement is the one that moved between font stacks.- await expect(charged - drawn).toBeLessThan(8);- // Bold is what it renders in, so bold is what it must be priced at β the- // regular weight is short, and short is the direction that clips.- const regular = measurerFor(rendered).measure("+10");- await expect(measurerFor(rendered).measureBold("+10")).toBeGreaterThan(- regular,- );- },-});--/**- * A comment count is a badge hanging off the corner of its bubble. It used to- * hang outside the icon's own box, so the cluster's clip cut it β and only ever- * for a 2-digit count, which is why it survived the single-digit stories.- */-export const CommentCountIsNeverClipped = meta.story({- name: "(Test) Comment Count Is Never Clipped",- args: {- showComments: true,- commentCount: 42,- showDuration: false,- // Room to spare, so the icon is certainly drawn and this is about its shape.- row: makeRow({ x: 0, width: 500, labelPlacement: "hidden" }),- },- play: async ({ canvasElement }) => {- const cluster = canvasElement.querySelector<HTMLElement>(- "div[style*='max-width']",- );- if (!cluster) throw new Error("metric cluster not found");- if (!cluster.textContent?.includes("42")) {- // Dropped rather than clipped is the other acceptable outcome, and then- // the row still has to say the comments exist.- await expect(cluster.title).toContain("42 comments");- return;- }- // Admitted: the count has to be whole, inside the icon's box and inside the- // cluster's.- const badge = cluster.querySelector<HTMLElement>(- "[data-testid='comment-count']",- );- if (!badge) throw new Error("no count badge");- const icon = badge.parentElement!.getBoundingClientRect();- await expect(badge.getBoundingClientRect().right).toBeLessThanOrEqual(- icon.right + 0.5,- );- await expect(cluster.scrollWidth).toBeLessThanOrEqual(- cluster.clientWidth + 0.5,- );- },-});--/**- * And the same count against a budget that leaves room for the bubble but not for- * its badge. Whichever way it goes β drawn whole or refused β the cluster must not- * end up holding half a number, which is what a flat "an icon is 22px" produced- * once the badge became part of the icon's footprint.- */-export const CommentCountIsPricedFromItsDigits = meta.story({- name: "(Test) Comment Count Is Priced From Its Digits",- args: {- showComments: true,- commentCount: 42,- showDuration: false,- // 24px of lane left after the bar: a two-digit count needs a little more.- row: makeRow({ x: 0, width: 610, labelPlacement: "hidden" }),- },- play: async ({ canvasElement }) => {- const cluster = canvasElement.querySelector<HTMLElement>(- "div[style*='max-width']",- );- if (cluster) {- // Admitted: whole, or not at all β never a half-drawn number.- await expect(cluster.scrollWidth).toBeLessThanOrEqual(- cluster.clientWidth + 0.5,- );- if (!cluster.textContent?.includes("42")) {- await expect(cluster.title).toContain("42 comments");- }- return;- }- // Refused, which is the correct outcome at this width β and then the bar- // itself has to say the comments exist, since there is no cluster left to.- const bar = canvasElement.querySelector<HTMLElement>("div[title]");- if (!bar) throw new Error("nothing on the row mentions the comments");- await expect(bar.title).toContain("42 comments");- },-});--/**- * "+N" cannot expand in place here. The cluster was measured for three chips, so- * an unbounded expansion inside its clip does not reveal the hidden scores β it- * cuts the ones already on screen.- */-export const ExpandingOverflowCannotClipTheCluster = meta.story({- name: "(Test) Expanding Overflow Cannot Clip The Cluster",- args: {- showScores: true,- scores: MANY_SCORES,- row: makeRow({ x: 0, width: 120, labelX: 126 }),- },- play: async ({ canvasElement }) => {- const cluster = canvasElement.querySelector<HTMLElement>(- "div[style*='max-width']",- );- if (!cluster) throw new Error("metric cluster not found");- const button = canvasElement.querySelector<HTMLElement>(- "button[aria-label*='more score']",- );- if (!button) throw new Error("no overflow button");- const before = cluster.textContent;- await userEvent.click(button);- // Nothing expanded, and nothing was cut.- await expect(cluster.textContent).toBe(before);- await expect(cluster.scrollWidth).toBeLessThanOrEqual(- cluster.clientWidth + 0.5,- );- },-});--/**- * A streaming bar is two phases in one bar, told apart by shade. The frame must- * not paint the ground: a translucent wait over an opaque frame of the same- * colour composites back to that colour, and the split disappears.- */-export const StreamingPhasesReadAsTwoShades = meta.story({- name: "(Test) Streaming Phases Read As Two Shades",- args: {- row: makeRow({ x: 40, width: 400, firstTokenX: 160, labelX: 446 }),- },- play: async ({ canvasElement }) => {- const waiting = canvasElement.querySelector<HTMLElement>(- "div[title='Time to first token']",- );- if (!waiting) throw new Error("no first-token segment");- const completion = waiting.nextElementSibling as HTMLElement | null;- if (!completion) throw new Error("no completion segment");- // Same hue, different shade β and the difference has to survive whatever the- // frame paints behind them.- const frame = waiting.parentElement!;- await expect(getComputedStyle(frame).backgroundColor).toMatch(- /rgba\(0, 0, 0, 0\)|transparent/,- );- await expect(Number(getComputedStyle(waiting).opacity)).toBeLessThan(- Number(getComputedStyle(completion).opacity),- );- },-});--export const HiddenLabelUsesTheRoomierSide = meta.story({- name: "(Test) Hidden Label Uses The Roomier Side",- args: {- showComments: true,- commentCount: 4,- row: makeRow({ x: 600, width: 38, labelPlacement: "hidden" }),- },- play: async ({ canvasElement }) => {- const cluster = canvasElement.querySelector<HTMLElement>(- "div[style*='max-width']",- );- if (!cluster) throw new Error("the cluster went nowhere at all");- const box = cluster.getBoundingClientRect();- const bar = canvasElement- .querySelector<HTMLElement>("div[style*='left: 600px']")- ?.getBoundingClientRect();- if (!bar) throw new Error("no bar");- // Left of the bar, and inside the lane.- await expect(box.right).toBeLessThanOrEqual(bar.left + 0.5);- await expect(box.width).toBeGreaterThan(0);- },-});--export const WithCostAndTokens = meta.story({- args: {- showCostTokens: true,- row: makeRow({- node: makeTreeNode({- totalCost: cost(0.0021),- inputUsage: 320,- outputUsage: 140,- totalUsage: 460,- }),- }),- },-});--export const WithComments = meta.story({- args: { showComments: true, commentCount: 3 },-});diff --git a/web/src/features/traces/components/TraceTimeline/TimelineBar.tsx b/web/src/features/traces/components/TraceTimeline/TimelineBar.tsxdeleted file mode 100644index a1fb1e6363..0000000000--- a/web/src/features/traces/components/TraceTimeline/TimelineBar.tsx+++ /dev/null@@ -1,288 +0,0 @@-/**- * TimelineBar - Renders the gantt bar for a node on the time track.- *- * Pure time-coordinate concern: a colored duration box positioned at the node's- * start offset, followed by a trailing metric label. Identity (badge, name) and- * hierarchy (tree connectors) live in the gutter (TimelineGutterRow) β not here β so- * the bar can sit at its true time position without dragging the tree with it.- *- * Every coordinate arrives already computed from `layout()`, including WHICH SIDE- * of the bar the metric cluster goes on. That decision used to belong to CSS- * flow, which cannot see the lane's width and so pushed the cluster off-screen- * in a narrow lane; the lane no longer scrolls horizontally, so off-screen means- * gone. See fns/timeline/layout.ts.- */--import { type TimelineBarProps } from "./types";-import { cn } from "@/src/utils/tailwind";-import { CommentCountIcon } from "@/src/features/comments/CommentCountIcon";-import { GroupedScoreBadges } from "@/src/components/grouped-score-badge";-import { formatIntervalSeconds } from "@/src/utils/dates";-import { usdFormatter } from "@/src/utils/numbers";-import { getSubtreeDurationOverflowMs } from "@/src/features/traces/fns/getSubtreeDurationOverflowMs";-import { heatMapTextColor } from "@/src/features/traces/fns/heatMapTextColor";-import { isPresent } from "@langfuse/shared";-import {- CLUSTER_ITEM_GAP_PX,- MAX_SCORE_GROUPS,- commentIconWidth,- createClusterFitter,- scoreBadgesWidth,-} from "../../fns/timeline/metricCluster";--const SUBTREE_DURATION_TITLE =- "Subtree wall-clock duration (first start β last end)";--export function TimelineBar({- row,- laneWidth,- measurer,- isSelected,- isHovered,- showDuration,- showCostTokens,- showScores,- showComments,- colorCodeMetrics,- parentTotalCost,- parentTotalDuration,- commentCount,- scores,- density,-}: TimelineBarProps) {- // Room between the bar and a metric cluster outside it, and the inset of one- // sitting inside: `density`'s own values, threaded in rather than copied. These- // are the exact numbers `placeLabel()` measured the placement with, so a local- // copy would be a silent desync waiting for the first change to density.- const CLUSTER_GAP_PX = density.labelGapPx;- const CLUSTER_INSET_PX = density.labelPaddingPx;- const node = row.node;-- // `layout()` already applies the latency fallback (`hasDuration` covers it), so- // a second one here could only ever run when latency is absent too. Wall-clock- // subtree duration is surfaced only when async descendants outlive this node's- // own span.- const ownDurationMs = row.durationMs ?? undefined;- const subtreeWallClockOverflowMs = showDuration- ? getSubtreeDurationOverflowMs(- ownDurationMs,- node.subtreeWallClockDurationMs,- )- : null;-- // Ring driven by shared row state (not group-hover) so it lights up whether- // the chart bar or the caption is hovered.- const ringClass = isSelected- ? "ring-primary-accent ring-2"- : isHovered- ? "ring-tertiary ring-2"- : "";-- // Which side the metric cluster lands on is layout()'s call, made against the- // measured lane; we only turn it into a position. `hidden` means neither side- // had room, so nothing is drawn rather than something drawn off the lane.- // `hidden` means the DURATION LABEL fitted on neither side β not that neither- // side has room. The cluster's other items are much narrower, so it goes to- // whichever side is actually roomier instead of always falling in with- // `after`, which in a lane like 137px is often the side with nothing left.- const spaceBefore = Math.max(row.x - CLUSTER_GAP_PX, 0);- const spaceAfter = Math.max(- laneWidth - (row.x + row.width + CLUSTER_GAP_PX),- 0,- );- const placement =- row.labelPlacement === "hidden" && spaceBefore > spaceAfter- ? "before"- : row.labelPlacement;-- const clusterStyle =- placement === "before"- ? {- right: `${Math.max(laneWidth - row.x + CLUSTER_GAP_PX, 0)}px`,- maxWidth: `${Math.max(row.x - CLUSTER_GAP_PX, 0)}px`,- }- : placement === "inside"- ? {- left: `${row.x + CLUSTER_INSET_PX}px`,- maxWidth: `${Math.max(row.width - CLUSTER_INSET_PX * 2, 0)}px`,- }- : {- left: `${row.x + row.width + CLUSTER_GAP_PX}px`,- maxWidth: `${Math.max(- laneWidth - (row.x + row.width + CLUSTER_GAP_PX),- 0,- )}px`,- };-- // layout() measures the duration; the optional metrics are this component's- // own content, so it fits them here with the SAME measurer rather than- // letting them clip mid-glyph at the lane edge. Highest priority first: a- // duration always beats a cost you cannot finish reading.- const budgetPx = Number.parseFloat(clusterStyle.maxWidth);- const fitsWidth = createClusterFitter(budgetPx, CLUSTER_ITEM_GAP_PX);- const fitsCluster = (text: string) => fitsWidth(measurer.measure(text));-- // The layout measured this exact string, which is why the bar renders it- // rather than formatting the duration a second time: two formatters disagree- // above an hour, and the side layout() chose was chosen for the shorter one.- const durationText = showDuration && row.label ? row.label : null;- const subtreeText =- isPresent(ownDurationMs) && subtreeWallClockOverflowMs != null- ? `β ${formatIntervalSeconds(subtreeWallClockOverflowMs / 1000)}`- : null;- const costText =- showCostTokens && node.totalCost- ? usdFormatter(node.totalCost.toNumber())- : null;-- // `hidden` is layout()'s verdict on the DURATION LABEL β neither side of the- // bar had room for it, or there is no duration to show yet. It is not a verdict- // on the icons, which are much narrower and may well fit.- const showDurationText =- durationText != null &&- row.labelPlacement !== "hidden" &&- fitsCluster(durationText);- const showSubtreeText = subtreeText != null && fitsCluster(subtreeText);- const showCostText = costText != null && fitsCluster(costText);- // Both are charged through the SAME running budget. Checking each against one- // leftover let a comment icon and score badges both be admitted on the same- // 48px, and their combined width then clipped the badges inside the cluster's- // overflow box.- const showCommentIcon =- showComments &&- Boolean(commentCount) &&- fitsWidth(commentIconWidth(commentCount!, measurer));- const showScoreBadges =- showScores &&- Boolean(scores?.length) &&- fitsWidth(scoreBadgesWidth(scores!, measurer, MAX_SCORE_GROUPS));-- // Everything the row HAS stays reachable on hover when anything had to be- // dropped β the icon and the badges included. They are admitted last, against- // the smallest remaining budget, so they are the likeliest to go; without this- // a narrow row simply did not mention that a comment or a score existed.- const plural = (count: number, noun: string) =>- `${count} ${noun}${count === 1 ? "" : "s"}`;- const commentText =- showComments && commentCount ? plural(commentCount, "comment") : null;- const scoreText =- showScores && scores?.length ? plural(scores.length, "score") : null;- const droppedSomething =- (durationText != null && !showDurationText) ||- (subtreeText != null && !showSubtreeText) ||- (costText != null && !showCostText) ||- (commentText != null && !showCommentIcon) ||- (scoreText != null && !showScoreBadges);- const clusterTitle = droppedSomething- ? [durationText, subtreeText, costText, commentText, scoreText]- .filter(Boolean)- .join(" ")- : undefined;-- // Draw the cluster when it has something in it. Gating it on the duration- // label's placement hid the comment icon, the cost and the scores of every- // in-flight span β which never has a duration label β however much room the- // lane had for them.- const cluster =- !showDurationText &&- !showSubtreeText &&- !showCostText &&- !showCommentIcon &&- !showScoreBadges ? null : (- <div- className="text-muted-foreground absolute top-1/2 flex -translate-y-1/2 items-center gap-2 overflow-hidden text-xs whitespace-nowrap"- style={clusterStyle}- title={clusterTitle}- >- {showCommentIcon ? <CommentCountIcon count={commentCount!} /> : null}- {showDurationText && (- <span- className={cn(- parentTotalDuration &&- colorCodeMetrics &&- heatMapTextColor({- max: parentTotalDuration,- value: ownDurationMs!,- }),- )}- >- {durationText}- </span>- )}- {showSubtreeText && (- <span title={SUBTREE_DURATION_TITLE}>{subtreeText}</span>- )}- {showCostText && (- <span- className={cn(- parentTotalCost &&- colorCodeMetrics &&- heatMapTextColor({- max: parentTotalCost,- value: node.totalCost!,- }),- )}- >- {costText}- </span>- )}- {showScoreBadges && (- <div className="flex max-h-5 gap-1" data-testid="timeline-bar-scores">- {/* Not expandable here: the cluster's width was measured for exactly- `MAX_SCORE_GROUPS` chips, so expanding in place would clip the- chips already on screen instead of revealing the hidden ones. The- hover preview shows them, and the row's title lists them. */}- <GroupedScoreBadges- scores={scores!}- maxVisible={MAX_SCORE_GROUPS}- expandable={false}- />- </div>- )}- </div>- );-- // Streaming LLMs (first token time) split the bar: waiting segment, then- // completion. firstTokenX is null when the marker falls outside the lane.- const firstTokenWidth =- row.firstTokenX == null- ? null- : Math.min(Math.max(row.firstTokenX - row.x, 0), row.width);-- return (- <>- <div- // When the lane is too narrow for even one item, the cluster is not drawn- // at all β and the title listing what was dropped went with it, so the- // narrowest rows were the ones that never mentioned their own comments or- // scores. The bar is always there, so it carries the fallback.- title={cluster ? undefined : clusterTitle}- className={cn(- "border-border absolute top-1/2 flex h-4 -translate-y-1/2 overflow-hidden rounded-sm border",- // Dashed when in-flight (no measurable duration yet).- row.durationMs == null && "border-dashed",- // A clipped edge loses its rounding, so the bar reads as continuing.- row.clippedLeft && "rounded-l-none",- row.clippedRight && "rounded-r-none",- ringClass,- )}- style={{ left: `${row.x}px`, width: `${row.width}px` }}- >- {/* Two SEGMENTS, and the ground belongs to them rather than to the- frame: a translucent waiting segment over an opaque frame of the same- colour composites straight back to that colour, so the wait and the- completion read identically and only the divider says there was a- split at all. */}- {firstTokenWidth == null ? null : (- <div- className="bg-muted h-full border-r border-gray-400 opacity-60"- style={{ width: `${firstTokenWidth}px` }}- title="Time to first token"- />- )}- <div className="bg-muted h-full flex-1" />- </div>- {cluster}- </>- );-}diff --git a/web/src/features/traces/components/TraceTimeline/TimelineGutterRow.stories.tsx b/web/src/features/traces/components/TraceTimeline/TimelineGutterRow.stories.tsxdeleted file mode 100644index 330552e108..0000000000--- a/web/src/features/traces/components/TraceTimeline/TimelineGutterRow.stories.tsx+++ /dev/null@@ -1,224 +0,0 @@-import { fn } from "storybook/test";-import preview from "../../../../../.storybook/preview";-import { TimelineGutterRow } from "./TimelineGutterRow";-import { prepareTimeline } from "../../fns/timeline/layout";-import { makeRow, makeTreeNode } from "./__tests__/timeline.fixtures";--const ROW_BOX =- "bg-background relative h-[26px] w-[320px] overflow-hidden rounded border";-const PANEL_BOX = "bg-background w-[320px] overflow-hidden rounded border";--// fn() gives Storybook actions; cast to the prop type so meta args and the-// per-story decorators agree (story-level decorators are typed against the-// component props, not the Mock-widened meta args).-const meta = preview.meta({- component: TimelineGutterRow,- args: {- row: makeRow({- depth: 1,- treeLines: [false],- isLastSibling: true,- node: makeTreeNode({ name: "compose-context-window", type: "SPAN" }),- }),- isSelected: false,- onSelect: fn() as () => void,- onHover: fn() as () => void,- onToggleCollapse: fn() as () => void,- hasChildren: false,- isCollapsed: false,- },-});--export const Default = meta.story({- decorators: [- (Story) => (- <div className={ROW_BOX}>- <Story />- </div>- ),- ],-});--export const RootWithChildren = meta.story({- args: {- row: makeRow({- depth: 0,- treeLines: [],- isLastSibling: true,- node: makeTreeNode({ name: "orchestrator-agent", type: "AGENT" }),- }),- hasChildren: true,- },- decorators: [- (Story) => (- <div className={ROW_BOX}>- <Story />- </div>- ),- ],-});--export const NestedWithSiblingBelow = meta.story({- args: {- row: makeRow({- depth: 2,- treeLines: [true, true],- isLastSibling: false,- node: makeTreeNode({ name: "rerank-candidate-passages", type: "SPAN" }),- }),- hasChildren: true,- },- decorators: [- (Story) => (- <div className={ROW_BOX}>- <Story />- </div>- ),- ],-});--export const NestedLastChild = meta.story({- args: {- row: makeRow({- depth: 2,- treeLines: [true, false],- isLastSibling: true,- node: makeTreeNode({ name: "vector-search-shard-3", type: "SPAN" }),- }),- },- decorators: [- (Story) => (- <div className={ROW_BOX}>- <Story />- </div>- ),- ],-});--export const Selected = meta.story({- args: { isSelected: true },- decorators: [- (Story) => (- <div className={ROW_BOX}>- <Story />- </div>- ),- ],-});--export const Collapsed = meta.story({- args: {- row: makeRow({- depth: 1,- treeLines: [false],- isLastSibling: true,- node: makeTreeNode({ name: "retrieve-relevant-documents", type: "SPAN" }),- }),- hasChildren: true,- isCollapsed: true,- },- decorators: [- (Story) => (- <div className={ROW_BOX}>- <Story />- </div>- ),- ],-});--// Design showcase: a stacked mini-tree from the real flattening logic, so the-// connectors connect parentβchild across rows exactly as in the app.-export const TreeShowcase = meta.story({- decorators: [- (Story) => (- <div className={PANEL_BOX}>- <Story />- </div>- ),- ],- render: (args) => {- const t = (ms: number) =>- new Date(Date.parse("2024-01-01T00:00:00.000Z") + ms);- const tree = makeTreeNode({- id: "orch",- name: "orchestrator-agent",- type: "AGENT",- startTime: t(0),- endTime: t(8000),- latency: 8,- children: [- makeTreeNode({- id: "retr",- name: "retrieve-relevant-documents",- type: "SPAN",- startTime: t(200),- endTime: t(6000),- children: [- makeTreeNode({- id: "rerank",- name: "rerank-candidate-passages",- type: "SPAN",- startTime: t(500),- endTime: t(5500),- children: [- makeTreeNode({- id: "compose",- name: "compose-context-window",- type: "SPAN",- startTime: t(1000),- endTime: t(5000),- children: [- makeTreeNode({- id: "llm",- name: "call-large-language-model",- type: "GENERATION",- startTime: t(1200),- endTime: t(4800),- }),- ],- }),- ],- }),- ],- }),- makeTreeNode({- id: "e0",- name: "vector-search-shard-0",- type: "SPAN",- startTime: t(6000),- endTime: t(6900),- }),- makeTreeNode({- id: "e1",- name: "vector-search-shard-1",- type: "SPAN",- startTime: t(6900),- endTime: t(7800),- }),- ],- });-- // The real tree walk, so connectors connect parentβchild across rows- // exactly as in the app. Only depth/treeLines matter here; the gutter takes- // no geometry.- const rows = prepareTimeline([tree]).rows;-- return (- <>- {rows.map((row) => (- <div key={row.node.id} className="h-[26px]">- <TimelineGutterRow- row={row}- isSelected={false}- onSelect={args.onSelect}- onHover={args.onHover}- onToggleCollapse={args.onToggleCollapse}- hasChildren={row.hasChildren}- isCollapsed={false}- />- </div>- ))}- </>- );- },-});diff --git a/web/src/features/traces/components/TraceTimeline/TimelineGutterRow.tsx b/web/src/features/traces/components/TraceTimeline/TimelineGutterRow.tsxdeleted file mode 100644index 35e756aaa2..0000000000--- a/web/src/features/traces/components/TraceTimeline/TimelineGutterRow.tsx+++ /dev/null@@ -1,151 +0,0 @@-/**- * TimelineGutterRow - the left, fixed gutter cell for one waterfall row.- *- * Pure depth coordinate: tree connectors + icon + name. It lives in the gutter- * pane (which never scrolls horizontally), so hover/selection highlighting is- * scoped to this narrow cell β the wide chart never gets a full-width band.- *- * Connectors are absolute lines at computed rail x's. Each parentβchild line is- * two segments (parent draws centerβbottom, child draws topβcenter) meeting at- * the shared row boundary, so the line is continuous at every depth. The rail- * sits a gap to the LEFT of the icon (it never crosses it), and the elbow stops- * at the icon.- */--import { type TimelineGutterRowProps } from "./types";-import { ItemBadge } from "@/src/components/ItemBadge";-import { ChevronRight } from "lucide-react";-import { cn } from "@/src/utils/tailwind";--const INDENT = 14; // px per depth level-const RAIL = 7; // x of a level's vertical rail within its indent step-const ICON_GAP = 6; // gap from a node's rail to its icon--export function TimelineGutterRow({- row,- isSelected,- isHovered,- onSelect,- onHover,- onToggleCollapse,- hasChildren,- isCollapsed,- maxVisualDepth = Infinity,-}: TimelineGutterRowProps) {- const { node, depth, treeLines, isLastSibling } = row;-- // Visual depth: real depth capped to the gutter width (see visual-depth.ts)- // so extremely deep traces keep names readable β rows past the cap render- // flat at the cap level (LFE-10959).- const visualDepth = Math.min(depth, maxVisualDepth);- const ownRailX = visualDepth * INDENT + RAIL;- const parentRailX = (visualDepth - 1) * INDENT + RAIL;- // A capped node's children render at the SAME indent (not one level right),- // so its child spine would dangle next to nothing β suppress it.- const showsChildSpine = hasChildren && !isCollapsed && depth < maxVisualDepth;- const contentLeft = ownRailX + ICON_GAP;-- return (- <div- className={cn(- "relative flex h-full w-full cursor-pointer items-center pr-2",- // Whole-row highlight is driven by shared state (so hovering the chart- // highlights the caption too). Selected uses an accent tint so it stays- // distinct from the neutral bar (bg-muted) β otherwise the bar vanishes- // into the selected row; hover stays neutral.- isSelected ? "bg-primary-accent/10" : isHovered ? "bg-muted" : "",- )}- onClick={onSelect}- onMouseEnter={onHover}- >- {/* Selected accent bar (no layout shift). */}- {isSelected && (- <div className="bg-primary-accent absolute inset-y-0 left-0 w-0.5" />- )}- {/* Ancestor rails: continue through this row for ancestors with a sibling below. */}- {treeLines- .slice(0, Math.max(0, visualDepth - 1))- .map((continues, level) =>- continues ? (- <div- key={level}- className="bg-border-contrast absolute inset-y-0 w-px"- style={{ left: `${level * INDENT + RAIL}px` }}- />- ) : null,- )}-- {visualDepth > 0 && (- <>- {/* This node's vertical off the parent rail: topβcenter (last) or full. */}- <div- className={cn(- "bg-border-contrast absolute top-0 w-px",- isLastSibling ? "h-1/2" : "bottom-0",- )}- style={{ left: `${parentRailX}px` }}- />- {/* Elbow: parent rail β icon, at the row's vertical center. */}- <div- className="bg-border-contrast absolute top-1/2 h-px"- style={{- left: `${parentRailX}px`,- width: `${INDENT + ICON_GAP}px`,- }}- />- </>- )}-- {/* Downward stub to this node's children, on its own rail (left of the icon). */}- {showsChildSpine && (- <div- className="bg-border-contrast absolute top-1/2 bottom-0 w-px"- style={{ left: `${ownRailX}px` }}- />- )}-- {/* Icon + name. The icon is offset to a node's rail; the rail sits a gap- to its left so it never crosses the chip. */}- <div- className="flex min-w-0 flex-1 items-center gap-2"- style={{ paddingLeft: `${contentLeft}px` }}- >- {/* Wrap to keep the badge from flex-shrinking (ItemBadge's className- only reaches the inner icon, not the Badge wrapper). */}- <div className="shrink-0">- <ItemBadge type={node.type} isSmall />- </div>- <span- className={cn(- "min-w-0 flex-1 truncate text-xs font-bold",- isSelected ? "text-foreground" : "dark:text-muted-foreground",- )}- title={node.name}- >- {node.name || `Unnamed ${node.type.toLowerCase()}`}- </span>- </div>-- {/* Expand/collapse caret, pinned right (as in the tree view). */}- {hasChildren && (- <button- type="button"- aria-label={isCollapsed ? "Expand" : "Collapse"}- aria-expanded={!isCollapsed}- onClick={(e) => {- e.stopPropagation();- onToggleCollapse();- }}- className="hover:bg-muted-foreground/10 ml-1 flex h-5 w-5 shrink-0 items-center justify-center rounded"- >- <ChevronRight- className={cn(- "h-4 w-4 transition-transform duration-200",- !isCollapsed && "rotate-90",- )}- />- </button>- )}- </div>- );-}diff --git a/web/src/features/traces/components/TraceTimeline/TimelineRows.tsx b/web/src/features/traces/components/TraceTimeline/TimelineRows.tsxdeleted file mode 100644index 5dab141488..0000000000--- a/web/src/features/traces/components/TraceTimeline/TimelineRows.tsx+++ /dev/null@@ -1,182 +0,0 @@-/**- * Memoized virtual-row shells for the timeline.- *- * These are the render boundary that keeps playback and hover cheap: each- * shell subscribes to its OWN row's playhead-active flag- * (useIsObservationActive β a primitive selector), so a playback boundary- * crossing re-renders only the rows whose glow flipped, never the whole- * virtualized list. Every other prop is a primitive or a reference the parent- * keeps stable (the flattenedItems memo, useCallback handlers, the- * scores-by-node map), so scroll/hover/selection reconciliation bails out here- * for unaffected rows.- */--import { memo } from "react";-import type Decimal from "decimal.js";-import { type ScoreDomain } from "@langfuse/shared";-import { type WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";-import { type TreeNode } from "../../types/treeNode";-import { type TimelineRowNode } from "./types";-import { type TextMeasurer } from "../../fns/timeline/textMeasurer";-import { type Density } from "../../fns/timeline/density";-import { TimelineGutterRow } from "./TimelineGutterRow";-import { TimelineBar } from "./TimelineBar";-import { useIsObservationActive } from "@/src/features/traces/contexts/PlayheadContext";-import { cn } from "@/src/utils/tailwind";--interface RowShellSharedProps {- row: TimelineRowNode;- /** Virtual row offset/extent β primitives so the memo can bail on scroll. */- top: number;- height: number;- isSelected: boolean;- isHovered: boolean;- /** Stable id/node-taking callbacks created once in the parent. */- onSelect: (nodeId: string) => void;- onHover: (node: TreeNode) => void;-}--type GutterRowShellProps = RowShellSharedProps & {- hasChildren: boolean;- isCollapsed: boolean;- /** Indentation cap from the gutter width (see visual-depth.ts). */- maxVisualDepth: number;- onToggleCollapse: (nodeId: string) => void;-};--function TimelineGutterRowShellComponent({- row,- top,- height,- isSelected,- isHovered,- hasChildren,- isCollapsed,- maxVisualDepth,- onSelect,- onHover,- onToggleCollapse,-}: GutterRowShellProps) {- const nodeId = row.node.id;- // Playhead glow: rows "playing" at the current time light UP (accent tint).- const isActive = useIsObservationActive(nodeId);-- return (- <div- style={{- position: "absolute",- top: 0,- left: 0,- width: "100%",- height: `${height}px`,- transform: `translateY(${top}px)`,- }}- className={cn(- "transition-colors duration-150",- isActive && "bg-primary-accent/15",- )}- >- <TimelineGutterRow- row={row}- isSelected={isSelected}- isHovered={isHovered}- onSelect={() => onSelect(nodeId)}- onHover={() => onHover(row.node)}- onToggleCollapse={() => onToggleCollapse(nodeId)}- hasChildren={hasChildren}- isCollapsed={isCollapsed}- maxVisualDepth={maxVisualDepth}- />- </div>- );-}--export const TimelineGutterRowShell = memo(TimelineGutterRowShellComponent);--type ChartRowShellProps = RowShellSharedProps & {- width: number;- showDuration: boolean;- showCostTokens: boolean;- showScores: boolean;- showComments: boolean;- colorCodeMetrics: boolean;- parentTotalCost?: Decimal;- parentTotalDuration?: number;- commentCount: number;- nodeScores: WithStringifiedMetadata<ScoreDomain>[];- measurer: TextMeasurer;- density: Density;-};--function TimelineChartRowShellComponent({- row,- top,- height,- width,- isSelected,- isHovered,- showDuration,- showCostTokens,- showScores,- showComments,- colorCodeMetrics,- parentTotalCost,- parentTotalDuration,- commentCount,- nodeScores,- measurer,- density,- onSelect,- onHover,-}: ChartRowShellProps) {- const nodeId = row.node.id;- const isActive = useIsObservationActive(nodeId);-- return (- <div- style={{- position: "absolute",- top: 0,- left: 0,- width: `${width}px`,- height: `${height}px`,- transform: `translateY(${top}px)`,- }}- className={cn(- "cursor-pointer transition-colors duration-150",- // Selected = accent tint so the neutral bar (bg-muted) stays visible- // against the row; a playhead-active row glows with the same accent;- // hover stays neutral.- isSelected- ? "bg-primary-accent/10"- : isActive- ? "bg-primary-accent/15"- : isHovered- ? "bg-muted"- : "",- )}- onClick={() => onSelect(nodeId)}- onMouseEnter={() => onHover(row.node)}- >- <TimelineBar- row={row}- laneWidth={width}- measurer={measurer}- density={density}- isSelected={isSelected}- isHovered={isHovered}- showDuration={showDuration}- showCostTokens={showCostTokens}- showScores={showScores}- showComments={showComments}- colorCodeMetrics={colorCodeMetrics}- parentTotalCost={parentTotalCost}- parentTotalDuration={parentTotalDuration}- commentCount={commentCount}- scores={nodeScores}- />- </div>- );-}--export const TimelineChartRowShell = memo(TimelineChartRowShellComponent);diff --git a/web/src/features/traces/components/TraceTimeline/TimelineScale.stories.tsx b/web/src/features/traces/components/TraceTimeline/TimelineScale.stories.tsxdeleted file mode 100644index 05a244833e..0000000000--- a/web/src/features/traces/components/TraceTimeline/TimelineScale.stories.tsx+++ /dev/null@@ -1,63 +0,0 @@-import { expect } from "storybook/test";-import preview from "../../../../../.storybook/preview";-import { TimelineScale } from "./TimelineScale";-import { TICK_LABEL_INSET_PX } from "../../fns/timeline/layout";--const meta = preview.meta({- component: TimelineScale,-});--/** Ticks arrive already placed and labelled by layout(); see fns/timeline. */-const ticks = (stepMs: number, count: number, laneWidth: number) =>- Array.from({ length: count }, (_, i) => ({- realMs: i * stepMs,- x: (i / count) * laneWidth,- label:- stepMs >= 1000- ? `${((i * stepMs) / 1000).toFixed(2)}s`- : `${i * stepMs}ms`,- }));--export const Default = meta.story({- args: { ticks: ticks(1000, 8, 700), laneWidth: 700 },-});--export const SubSecond = meta.story({- args: { ticks: ticks(100, 8, 700), laneWidth: 700 },-});--export const NarrowLane = meta.story({- args: { ticks: ticks(1000, 3, 240), laneWidth: 240 },-});--/**- * The axis renders a label at the same distance from its tick line that `layout()`- * reserves for it. There were three numbers for that one distance β a constant- * here, a Tailwind class in the renderer, and a literal in the label's clamp β so- * `fits()` was quietly stricter than the render and dropped ticks that would have- * been whole. One number, asserted against what the DOM did with it.- */-export const TheLabelSitsWhereLayoutReservedIt = meta.story({- name: "(Test) The Label Sits Where Layout Reserved It",- args: { ticks: ticks(1000, 6, 700), laneWidth: 700 },- play: async ({ canvasElement }) => {- const lane = canvasElement.querySelector<HTMLElement>(- "div[style*='width']",- );- if (!lane) throw new Error("no lane");- const labels = [...canvasElement.querySelectorAll<HTMLElement>("span")];- await expect(labels.length).toBeGreaterThan(1);-- const laneBox = lane.getBoundingClientRect();- for (const label of labels) {- const line = label.parentElement!.getBoundingClientRect();- const drawn = label.getBoundingClientRect();- // Exactly the reserved inset from its own tick line...- await expect(drawn.left - line.left).toBeCloseTo(TICK_LABEL_INSET_PX, 0);- // ...and never past the lane, whatever the label says.- await expect(drawn.right).toBeLessThanOrEqual(laneBox.right + 0.5);- }- // And the axis itself does not scroll β the same rule as everything else.- await expect(lane.scrollWidth).toBeLessThanOrEqual(lane.clientWidth);- },-});diff --git a/web/src/features/traces/components/TraceTimeline/TimelineScale.tsx b/web/src/features/traces/components/TraceTimeline/TimelineScale.tsxdeleted file mode 100644index 11403409ca..0000000000--- a/web/src/features/traces/components/TraceTimeline/TimelineScale.tsx+++ /dev/null@@ -1,62 +0,0 @@-/**- * TimelineScale - Renders the time axis at the top of the timeline.- *- * Draws ticks, nothing more: which times get a tick, where they land and how- * they are labelled all come from `layout()`, in the same coordinate space as- * the bars and the playhead. That is what keeps a tick labelled "5.00s" exactly- * above the bar that starts at 5.00s β the axis and the bars used to derive- * their positions separately and disagree whenever the rounded step size did- * not divide the trace duration evenly.- *- * Ticks whose label would not fit inside the measured lane are dropped by the- * layout rather than clipped here, so the axis obeys the same- * everything-inside-the-box rule as everything else.- */--import {- TICK_LABEL_GAP_PX,- TICK_LABEL_INSET_PX,-} from "../../fns/timeline/layout";-import { type TimelineScaleProps } from "./types";--export function TimelineScale({ ticks, laneWidth }: TimelineScaleProps) {- return (- <div className="mb-2">- <div- className="relative h-8 overflow-hidden"- style={{ width: `${laneWidth}px` }}- >- {ticks.map((tick) => (- <div- key={tick.realMs}- className="border-border-contrast absolute h-full border-l text-xs"- style={{ left: `${tick.x}px` }}- >- {/* maxWidth is the structural guarantee: layout() already drops a- tick whose label would not fit, but it predicts the width from- measured glyphs, and a prediction must not be the only thing- keeping the axis inside the box.-- The offset and the clamp both come from the constant layout()- reserves with, so the prediction and the render cannot drift. */}- <span- className="text-muted-foreground absolute overflow-hidden text-xs whitespace-nowrap"- style={{- // Inside the tick's border, so the gap β while the clamp pays for- // the border too, which is what layout() reserved.- left: `${TICK_LABEL_GAP_PX}px`,- maxWidth: `${Math.max(- laneWidth - tick.x - TICK_LABEL_INSET_PX,- 0,- )}px`,- }}- title={tick.label}- >- {tick.label}- </span>- </div>- ))}- </div>- </div>- );-}diff --git a/web/src/features/traces/components/TraceTimeline/TraceTimeline.tsx b/web/src/features/traces/components/TraceTimeline/TraceTimeline.tsxdeleted file mode 100644index a955afeae3..0000000000--- a/web/src/features/traces/components/TraceTimeline/TraceTimeline.tsx+++ /dev/null@@ -1,757 +0,0 @@-/**- * TraceTimeline - Gantt waterfall: a fixed name-gutter + a scrollable chart.- *- * Two panes, side by side, sharing the virtualized rows:- * - Gutter pane (fixed, resizable): the indented name tree. It never scrolls- * itself β its content is a one-way translateY projection of the chart's- * vertical scroll, so the two panes can't drift; wheeling or touch-dragging- * over it drives the chart.- * - Chart pane (flex-1): the gantt bars. Owns the only (vertical) scrollbar and- * is the virtualizer's scroll element.- *- * The chart NEVER scrolls horizontally. Its measured client width is the scale- * basis, so the whole trace is fitted into the lane the user actually has, at- * any size β every coordinate comes from the pure layout() in fns/timeline,- * which clamps bars, labels and ticks inside that lane. The previous design- * scaled against a hard-coded 900px canvas and let the container scroll, which- * put part of the trace off-screen in any narrower lane.- *- * Playback: the engine (RAF loop, transport) lives in the shared playhead- * store (contexts/playheadStore.ts); the transport buttons live in the- * navigation header (PlaybackControls). This file only draws the vertical- * playhead line + scrub handle (useTimelinePlayhead) and glows the active rows- * (each row shell subscribes to its own flag β see TimelineRows.tsx).- */--import {- useCallback,- useEffect,- useMemo,- useRef,- useState,- useLayoutEffect,-} from "react";-import { useVirtualizer } from "@tanstack/react-virtual";-import { useTraceData } from "@/src/features/traces/contexts/TraceDataContext";-import { useSelection } from "@/src/features/traces/contexts/SelectionContext";-import { useViewPreferences } from "@/src/features/traces/contexts/ViewPreferencesContext";-import {- usePlayhead,- useShowPlayhead,-} from "@/src/features/traces/contexts/PlayheadContext";-import { useHandlePrefetchObservation } from "@/src/features/traces/hooks/useHandlePrefetchObservation";-import { useSelectTraceNode } from "@/src/features/traces/hooks/useSelectTraceNode";-import { computeSelectionScrollTarget } from "../../fns/timelineCalculations";-import { formatIntervalSeconds } from "@/src/utils/dates";-import {- layout as computeTimelineLayout,- prepareTimeline,-} from "../../fns/timeline/layout";-import { resolveDensity } from "../../fns/timeline/density";-import { createTextMeasurer } from "../../fns/timeline/textMeasurer";-import { TimelineScale } from "./TimelineScale";-import { TimelineChartRowShell, TimelineGutterRowShell } from "./TimelineRows";-import {- computeMaxVisualDepth,- GUTTER_VISUAL_DEPTH,-} from "../../fns/visualDepth";-import { useMobileLayoutContextOptional } from "../TraceLayoutMobile";-import { type TreeNode } from "../../types/treeNode";-import { cn } from "@/src/utils/tailwind";--// Width of the left name gutter. Resizable; these bound it. Kept slim so the-// waterfall (the point of the timeline) gets the central space.-const GUTTER_WIDTH_DEFAULT = 200;-const GUTTER_WIDTH_MIN = 160;-const GUTTER_WIDTH_MAX = 560;-// Dense waterfall rows (LFE-10539): the 16px bar / 16px name chip sit centered-// with ~5px of breathing room. Resolved once here so the virtualizer estimate-// and the rendered row height cannot drift. Touch density is Phase 4's job, so-// this pins the fine-pointer value.-const DENSITY = resolveDensity({ pointer: "fine" });-const ROW_HEIGHT = DENSITY.rowHeight;--const EMPTY_SCORES: never[] = [];--/** The timeline's own duration copy, and therefore what layout() measures. */-const formatRowDuration = (durationMs: number) =>- formatIntervalSeconds(durationMs / 1000);--/**- * Wire a window-level drag gesture: move events flow to `onMove` until- * pointerup β and pointercancel (OS gesture, contextmenu, touch interruption),- * which must also tear down the listener, else the drag ghosts on afterwards.- * One helper for all three drag sites (gutter resize, scale scrub, handle- * scrub) so future fixes land once.- */-function startWindowDrag(onMove: (ev: PointerEvent) => void) {- const onUp = () => {- window.removeEventListener("pointermove", onMove);- window.removeEventListener("pointerup", onUp);- window.removeEventListener("pointercancel", onUp);- };- window.addEventListener("pointermove", onMove);- window.addEventListener("pointerup", onUp);- window.addEventListener("pointercancel", onUp);-}--/**- * The timeline's playhead surface: maps the shared engine onto gantt- * coordinates. Owns the line/handle refs, the imperative position feed- * (transforms + slider ARIA + follow-scroll while playing β no React state at- * 60fps), and the scrub gestures (scale click-drag, handle drag, handle- * keyboard).- */-function useTimelinePlayhead({- traceDuration,- secToX,- xToSec,-}: {- traceDuration: number;- /** Seconds from the trace origin β px in the chart lane. */- secToX: (sec: number) => number;- /** px in the chart lane β seconds from the trace origin. */- xToSec: (px: number) => number;-}) {- const { seekToSec, pause, getPlayheadSec, subscribePosition } = usePlayhead();- const showPlayhead = useShowPlayhead();-- const scaleOuterRef = useRef<HTMLDivElement>(null);- const playheadLineRef = useRef<HTMLDivElement>(null);- const playheadHandleRef = useRef<HTMLDivElement>(null);-- // Position the line + handle imperatively off the engine's position feed (no- // re-render). They only exist while showPlayhead; re-subscribe when the- // scale (secToX) changes so the mapping stays correct.- useEffect(() => {- if (!showPlayhead) return;- const apply = (sec: number) => {- const t = `translateX(${secToX(sec)}px)`;- if (playheadLineRef.current) playheadLineRef.current.style.transform = t;- const handle = playheadHandleRef.current;- if (handle) {- handle.style.transform = t;- // Slider semantics for assistive tech, updated on the same feed.- handle.setAttribute("aria-valuenow", sec.toFixed(2));- handle.setAttribute("aria-valuetext", `${sec.toFixed(2)} seconds`);- }- // No follow-scroll: the whole trace is fitted into the lane, so the- // playhead cannot sweep out of view.- };- apply(getPlayheadSec());- return subscribePosition(apply);- }, [showPlayhead, secToX, getPlayheadSec, subscribePosition]);-- // Translate a pointer x on the scale into a seek (places/moves the playhead).- // The scale shares the chart lane's coordinate space and neither scrolls, so- // the offset from the strip's left edge IS the lane x.- const seekFromClientX = useCallback(- (clientX: number) => {- const outer = scaleOuterRef.current;- if (!outer || traceDuration <= 0) return;- seekToSec(xToSec(clientX - outer.getBoundingClientRect().left));- },- [traceDuration, seekToSec, xToSec],- );-- const handleScalePointerDown = useCallback(- (e: React.PointerEvent) => {- e.preventDefault(); // don't start a text selection on the scale labels- seekFromClientX(e.clientX); // seekToSec pauses + shows the playhead- // Click-and-drag on the scale scrubs in one gesture.- startWindowDrag((ev) => seekFromClientX(ev.clientX));- },- [seekFromClientX],- );-- const handleHandlePointerDown = useCallback(- (e: React.PointerEvent) => {- // Grab the handle to scrub without re-seeking to the click x.- e.preventDefault();- e.stopPropagation();- pause();- startWindowDrag((ev) => seekFromClientX(ev.clientX));- },- [pause, seekFromClientX],- );-- // Keyboard seek on the handle: β/β nudge by 1% of the trace, Home/End jump.- const handleHandleKeyDown = useCallback(- (e: React.KeyboardEvent) => {- let next: number | null = null;- if (e.key === "ArrowLeft") next = getPlayheadSec() - traceDuration / 100;- else if (e.key === "ArrowRight")- next = getPlayheadSec() + traceDuration / 100;- else if (e.key === "Home") next = 0;- else if (e.key === "End") next = traceDuration;- if (next == null) return;- e.preventDefault();- seekToSec(next);- },- [traceDuration, getPlayheadSec, seekToSec],- );-- return {- scaleOuterRef,- playheadLineRef,- playheadHandleRef,- showPlayhead,- secToX,- getPlayheadSec,- handleScalePointerDown,- handleHandlePointerDown,- handleHandleKeyDown,- };-}--export function TraceTimeline() {- const {- roots,- serverScores: scores,- traceLevelScoreOwnerIds,- comments,- traceDuration,- } = useTraceData();- const { collapsedNodes, toggleCollapsed, selectedNodeId } = useSelection();- const {- showDuration,- showCostTokens,- showScores,- showComments,- colorCodeMetrics,- } = useViewPreferences();- const { handleHover } = useHandlePrefetchObservation();- const handleSelectNode = useSelectTraceNode("timeline");- // Optional (null on desktop): its presence also means the timeline is- // rendered inside a narrow mobile tab, which the gutter width follows.- const mobileLayout = useMobileLayoutContextOptional();-- // The chart is the single vertical scroller; the gutter content is a one-way- // transform projection of it (gutterInnerRef), so the two panes can't drift.- const gutterInnerRef = useRef<HTMLDivElement>(null);- const chartRef = useRef<HTMLDivElement>(null);-- // Hovered row, lifted to shared state so hovering either pane highlights the- // whole row (caption + chart), which CSS :hover can't do across two panes.- const [hoveredNodeId, setHoveredNodeId] = useState<string | null>(null);-- // Resizable name gutter so users can trade name space for chart space. On- // mobile the timeline lives in a narrow tab, so start the gutter at its MIN- // and let the waterfall (the point of the timeline) claim the rest β the- // chart pane keeps its own horizontal scroll, so the bars scroll within the- // tab instead of overflowing the page.- const [gutterWidth, setGutterWidth] = useState(() =>- mobileLayout ? GUTTER_WIDTH_MIN : GUTTER_WIDTH_DEFAULT,- );- const startGutterResize = useCallback(- (e: React.PointerEvent) => {- e.preventDefault();- const startX = e.clientX;- const startWidth = gutterWidth;- startWindowDrag((ev) => {- const next = startWidth + (ev.clientX - startX);- setGutterWidth(- Math.min(GUTTER_WIDTH_MAX, Math.max(GUTTER_WIDTH_MIN, next)),- );- });- },- [gutterWidth],- );-- // Cap gutter indentation to the gutter width so extremely deep traces (a- // reported one chained ~1400 levels) keep names readable instead of- // clipping into nothing (LFE-10959).- const gutterMaxVisualDepth = computeMaxVisualDepth(- gutterWidth,- GUTTER_VISUAL_DEPTH,- );-- // Tree walk, memoized on the tree + collapsed set: it is the one expensive- // part and it must stay out of the resize/render path.- const prepared = useMemo(- () => prepareTimeline(roots, collapsedNodes),- [roots, collapsedNodes],- );-- // Canvas glyph widths so layout() can decide whether a duration label fits- // inside its bar β measured in the font the labels ACTUALLY render in, read- // off a probe span carrying the label's own classes. Guessing the font gets- // the decision wrong: a `12px ui-sans-serif` guess resolves to a different- // face than the app's 11.2px system stack and underestimated an axis label by- // 5px, which is exactly enough to push it past the lane edge.- const [labelFont, setLabelFont] = useState<string | null>(null);- const labelProbeRef = useCallback((el: HTMLSpanElement | null) => {- if (!el) return;- const style = getComputedStyle(el);- const font = `${style.fontSize} ${style.fontFamily}`;- setLabelFont((prev) => (prev === font ? prev : font));- }, []);- const measurer = useMemo(- () => createTextMeasurer(labelFont ?? undefined),- [labelFont],- );-- // Virtualizer drives off the chart pane; the gutter mirrors its vertical scroll.- // overscan is a ROW COUNT (not px): keep it small so a long trace re-renders- // only a few dozen rows per scroll step instead of ~1000 (the old "500" β a- // px-vs-items mix-up β made big traces stutter). ~16 rows β half a viewport of- // headroom, enough to avoid blank rows on a normal scroll.- const rowVirtualizer = useVirtualizer({- count: prepared.rows.length,- getScrollElement: () => chartRef.current,- estimateSize: () => ROW_HEIGHT,- overscan: 16,- // Key by node id: an index-keyed measurement cache and an id-keyed DOM- // drift apart the moment a collapse changes what index a row holds.- getItemKey: (index) => prepared.rows[index]?.node.id ?? index,- });-- // Scroll the selected row into view whenever the selection changes β so- // selecting a node elsewhere (e.g. clicking it in the graph view) brings the- // matching timeline row into view. Math lives in computeSelectionScrollTarget- // (pure, tested); both axes go through ONE scrollTo (two competing smooth- // animations on the same element clobber each other).- const prevSelectedIdRef = useRef<string | null | undefined>(undefined);-- useLayoutEffect(() => {- if (!selectedNodeId || selectedNodeId === prevSelectedIdRef.current) {- prevSelectedIdRef.current = selectedNodeId;- return;- }-- const index = prepared.rows.findIndex(- (row) => row.node.id === selectedNodeId,- );- // Keep the scroll PENDING when the row is missing (collapsed subtree,- // level filter) β the ref stays un-advanced, so this retries when- // prepared.rows changes and the row appears.- if (index === -1) return;- const chart = chartRef.current;- if (!chart) return;-- const isInitial = prevSelectedIdRef.current === undefined;- prevSelectedIdRef.current = selectedNodeId;-- // Vertical only: the whole trace is fitted into the lane, so a selected bar- // is never off to the side. Reaching detail is zoom's job (Phase 3).- const { top } = computeSelectionScrollTarget({- index,- rowHeight: ROW_HEIGHT,- scrollTop: chart.scrollTop,- clientHeight: chart.clientHeight,- isInitial,- });-- chart.scrollTo({ top, behavior: isInitial ? "auto" : "smooth" });- }, [selectedNodeId, prepared]);-- // The chart owns the only scroll. The gutter is a one-way projection of it- // (translateY) updated in the same scroll frame β no second scroll container- // to fight the chart's momentum, which is what made the two panes drift- // apart. The scale needs no projection: nothing scrolls horizontally.- const handleChartScroll = useCallback(() => {- const chart = chartRef.current;- if (!chart) return;- if (gutterInnerRef.current) {- gutterInnerRef.current.style.transform = `translateY(${-chart.scrollTop}px)`;- }- }, []);-- // The gutter doesn't scroll itself; wheeling over it drives the chart, which- // then projects back onto the gutter via handleChartScroll. Normalize the- // delta to pixels first: Firefox (and classic mouse wheels) report deltaMode- // in lines (1) or pages (2), not pixels (0) β without this, a line-mode wheel- // moves ~1px per notch and the gutter feels stuck.- const handleGutterWheel = useCallback((e: React.WheelEvent) => {- const chart = chartRef.current;- if (!chart) return;- const unit =- e.deltaMode === 1- ? ROW_HEIGHT- : e.deltaMode === 2- ? chart.clientHeight- : 1;- chart.scrollTop += e.deltaY * unit;- }, []);-- // Touch (and pen/mouse drag) over the gutter scrolls it too. WheelEvents are- // never synthesized on touch, so on touch-capable screens that render this- // desktop layout the wheel handler alone leaves the gutter stuck. Pointer- // events cover touch + pen + mouse uniformly: we drag-scroll the chart (move- // a finger up β content scrolls up, so scrollTop -= dy), and the chart- // projects straight back onto the gutter via handleChartScroll β same- // pixel-locked path as the wheel, so the two panes still can't drift.- const dragRef = useRef<{ pointerId: number; lastY: number } | null>(null);- const handleGutterPointerDown = useCallback((e: React.PointerEvent) => {- // Only drag-scroll for touch/pen. Leave the mouse to clicks (rows are- // clickable) and the wheel; a mouse drag here would otherwise hijack- // text selection / row clicks.- if (e.pointerType === "mouse") return;- const chart = chartRef.current;- if (!chart) return;- dragRef.current = { pointerId: e.pointerId, lastY: e.clientY };- e.currentTarget.setPointerCapture(e.pointerId);- }, []);- const handleGutterPointerMove = useCallback((e: React.PointerEvent) => {- const drag = dragRef.current;- const chart = chartRef.current;- if (!drag || drag.pointerId !== e.pointerId || !chart) return;- // Clamp-aware: only consume the scroll delta the browser actually applied.- // The browser clamps scrollTop to [0, maxScroll], so advancing lastY to- // e.clientY unconditionally would record finger motion past a boundary that- // scrollTop discarded; a later direction reversal would then resurface as- // phantom scroll with zero net finger travel. Advancing lastY by only the- // applied delta keeps over-the-boundary motion from leaking back in.- const prev = chart.scrollTop;- chart.scrollTop -= e.clientY - drag.lastY;- drag.lastY += prev - chart.scrollTop;- }, []);- const handleGutterPointerEnd = useCallback((e: React.PointerEvent) => {- if (dragRef.current?.pointerId !== e.pointerId) return;- dragRef.current = null;- if (e.currentTarget.hasPointerCapture(e.pointerId)) {- e.currentTarget.releasePointerCapture(e.pointerId);- }- }, []);-- // Parent totals for heatmap coloring (aggregate across all roots).- const parentTotalCost = useMemo(() => {- return roots.reduce(- (acc, r) => {- if (!r.totalCost) return acc;- return acc ? acc.plus(r.totalCost) : r.totalCost;- },- undefined as (typeof roots)[0]["totalCost"],- );- }, [roots]);- // MILLISECONDS: TimelineBar heat-maps ownDurationMs against this max, and- // the tree path (TraceTree rootTotalDuration) is ms too. traceDuration is- // seconds β passing it raw inflated the heat ratio Γ1000, painting every- // duration label dark red.- const parentTotalDuration = traceDuration * 1000;-- // Score lookup keyed by tree-node id: one pass over the scores instead of an- // O(scores) filter per row per render. Trace-level scores land on their owner- // node(s) β the TRACE row, or every top-level span when there is none β so the- // timeline badge matches the tree badge and the node's Scores tab.- const scoresByNodeId = useMemo(() => {- const byNode = new Map<string, typeof scores>();- const pushTo = (key: string, score: (typeof scores)[number]) => {- const arr = byNode.get(key);- if (arr) arr.push(score);- else byNode.set(key, [score]);- };- for (const score of scores) {- if (score.observationId) {- pushTo(score.observationId, score);- } else {- for (const ownerId of traceLevelScoreOwnerIds) {- pushTo(ownerId, score);- }- }- }- return byNode;- }, [scores, traceLevelScoreOwnerIds]);-- const totalSize = rowVirtualizer.getTotalSize();- const virtualItems = rowVirtualizer.getVirtualItems();-- // THE measurement. The chart pane's own client box is the scale basis, and it- // must be the box of the element that SCROLLS: its border and its vertical- // scrollbar (~15px on Windows/Linux, 0 with macOS overlay bars) both take- // width that an arithmetic guess from the container would miss, and any such- // miss is a lane wider than the space available β which is horizontal scroll,- // the thing this design removes. `scrollbarWidth` is reported separately so- // the scale strip, which has no scrollbar of its own, can reserve the same- // gutter and stay aligned with the bars.- const [chartBox, setChartBox] = useState({- width: 0,- height: 0,- scrollbarWidth: 0,- });- useLayoutEffect(() => {- const el = chartRef.current;- if (!el) return;- const measure = () => {- const next = {- width: el.clientWidth,- height: el.clientHeight,- scrollbarWidth: el.offsetWidth - el.clientWidth,- };- // Only re-render when the measurement actually changes β the observer- // fires on every content resize, but the box rarely moves.- setChartBox((prev) =>- prev.width === next.width &&- prev.height === next.height &&- prev.scrollbarWidth === next.scrollbarWidth- ? prev- : next,- );- };- measure();- const ro = new ResizeObserver(measure);- ro.observe(el);- return () => ro.disconnect();- }, [totalSize, gutterWidth]);-- // One pure call owns every coordinate on screen, for the mounted rows only.- // The view is the whole trace: zoom/pan is Phase 3, and until then- // "fit to the measured box" is the only view there is.- //- // Memoized because it allocates a fresh PositionedNode per mounted row, and- // the row shells are React.memo precisely so a hover or a selection re-renders- // the two rows that changed. Recomputing this on every render handed all of- // them a new `row` object and re-rendered every one, which is the memo- // boundary TimelineRows.tsx documents doing nothing at all.- // Keyed on the two indices rather than on the items array, so the range is- // only a new object when the mounted window really moved.- const firstIndex = virtualItems.length ? virtualItems[0]!.index : -1;- const lastIndex = virtualItems.length- ? virtualItems[virtualItems.length - 1]!.index- : -1;- const rowRange = useMemo(- () =>- firstIndex < 0- ? // Before the virtualizer has measured its scroll element, fill the box.- {- startIndex: 0,- endIndex: Math.ceil(chartBox.height / ROW_HEIGHT) + 1,- }- : { startIndex: firstIndex, endIndex: lastIndex },- [firstIndex, lastIndex, chartBox.height],- );- const chartLayout = useMemo(- () =>- computeTimelineLayout({- roots,- box: { width: chartBox.width, height: chartBox.height },- density: DENSITY,- measurer,- view: null,- compress: false,- prepared,- rowRange,- // The bar renders `label`, so the layout has to measure the string the- // bar will draw β see the formatLabel contract in fns/timeline/layout.ts.- formatLabel: formatRowDuration,- }),- [roots, chartBox.width, chartBox.height, measurer, prepared, rowRange],- );-- // Playhead β lane mapping, in the same space as the bars and the ticks.- const { pxPerMs } = chartLayout;- const secToX = useCallback((sec: number) => sec * 1000 * pxPerMs, [pxPerMs]);- const xToSec = useCallback(- (px: number) => (pxPerMs > 0 ? px / pxPerMs / 1000 : 0),- [pxPerMs],- );-- const {- scaleOuterRef,- playheadLineRef,- playheadHandleRef,- showPlayhead,- getPlayheadSec,- handleScalePointerDown,- handleHandlePointerDown,- handleHandleKeyDown,- } = useTimelinePlayhead({ traceDuration, secToX, xToSec });-- // Stable node-taking callback shared by every row shell (see TimelineRows.tsx- // β stable references keep the memo boundary effective). Selecting itself is- // useSelectTraceNode, above, which every view of a trace shares.- const handleHoverNode = useCallback(- (node: TreeNode) => {- setHoveredNodeId(node.id);- handleHover(node);- },- [handleHover],- );-- return (- <div className="flex h-full w-full flex-col overflow-hidden">- {/* Header: name label + time scale. The scale shares the chart lane's- coordinate space and neither scrolls, so no transform sync is needed β- it only reserves the width the chart's scrollbar takes. Transport- controls live in the shared navigation header (see PlaybackControls). */}- <div className="flex shrink-0">- <div- className="bg-background text-muted-foreground flex shrink-0 items-center pl-2 text-xs font-bold"- style={{ width: `${gutterWidth}px` }}- >- <span className="truncate" title="Name">- Name- </span>- </div>- <div className="bg-border-contrast/60 w-px shrink-0" />- <div- ref={scaleOuterRef}- onPointerDown={handleScalePointerDown}- className="flex-1 cursor-pointer overflow-hidden select-none"- style={{ marginRight: `${chartBox.scrollbarWidth}px` }}- >- <div className="relative">- {/* Font probe for the text measurer: same classes as a tick label,- invisible and out of flow so it costs no layout. */}- <span- ref={labelProbeRef}- aria-hidden- className="text-muted-foreground invisible absolute text-xs"- >- 0- </span>- <TimelineScale- ticks={chartLayout.ticks}- laneWidth={chartBox.width}- />- {showPlayhead && (- <div- ref={playheadHandleRef}- role="slider"- tabIndex={0}- aria-label="Playhead position"- aria-valuemin={0}- aria-valuemax={Number(traceDuration.toFixed(2))}- aria-valuenow={Number(getPlayheadSec().toFixed(2))}- onPointerDown={handleHandlePointerDown}- onKeyDown={handleHandleKeyDown}- className={cn(- "absolute top-0 bottom-0 z-30 -ml-1.5 w-3 cursor-ew-resize select-none",- "focus-visible:ring-ring rounded focus-visible:ring-2 focus-visible:outline-none",- )}- style={{- transform: `translateX(${secToX(getPlayheadSec())}px)`,- }}- >- <div className="bg-primary mx-auto h-2 w-2 rotate-45" />- </div>- )}- </div>- </div>- </div>-- {/* Body: gutter pane | resizer | chart pane. */}- <div- className="flex min-h-0 flex-1"- onMouseLeave={() => setHoveredNodeId(null)}- >- {/* Gutter pane β a one-way projection of the chart's vertical scroll- (translateY), never its own scroll container, so it stays locked to- the chart. Wheeling or touch-dragging over it drives the chart.- touchAction:none stops the browser claiming the vertical pan gesture- (there's nothing to pan here) so our pointer-drag handlers fire. */}- <div- onWheel={handleGutterWheel}- onPointerDown={handleGutterPointerDown}- onPointerMove={handleGutterPointerMove}- onPointerUp={handleGutterPointerEnd}- onPointerCancel={handleGutterPointerEnd}- className="shrink-0 touch-none overflow-hidden"- style={{ width: `${gutterWidth}px` }}- >- <div- ref={gutterInnerRef}- style={{- // Match the chart's scrollable extent. The chart no longer scrolls- // horizontally, so there is no horizontal scrollbar height to- // reserve for any more.- height: `${totalSize}px`,- position: "relative",- willChange: "transform",- }}- >- {chartLayout.nodes.map((row) => {- const nodeId = row.node.id;- return (- <TimelineGutterRowShell- key={nodeId}- row={row}- top={row.y}- height={row.height}- isSelected={selectedNodeId === nodeId}- isHovered={hoveredNodeId === nodeId}- hasChildren={row.hasChildren}- isCollapsed={row.isCollapsed}- maxVisualDepth={gutterMaxVisualDepth}- onSelect={handleSelectNode}- onHover={handleHoverNode}- onToggleCollapse={toggleCollapsed}- />- );- })}- </div>- </div>-- {/* Resizer: structural 1px divider with a wider invisible drag grip. */}- <div className="bg-border-contrast/60 relative w-px shrink-0">- <div- role="separator"- aria-orientation="vertical"- aria-label="Resize name column"- onPointerDown={startGutterResize}- className={cn(- "hover:bg-primary/40 active:bg-primary/40 absolute inset-y-0 left-1/2 z-20 w-2",- "-translate-x-1/2 cursor-col-resize",- )}- />- </div>-- {/* Chart pane β vertical scroll only. overflow-x is hidden rather than- auto so a stray sub-pixel can never reintroduce a horizontal- scrollbar; the content is exactly the measured lane wide. */}- <div- ref={chartRef}- onScroll={handleChartScroll}- className="flex-1 overflow-x-hidden overflow-y-auto"- >- <div- style={{- height: `${totalSize}px`,- width: `${chartBox.width}px`,- position: "relative",- }}- >- {chartLayout.nodes.map((row) => {- const nodeId = row.node.id;- return (- <TimelineChartRowShell- key={nodeId}- row={row}- top={row.y}- height={row.height}- width={chartBox.width}- density={DENSITY}- isSelected={selectedNodeId === nodeId}- isHovered={hoveredNodeId === nodeId}- showDuration={showDuration}- showCostTokens={showCostTokens}- showScores={showScores}- showComments={showComments}- colorCodeMetrics={colorCodeMetrics}- parentTotalCost={parentTotalCost}- parentTotalDuration={parentTotalDuration}- commentCount={comments.get(nodeId) ?? 0}- nodeScores={scoresByNodeId.get(nodeId) ?? EMPTY_SCORES}- measurer={measurer}- onSelect={handleSelectNode}- onHover={handleHoverNode}- />- );- })}- {showPlayhead && (- <div- ref={playheadLineRef}- className="bg-primary pointer-events-none absolute top-0 z-20 w-0.5"- style={{- left: 0,- height: `${totalSize}px`,- transform: `translateX(${secToX(getPlayheadSec())}px)`,- }}- />- )}- </div>- </div>- </div>- </div>- );-}diff --git a/web/src/features/traces/components/TraceTimeline/__tests__/timeline.fixtures.ts b/web/src/features/traces/components/TraceTimeline/__tests__/timeline.fixtures.tsdeleted file mode 100644index d3949607d7..0000000000--- a/web/src/features/traces/components/TraceTimeline/__tests__/timeline.fixtures.ts+++ /dev/null@@ -1,123 +0,0 @@-/**- * Small fixtures for TraceTimeline stories. Kept minimal β the smallest shape- * that renders each state β and shared across the TimelineBar / TimelineGutterRow- * stories so node construction lives in one place.- */--import Decimal from "decimal.js";-import { type TreeNode } from "@/src/features/traces/types/treeNode";-import {- type TimelineBarProps,- type TimelineRowNode,-} from "@/src/features/traces/components/TraceTimeline/types";--const BASE_START = new Date("2024-01-01T00:00:00.000Z");--export function makeTreeNode(overrides: Partial<TreeNode> = {}): TreeNode {- const startTime = overrides.startTime ?? BASE_START;- return {- id: "node",- type: "GENERATION",- name: "llm-call",- startTime,- endTime: new Date(startTime.getTime() + 2000),- latency: 2,- children: [],- startTimeSinceTrace: 0,- startTimeSinceParentStart: 0,- depth: 0,- childrenDepth: 0,- ...overrides,- };-}--/**- * A row as `layout()` returns it. Geometry is passed in directly rather than- * computed so a story can pin the exact placement it wants to show.- */-export function makeRow(- overrides: Partial<TimelineRowNode> = {},-): TimelineRowNode {- const node = overrides.node ?? makeTreeNode();- return {- node,- id: node.id,- name: node.name,- type: node.type,- index: 0,- depth: 0,- treeLines: [],- isLastSibling: true,- hasChildren: node.children.length > 0,- isCollapsed: false,- y: 0,- height: 26,- x: 60,- width: 220,- clippedLeft: false,- clippedRight: false,- offscreen: false,- durationMs: 2000,- firstTokenX: null,- label: "2.00s",- labelWidth: 32,- labelPlacement: "after",- labelX: 286,- startMs: 0,- endMs: 2000,- ...overrides,- };-}--export const cost = (value: number) => new Decimal(value);--/**- * A numeric score, as the timeline receives them: metadata already stringified.- *- * `level` and the annotation flags matter for WIDTH: a row that mixes levels- * grows a spelled-out pill per chip, and a value carrying a comment and metadata- * grows two icons β all three are things the cluster has to reserve room for.- */-export function score(- name: string,- value: number,- extras: {- level?: "trace" | "observation";- comment?: string;- metadata?: string;- /**- * A categorical score's own label. Worth setting when a test needs its width- * to be EXACT: the measurer prices every digit at the widest digit's width,- * on purpose (a ticking duration must not jitter), so a numeric value is- * reserved a couple of px over β enough slack to hide a small mispricing- * elsewhere in the same sum.- */- stringValue?: string;- } = {},-): NonNullable<TimelineBarProps["scores"]>[number] {- return {- id: `score-${name}`,- projectId: "project",- environment: "default",- name,- value,- stringValue: extras.stringValue ?? null,- dataType: extras.stringValue ? "CATEGORICAL" : "NUMERIC",- source: "API",- authorUserId: null,- comment: extras.comment ?? null,- metadata: extras.metadata ?? null,- configId: null,- queueId: null,- executionTraceId: null,- createdAt: BASE_START,- updatedAt: BASE_START,- timestamp: BASE_START,- traceId: "trace",- sessionId: null,- datasetRunId: null,- // A trace-level score has no observation; that is what makes a row "mixed".- observationId: extras.level === "trace" ? null : "node",- longStringValue: "",- };-}diff --git a/web/src/features/traces/components/TraceTimeline/types.ts b/web/src/features/traces/components/TraceTimeline/types.tsdeleted file mode 100644index 58883273b0..0000000000--- a/web/src/features/traces/components/TraceTimeline/types.ts+++ /dev/null@@ -1,89 +0,0 @@-/**- * Timeline-specific types for trace visualization- *- * Geometry is not here: every coordinate comes from `PositionedNode`, produced- * by the pure `layout()` in fns/timeline. These types only describe what the- * row components need on top of it.- */--import type { TreeNode } from "../../types/treeNode";-import type { PositionedNode, Tick } from "../../fns/timeline/layout";-import type { TextMeasurer } from "../../fns/timeline/textMeasurer";-import type { Density } from "../../fns/timeline/density";-import type Decimal from "decimal.js";-import type { ScoreDomain } from "@langfuse/shared";-import type { WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";--/** A row of the timeline, positioned against the measured lane. */-export type TimelineRowNode = PositionedNode<TreeNode>;--/**- * Props for TimelineBar component- * Renders the gantt bar (duration) plus a trailing metric label, positioned on- * the time axis. Hierarchy/identity (badge, name, connectors) lives in the- * gutter (TimelineGutterRow), not here.- */-export interface TimelineBarProps {- row: TimelineRowNode;- /** Measured width of the chart lane; the cluster may not cross it. */- laneWidth: number;- /** Same measurer layout() used, so the bar can fit its own optional badges. */- measurer: TextMeasurer;- /**- * Same density layout() used. The cluster's gap and inset ARE- * `labelGapPx`/`labelPaddingPx` β the values `placeLabel()` measured the- * placement with β so they have to come from the same place, or a change to- * density silently desyncs the rendered cluster from the decision made about- * where it goes.- */- density: Density;- isSelected: boolean;- /** Row is hovered (driven by shared state so the whole row highlights). */- isHovered?: boolean;- // View preferences- showDuration: boolean;- showCostTokens: boolean;- showScores: boolean;- showComments: boolean;- colorCodeMetrics: boolean;- // Heatmap context for color coding- parentTotalCost?: Decimal;- parentTotalDuration?: number;- // Comment count (optional)- commentCount?: number;- // Scores for badges- scores?: WithStringifiedMetadata<ScoreDomain>[];-}--/**- * Props for TimelineGutterRow component- * Renders the left gutter: tree connectors + icon + name (the depth coordinate).- * Identity only β time/metrics live on the bar (TimelineBar) in the chart pane.- */-export interface TimelineGutterRowProps {- row: Pick<TimelineRowNode, "node" | "depth" | "treeLines" | "isLastSibling">;- isSelected: boolean;- /** Row is hovered (shared state so the gutter + chart highlight together). */- isHovered?: boolean;- onSelect: () => void;- onHover?: () => void;- onToggleCollapse: () => void;- hasChildren: boolean;- isCollapsed: boolean;- /**- * Deepest level to render indentation for; deeper rows render flat at this- * level so extreme depth never clips names away (LFE-10959, see- * _shared/visual-depth.ts). Defaults to unbounded.- */- maxVisualDepth?: number;-}--/**- * Props for TimelineScale component- * Renders the time axis from ticks the layout already placed and labelled.- */-export interface TimelineScaleProps {- ticks: readonly Tick[];- /** Measured width of the chart lane. */- laneWidth: number;-}diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsxindex fda703d5c8..97da08e83a 100644--- a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx@@ -1,9 +1,7 @@/**- * The Compact Timeline renderer, shipped behind the `compactTimeline` feature- * preview: `TraceTimelineCompact` measures a box and renders this inside it, and- * the trace panel's Timeline view is this whenever the preview is on β by- * default for the team, opt-in for everyone else. Real users read traces through- * it, so a bug here is a bug in the product.+ * The Timeline. `TraceTimelineCompact` measures a box and renders this inside it,+ * and the trace panel's Timeline view IS this β for everyone, on every device,+ * with no flag in front of it. A bug here is a bug in the product.** The question it started as a spike to answer, and still answers: in a narrow,* tall layout, does killing the names and the text and spending every pixel ondiff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineRowMetrics.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineRowMetrics.tsxindex 74e685b564..e2db9ead23 100644--- a/web/src/features/traces/components/TraceTimelineDense/TimelineRowMetrics.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineRowMetrics.tsx@@ -14,10 +14,6 @@* is the one thing this timeline promises never to do.*/-import {- CLUSTER_ITEM_GAP_PX,- createClusterFitter,-} from "../../fns/timeline/metricCluster";import { type Density } from "../../fns/timeline/density";import { type TextMeasurer } from "../../fns/timeline/textMeasurer";import { type PositionedNode } from "../../fns/timeline/layout";@@ -36,6 +32,29 @@ import { type PositionedNode } from "../../fns/timeline/layout";* white for contrast. They belong somewhere that does not move: the tree, the* detail panel, or a fixed column of their own.*/+/**+ * The cluster's own `gap-2`. A budget has to reserve the gap the cluster actually+ * renders with, not a smaller one: five admitted items multiply a 2px+ * under-reservation into a clipped last item.+ */+const CLUSTER_ITEM_GAP_PX = 8;++/**+ * Admit items into the room the lane has left, in priority order, charging each+ * the gap the cluster renders with. The flex gap sits BETWEEN children, so the+ * first item is charged none: billing it for a gap it does not have rejected+ * content that renders perfectly well alone.+ */+function createClusterFitter(budgetPx: number, gapPx: number) {+ let spentPx = 0;+ return (widthPx: number): boolean => {+ const next = spentPx + widthPx + (spentPx > 0 ? gapPx : 0);+ if (next > budgetPx) return false;+ spentPx = next;+ return true;+ };+}+export type RowMetrics = {/** Already formatted, e.g. `β $0.02`. */costText?: string | null;diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2.mdx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2.mdxdeleted file mode 100644index e69e06613c..0000000000--- a/web/src/features/traces/components/TraceTimelineV2/TimelineV2.mdx+++ /dev/null@@ -1,199 +0,0 @@-import { Canvas, Meta } from "@storybook/addon-docs/blocks";-import * as TimelineV2Stories from "./TimelineV2.stories";-import * as SizeStories from "./TimelineV2Sizes.stories";-import * as CompressionStories from "./TimelineV2Compression.stories";-import * as MobileStories from "./TimelineV2Mobile.stories";--<Meta of={TimelineV2Stories} name="Findings" />--# Size-adaptive timeline β spike findings--A throwaway renderer over a pure `layout()`, built to answer one question before-any production code moves: **does fit-to-box + zoom + time compression read-better than today's fixed 900px canvas, at every size and shape?**--**Verdict: yes, and by a wide margin.** The model holds at every cell of the-matrix. Two things it does not solve on its own are called out below: the name-gutter below ~480px, and what a collapsed gap should look like.--## What to look at, in order--1. **Sizes β Variant Matrix.** The same nine-observation trace at 320 / 480 /- 768 / 1280 / 1920. Every bar is inside every box. Nothing scrolls sideways at- any width. The scale readout under each cell shows the px/ms the box bought.-2. **Timeline V2 β Reporter Shape.** The exact trace from the community report,- in the peek-width lane it was reported in. Compare against the screenshot on- that issue.-3. **Compression β Long Tail Honest, then Long Tail Compressed.** The whole- trade-off in two cells.-4. **Mobile β Variant Matrix.** Five takes on the gutter problem at 320px.-5. **Timeline V2 β Ten Thousand Spans.** Ctrl-scroll (or pinch) inside the- chart to zoom; double-click a bar to fit it; double-click again to reset.--## Does the model win?--<Canvas of={SizeStories.VariantMatrix} />--At 320px the trace is whole, the axis is honest and the durations are readable.-That is the claim, and it holds without a single conditional on viewport width:-`layout()` gets the measured box and everything else follows. The 1920px cell-gets 3.37 px/ms for the same trace, from the same code path.--Where it does **not** win on its own:--- **Names.** At 320px the gutter is 127px, so `RunnableSequence` renders as- `Runnaβ¦`. Fit-to-box fixed time, not identity. See the mobile section.-- **Zero-information cells.** All-instantaneous and missing-`endTime` traces- render a column of dashed minimum-width markers. That is honest β there is- genuinely no duration to draw β but a trace where nothing has an end would- read better as a list than as a chart. Worth a Phase 2 decision, not a- renderer change.--## Two bugs the spike caught in its own first render--Both are the exact failure class the architecture exists to remove, and both are-worth remembering for Phase 2:--1. **The frame border.** The component sized its lanes from the `box` prop while- the actual content area was 2px narrower, so `gutter + lane` exceeded the- viewport and produced 2px of horizontal scroll. Fixed by measuring the scroll- viewport's own client box with a `ResizeObserver` rather than deriving it.-2. **The scrollbar.** On a platform with classic scrollbars the same arithmetic- is wrong by another ~15px. Measuring covers both. **Phase 2 must measure the- element that scrolls, not the element that contains it.**--## Design question 1 β mobile composition--<Canvas of={MobileStories.VariantMatrix} />--| Take | Lane | Verdict |-| --------------------------------- | ----- | ----------------------------------------------------------------------- |-| `split` β gutter beside chart | 191px | Correlation kept, names useless (`Chatβ¦`) |-| `icons` β gutter is icon + caret | 272px | Chart readable, identity gone entirely |-| `overlay` β names over the bars | 318px | Worst: name, duration and bar fight for the same pixels, depth lost |-| `stacked` β name above, bar below | 318px | **Best.** Full names, full-width chart, depth by indent, durations kept |-| `modes` β tree β timeline toggle | 318px | Honest, but correlating a name to a bar costs a mode flip |--**Recommendation: `stacked` for `pointer: coarse` / narrow boxes, `split`-above ~480px.** It is the only take that keeps all three of identity, duration-and position, and it costs only row height β which touch density was already-spending (44px). Note this moved `density`'s second axis somewhere the plan did-not anticipate: `resolveDensity` takes `lines: 1 | 2`, because a row that stacks-a name over a bar needs two text lines' worth of height.--**Density is not a function of box height.** The first revision grew rows into-the slack of a tall box (a 3-row trace got 34px rows in a 420px box); review-rejected it on sight β density is the whole point of the parent ticket, so the-box decides how many rows are visible, never how tall they are. Row height-resolves from modality and lines-per-row only: 26px fine, 44px coarse, 38px-stacked.--**Does this need a designer?** For the _choice_, no β `stacked` is clearly-ahead. For the _finish_, yes: row separation, what a selected row looks like,-and whether the type icon stays on the name line are visual calls, and the-stacked row is a new pattern in this product rather than a tweak to an existing-one.--## Design question 2 β compression on by default?--<Canvas of={CompressionStories.LongTailHonest} />--Fitted honestly, a 36.02s trace whose real work is three 40ms spans gives-0.005 px/ms: three 4px slivers pinned to the minimum bar width. This is exactly-the "36.02s root drawn as a sliver" complaint, reproduced.--<Canvas of={CompressionStories.LongTailCompressed} />--Compressed: **0.372 px/ms, a 74Γ change**, and the spans are real bars with-readable labels. Two collapsed bands cost 28px each β 29% of a 191px lane spent-saying "nothing happened here".--**Recommendation: default OFF, one click away, and auto-suggested.** Reasons:--- Compression is only ever a large win on long-tail traces. On a dense trace it- correctly does nothing (see _Dense Trace Compressed_), so defaulting it on- would change nothing for most traces while making a minority of traces lie.-- It genuinely misleads. A user reading proportion off a compressed axis reads- it wrong, and that is a support cost we would be creating.-- The cheap middle path: when `layout()` reports gaps that _would_ collapse,- offer it in place β "36.02s, 99.6% idle Β· compress?" β rather than making- every user carry a preference.--Two things compression needs before it ships, both learned here:--- **Ticks at the gap boundaries.** Without them every nice-step tick falls- inside a collapsed gap and the axis degrades to a lone `0ms`. With them the- axis reads `0ms Β· 17.95s Β· 35.91s` and the visible jump across a 28px band is- what explains the band.-- **A better band than `β―`.** The current treatment is a dashed grey column- with a hover title. It is legible-but-mute, and 28px cannot hold `17.84s`.- This is a small design ask.--## Performance β the React-vs-imperative call--The plan bets that vertical virtualization keeps the mounted row count low-enough that recomputing every visible bar per frame in React is affordable, so-we can adopt Sentry's 146-line space model and skip its 2447-line imperative-view manager. **The bet is correct, with three orders of magnitude to spare.**--Measured on the 10k-span story, 768Γ420 box, 486px lane:--| Measurement | Result |-| ---------------------------------------------------- | -------------------------------------- |-| Mounted bars for 10,000 rows | **20** |-| `layout()`, 40-row window, per call | **0.0070 ms** (0.0046 ms compressed) |-| Frame time, 235 frames of continuous ctrl-wheel zoom | p50 **8.3 ms**, p95 9.3 ms, max 9.4 ms |-| Frames over 16.7 ms | **0** |-| Same measurement with no zoom driven (baseline) | p50 8.3 ms, max 9.4 ms |-| Zoom range actually swept during the run | 0.02 β 486 px/ms |-| `prepareTimeline(10k)` β memoized on tree + collapse | 1.92 ms |-| `timeCompressionFor(10k)` β memoized on box width | 2.05 ms |--Frame time under continuous zoom is **indistinguishable from idle**, and the-pure math is ~0.007ms against a 16.7ms budget. Measured in Storybook's dev-build, so React is unminified and in development mode β production is faster,-making these numbers a pessimistic bound.--**Conclusion: adopt the space model, skip the view manager.** If a future shape-ever does drop frames, `layout()` is the seam an imperative write path plugs-into without redesigning anything above it β the two calls that are not cheap-(`prepareTimeline`, `timeCompressionFor`) are already memoized out of the frame-loop.--## Deviations from the Sentry originals--- **Time compression prices its label buffer at the wrong scale.** Sentry- converts `DURATION_LABEL_BUFFER_PX = 48` to milliseconds using the- _uncompressed_ px/ms. In a 320px lane that reserves ~5.4 seconds around each- span of a 36s trace, and compression becomes a no-op precisely where it is- needed most. One fixed-point step β compress with no buffer, then re-compress- with the buffer priced at the resulting scale β takes the long-tail case from- ~15px of legible bar to ~41px.-- **Clamping holds the zoom, not the pan.** At the right edge Sentry holds- `trace_view.x` and shrinks the window; we hold the window and pull `x` back.- Panning past the end should stop, not silently zoom out.-- **A plain scalar transform replaces `mat3`.** Both spaces are- one-dimensional in time, so the matrix composition buys nothing.-- **No `gl-matrix`, no `TraceScheduler`, no DOM-ref write path.**--## What Phase 2 inherits--Pure and tested, no React: `layout()`, the four-space view model, compression,-the text measurer, density resolution. `TreeNode` already satisfies `LayoutNode`-structurally, so there is no adapter to write.--Suggested sub-issue split:--1. **Land the renderer** behind the existing timeline entry point β measured box- β `layout()` β absolute placement, `SCALE_WIDTH` deleted, gutter/chart split,- virtualization, playhead and selection kept working. Closes the community- issue; its acceptance test is _Reporter Shape_ at peek width.-2. **Zoom/pan as real state** β toolbar, double-tap-to-fit, URL persistence if- we want shareable zoom.-3. **Touch + density** β pinch, drag, the `stacked` composition below 480px,- `pointer: coarse` resolution, and a tap equivalent for every hover-only- affordance in `TimelineBar`.-4. **Compression, with the gap-boundary ticks and a designed band**, behind the- suggest-in-place affordance rather than a preference.-5. **The density follow-ups** β gutter header dead space, observation names- weighted like the trace tree.diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2.stories.tsx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2.stories.tsxdeleted file mode 100644index cf41e61bc5..0000000000--- a/web/src/features/traces/components/TraceTimelineV2/TimelineV2.stories.tsx+++ /dev/null@@ -1,468 +0,0 @@-import { useState } from "react";-import { expect, userEvent, waitFor } from "storybook/test";-import preview from "../../../../../.storybook/preview";-import { TimelineV2, type TimelineV2Props } from "./TimelineV2";-import {- TIMELINE_SHAPES,- allInstantaneous,- deepNesting,- longTailTrace,- manySpans,- missingEndTimes,- reporterTrace,- singleSpan,- threeSpans,- zeroDurationTrace,-} from "../../fns/timeline/__tests__/timelineV2.fixtures";--const meta = preview.meta({- component: TimelineV2,-});--/** A comfortable desktop lane; the size axis lives in TimelineV2Sizes. */-const DESKTOP = { width: 768, height: 420 };-/** Roughly the peek panel β the lane the community bug was reported in. */-const PEEK = { width: 320, height: 260 };--export const ReporterShape = meta.story({- args: {- roots: reporterTrace(),- box: PEEK,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const SingleSpan = meta.story({- args: {- roots: singleSpan(),- box: DESKTOP,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const ThreeSpans = meta.story({- args: {- roots: threeSpans(),- box: DESKTOP,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const DeepNesting = meta.story({- args: {- roots: deepNesting(12),- box: DESKTOP,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const FiveHundredSpans = meta.story({- args: {- roots: manySpans(500),- box: DESKTOP,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const TenThousandSpans = meta.story({- args: {- roots: manySpans(10_000),- box: DESKTOP,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const LongTail = meta.story({- args: {- roots: longTailTrace(),- box: DESKTOP,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const AllInstantaneous = meta.story({- args: {- roots: allInstantaneous(),- box: DESKTOP,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const MissingEndTimes = meta.story({- args: {- roots: missingEndTimes(),- box: DESKTOP,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const ZeroDuration = meta.story({- args: {- roots: zeroDurationTrace(),- box: DESKTOP,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const CoarsePointer = meta.story({- args: {- roots: reporterTrace(),- box: DESKTOP,- pointer: "coarse",- compress: false,- composition: "split",- showReadout: true,- },-});--/** Every shape in the peek-width lane β the column that matters most. */-export const VariantMatrix = meta.story({- args: {- roots: reporterTrace(),- box: PEEK,- pointer: "fine",- compress: true,- composition: "split",- showReadout: true,- },- render: (args) => (- <div className="flex flex-wrap gap-4">- {Object.entries(TIMELINE_SHAPES).map(([shape, makeRoots]) => (- <div key={shape} className="flex flex-col gap-1">- <span className="text-muted-foreground text-xs">{shape}</span>- <TimelineV2 {...args} roots={makeRoots()} />- </div>- ))}- </div>- ),-});--export const FitsTheBox = meta.story({- name: "(Test) Fits The Box",- args: {- roots: reporterTrace(),- box: PEEK,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },- play: async ({ canvasElement }) => {- const scroll = canvasElement.querySelector<HTMLElement>(- '[data-testid="timeline-v2-scroll"]',- );- if (!scroll) throw new Error("timeline scroll container not found");-- // The invariant the community bug is about: nothing to scroll sideways to.- await expect(scroll.scrollWidth).toBeLessThanOrEqual(scroll.clientWidth);-- const lane = canvasElement.querySelector<HTMLElement>(- '[data-testid="timeline-v2-lane"]',- );- const bars = canvasElement.querySelectorAll<HTMLElement>(- '[data-testid="timeline-v2-bar"]',- );- if (!lane) throw new Error("timeline lane not found");- await expect(bars.length).toBeGreaterThan(0);-- const laneRect = lane.getBoundingClientRect();- for (const bar of bars) {- const rect = bar.getBoundingClientRect();- await expect(rect.left).toBeGreaterThanOrEqual(laneRect.left - 0.5);- await expect(rect.right).toBeLessThanOrEqual(laneRect.right + 0.5);- await expect(rect.width).toBeGreaterThan(0);- }- },-});--export const ClickSelectsARow = meta.story({- name: "(Test) Click Selects A Row",- args: {- roots: reporterTrace(),- box: PEEK,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },- play: async ({ canvasElement }) => {- const scroll = canvasElement.querySelector<HTMLElement>(- '[data-testid="timeline-v2-scroll"]',- );- const row = canvasElement.querySelector<HTMLElement>(- '[data-testid="timeline-v2-content"] > div',- );- if (!scroll || !row) throw new Error("timeline row not found");-- // Pointer capture retargets the derived click to the capture element, so- // capturing on pointerdown silently kills row selection. userEvent's- // synthetic events ignore capture and cannot see that, so assert the- // handler's contract directly: a press that does not move must not capture.- const captured: number[] = [];- scroll.setPointerCapture = (pointerId: number) => {- captured.push(pointerId);- };- const press = (type: string, clientX: number) =>- scroll.dispatchEvent(- new PointerEvent(type, { pointerId: 1, clientX, bubbles: true }),- );-- press("pointerdown", 100);- press("pointermove", 102);- press("pointerup", 102);- await expect(captured).toHaveLength(0);-- press("pointerdown", 100);- press("pointermove", 160);- await expect(captured).toHaveLength(1);- press("pointerup", 160);-- await userEvent.click(row);- await waitFor(() =>- expect(row.className).toContain("bg-primary-accent/10"),- );- },-});--export const DraggingMovesContentWithThePointer = meta.story({- name: "(Test) Dragging Moves Content With The Pointer",- args: {- roots: reporterTrace(),- box: PEEK,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },- play: async ({ canvasElement }) => {- const scroll = canvasElement.querySelector<HTMLElement>(- '[data-testid="timeline-v2-scroll"]',- );- if (!scroll) throw new Error("timeline scroll not found");- const readout = () =>- canvasElement.querySelector<HTMLElement>(- '[data-testid="timeline-v2-readout"]',- )?.textContent ?? "";- const viewStart = () => {- const match = /view (\d+)ms/.exec(readout());- if (!match) throw new Error(`no view window in "${readout()}"`);- return Number(match[1]);- };-- // Zoom into the LAST span to start, so the window has somewhere to go in- // both directions β zooming one that starts at the origin leaves the window- // pinned to 0 and a leftward drag with nothing to prove.- const bars = [- ...canvasElement.querySelectorAll<HTMLElement>(- '[data-testid="timeline-v2-bar"]',- ),- ];- const target = bars.reduce<HTMLElement | null>(- (latest, bar) =>- !latest ||- bar.getBoundingClientRect().left > latest.getBoundingClientRect().left- ? bar- : latest,- null,- );- if (!target) throw new Error("expected a bar to double-click");- await userEvent.dblClick(target);- await waitFor(() => expect(viewStart()).toBeGreaterThan(0));-- const pointer = (type: string, clientX: number, pointerId = 1) =>- scroll.dispatchEvent(- new PointerEvent(type, { pointerId, clientX, bubbles: true }),- );-- // Grab and drag RIGHT: the moment under the cursor has to come with it, which- // means the window moves EARLIER. The other sign slides the bars against the- // finger, which is the one thing a drag-to-pan must never do.- const startedAt = viewStart();- pointer("pointerdown", 200);- pointer("pointermove", 260);- pointer("pointerup", 260);- await waitFor(() => expect(viewStart()).toBeLessThan(startedAt));-- const afterDragRight = viewStart();- pointer("pointerdown", 260);- pointer("pointermove", 200);- pointer("pointerup", 200);- await waitFor(() => expect(viewStart()).toBeGreaterThan(afterDragRight));-- // Lifting one finger of a two-finger pinch leaves the gesture live. The- // survivor's next move must pan from where IT is, not jump by the finger- // separation it inherited from the finger that left.- const beforeRelease = viewStart();- pointer("pointerdown", 100, 1);- pointer("pointerdown", 260, 2);- pointer("pointerup", 260, 2);- // 1px is under the drag threshold, so re-anchored this does nothing at all;- // inheriting the departed finger's 260 makes it a 159px pan instead.- pointer("pointermove", 101, 1);- await expect(viewStart()).toBe(beforeRelease);- pointer("pointerup", 101, 1);- },-});--/**- * Compression and the box under the user's thumb, so a story can change either- * one mid-zoom β both replace the coordinate space a stored view addresses.- */-let resize: (width: number) => void = () => undefined;--function WithCompressionToggle(props: TimelineV2Props) {- const [compress, setCompress] = useState(props.compress);- const [width, setWidth] = useState(props.box.width);- resize = setWidth;- return (- <div className="flex flex-col items-start gap-1">- <button type="button" onClick={() => setCompress((on) => !on)}>- toggle compression- </button>- <TimelineV2- {...props}- compress={compress}- box={{ ...props.box, width }}- />- </div>- );-}--export const CompressionChangeDropsTheView = meta.story({- name: "(Test) Compression Change Drops The View",- args: {- roots: longTailTrace(),- box: PEEK,- pointer: "fine",- compress: true,- composition: "split",- showReadout: true,- },- render: (args) => <WithCompressionToggle {...args} />,- play: async ({ canvasElement }) => {- const readout = () =>- canvasElement.querySelector<HTMLElement>(- '[data-testid="timeline-v2-readout"]',- )?.textContent ?? "";-- const bars = canvasElement.querySelectorAll<HTMLElement>(- '[data-testid="timeline-v2-bar"]',- );- const target = bars[bars.length - 1];- if (!target) throw new Error("expected a bar to double-click");- // Zoom onto the last span, so the window starts well after the origin.- await expect(readout()).toContain("view 0msβ");- await userEvent.dblClick(target);- await waitFor(() => expect(readout()).not.toContain("view 0msβ"));-- // A zoomed window is expressed in COMPRESSED ms. Turning compression off- // replaces the space those numbers live in, so keeping them would draw an- // unrelated window instead of an obviously broken one.- const toggle = canvasElement.querySelector("button");- if (!toggle) throw new Error("expected the compression toggle");- await userEvent.click(toggle);- await waitFor(() => expect(readout()).toContain("view 0msβ"));-- // A RESIZE is the same hazard: collapsed gaps are priced in physical px, so- // a narrower box rescales the compressed space around a window that still- // addresses the old one.- await userEvent.click(toggle); // compression back on- const compressedBars = canvasElement.querySelectorAll<HTMLElement>(- '[data-testid="timeline-v2-bar"]',- );- const last = compressedBars[compressedBars.length - 1];- if (!last) throw new Error("expected a bar to zoom into");- await userEvent.dblClick(last);- await waitFor(() => expect(readout()).not.toContain("view 0msβ"));- resize(240);- await waitFor(() => expect(readout()).toContain("view 0msβ"));- },-});--export const DoubleClickingTheChevronDoesNotZoom = meta.story({- name: "(Test) Double Clicking The Chevron Does Not Zoom",- args: {- roots: reporterTrace(),- box: PEEK,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },- play: async ({ canvasElement }) => {- const readout = () =>- canvasElement.querySelector<HTMLElement>(- '[data-testid="timeline-v2-readout"]',- )?.textContent ?? "";- const chevron = canvasElement.querySelector<HTMLElement>(- 'button[aria-label="Collapse"], button[aria-label="Expand"]',- );- if (!chevron) throw new Error("expected a collapse chevron");-- const before = readout();- await userEvent.dblClick(chevron);- // Collapsing twice is a no-op you cannot see, so a jumped view would be the- // only visible result of an impatient click on the chevron.- await expect(readout()).toBe(before);- },-});--export const ZoomsToASpan = meta.story({- name: "(Test) Zooms To A Span",- args: {- roots: reporterTrace(),- box: PEEK,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },- play: async ({ canvasElement }) => {- const readout = () =>- canvasElement.querySelector<HTMLElement>(- '[data-testid="timeline-v2-readout"]',- )?.textContent ?? "";-- await expect(readout()).toContain("view 0msβ486ms");-- const bars = canvasElement.querySelectorAll<HTMLElement>(- '[data-testid="timeline-v2-bar"]',- );- const chatGroq = bars[4];- if (!chatGroq) throw new Error("expected a bar to double-click");- await userEvent.dblClick(chatGroq);-- // Double-tap-to-fit narrows the window instead of scrolling a canvas.- await waitFor(() => expect(readout()).not.toContain("view 0msβ486ms"));- },-});diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2.tsx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2.tsxdeleted file mode 100644index 301ad3bf1d..0000000000--- a/web/src/features/traces/components/TraceTimelineV2/TimelineV2.tsx+++ /dev/null@@ -1,813 +0,0 @@-/**- * Throwaway renderer for the size-adaptive timeline spike.- *- * Its only job is to make `layout()` visible: measured box in, absolutely- * placed boxes out. Every coordinate on screen comes from the pure function β- * no flex, no min-width and no intrinsic content sizing participates in where a- * bar lands. There is deliberately no horizontal scroll anywhere: the whole- * trace fits the box by default, and detail is reached by zooming the view.- *- * Not production code. Phase 2 lands this behind the real timeline entry point- * with selection, playhead and the resizable gutter kept working.- */--import {- useCallback,- useMemo,- useRef,- useState,- type PointerEvent as ReactPointerEvent,- type ReactNode,-} from "react";-import { useVirtualizer } from "@tanstack/react-virtual";-import { ChevronRight, Maximize2, Minus, Plus } from "lucide-react";-import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";-import { cn } from "@/src/utils/tailwind";-import {- detectPointerModality,- resolveDensity,- type PointerModality,-} from "../../fns/timeline/density";-import {- formatDurationMs,- layout,- prepareTimeline,- timeCompressionFor,- type LayoutNode,- type PositionedNode,-} from "../../fns/timeline/layout";-import { createTextMeasurer } from "../../fns/timeline/textMeasurer";-import {- fitView,- isFitted,- panView,- traceSpaceOf,- zoomToSpan,- zoomView,- type Box,- type TimeSpan,-} from "../../fns/timeline/viewTransform";--/**- * The four takes on "what happens to the name gutter below ~480px", so the- * design call can be made from renders instead of prose.- */-export type TimelineComposition =- /** Name gutter beside the chart, as today. */- | "split"- /** Gutter collapses to the type icon and the depth rail. */- | "icons"- /** No gutter: names ride on top of the bars. */- | "overlay"- /** No gutter: name above, bar below, both full width. */- | "stacked"- /** Full-width tree or full-width timeline, one at a time. */- | "modes";--export type TimelineV2Props = {- roots: LayoutNode[];- /** The measured box. Required β there is no fallback canvas width. */- box: Box;- /** `null` resolves from `(pointer: coarse)` once, on mount. */- pointer: PointerModality | null;- compress: boolean;- composition: TimelineComposition;- /** View window + scale readout under the chart; the spike's instrument panel. */- showReadout: boolean;-};--const FRAME_BORDER = 1;-const TOOLBAR_HEIGHT = 30;-const AXIS_HEIGHT = 20;-const READOUT_HEIGHT = 18;-const GUTTER_INDENT = 10;-const GUTTER_MAX_DEPTH = 6;-const ICON_GUTTER_WIDTH = 46;-const ZOOM_STEP = 1.6;-/** Movement before a press becomes a pan rather than a click. */-const DRAG_THRESHOLD_PX = 4;--export function TimelineV2({- roots,- box,- pointer,- compress,- composition,- showReadout,-}: TimelineV2Props) {- const [detectedPointer] = useState(detectPointerModality);- const [view, setView] = useState<TimeSpan | null>(null);- const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(- () => new Set<string>(),- );- const [selectedId, setSelectedId] = useState<string | null>(null);- const [mode, setMode] = useState<"tree" | "timeline">("timeline");-- const modality = pointer ?? detectedPointer;- const prepared = useMemo(- () => prepareTimeline(roots, collapsed),- [roots, collapsed],- );-- // The scroll viewport's own client box, not an arithmetic guess at it. The- // guess was wrong by the frame border and again by the scrollbar β two- // constants the math would never have seen, which is the whole failure mode- // this renderer exists to remove. Measure first; everything below derives.- const [viewport, setViewport] = useState<Box | null>(null);- const estimated = {- width: Math.max(box.width - FRAME_BORDER * 2, 0),- height: Math.max(- box.height -- FRAME_BORDER * 2 -- TOOLBAR_HEIGHT -- AXIS_HEIGHT -- (showReadout ? READOUT_HEIGHT : 0),- 0,- ),- };- const contentWidth = viewport?.width ?? estimated.width;- const viewportHeight = viewport?.height ?? estimated.height;-- const gutterWidth = resolveGutterWidth({ composition, contentWidth, mode });- const chartWidth = Math.max(contentWidth - gutterWidth, 0);- const chartBox = useMemo(- () => ({ width: chartWidth, height: viewportHeight }),- [chartWidth, viewportHeight],- );-- const density = useMemo(- () =>- resolveDensity({- pointer: modality,- lines: composition === "stacked" ? 2 : 1,- }),- [modality, composition],- );- const measurer = useMemo(- () => createTextMeasurer(`${density.labelFontPx}px ui-sans-serif`),- [density.labelFontPx],- );- const compression = useMemo(- () => timeCompressionFor(prepared, chartBox, compress),- [prepared, chartBox, compress],- );-- // The view is a window in COMPRESSED ms, so it only means anything relative to- // the compression that produced it. Switch trace or switch compression off and- // the stored numbers quietly address somewhere else β layout() clamps them into- // the new space and draws an unrelated window rather than an obviously broken- // one. So the window is dropped when the space it belongs to is replaced;- // fitted is the only view that means the same thing in every space.- //- // Compressed duration is part of that identity, not just the flags: collapsed- // gaps are priced in PHYSICAL px (`min(28, width / (gaps + 1))`), so resizing- // the pane while zoomed in with compression on rescales the whole space around- // a window that still addresses the old one. Collapsing a node is deliberately- // not in the key β it changes which rows exist, not what a ms means.- const spaceKey = `${compress}:${compression.compressedDurationMs}`;- const spaceRef = useRef({ roots, spaceKey });- if (- spaceRef.current.roots !== roots ||- spaceRef.current.spaceKey !== spaceKey- ) {- spaceRef.current = { roots, spaceKey };- if (view !== null) setView(null);- }-- const scrollRef = useRef<HTMLDivElement | null>(null);- const virtualizer = useVirtualizer({- count: prepared.rows.length,- getScrollElement: () => scrollRef.current,- estimateSize: () => density.rowHeight,- overscan: 6,- // Key by node id, not index: an index-keyed cache and id-keyed DOM drift- // apart the moment rows are collapsed away.- getItemKey: (index) => prepared.rows[index]?.node.id ?? index,- });-- const virtualItems = virtualizer.getVirtualItems();- const rowRange = virtualItems.length- ? {- startIndex: virtualItems[0]!.index,- endIndex: virtualItems[virtualItems.length - 1]!.index,- }- : // Before the virtualizer has measured its scroll element, fill the box.- {- startIndex: 0,- endIndex: Math.ceil(viewportHeight / density.rowHeight) + 1,- };-- const result = layout({- roots,- box: chartBox,- density,- measurer,- view,- compress,- prepared,- compression,- rowRange,- });-- const traceSpace = useMemo(- () => traceSpaceOf(compression.compressedDurationMs),- [compression.compressedDurationMs],- );- const fitted = isFitted(result.view, traceSpace);- const viewStartMs = compression.toRealMs(result.view.start);- const viewEndMs = compression.toRealMs(- result.view.start + result.view.duration,- );-- const zoomBy = useCallback(- (factor: number, anchorRatio: number) =>- setView((current) =>- zoomView(current ?? fitView(traceSpace), traceSpace, {- factor,- anchorRatio,- }),- ),- [traceSpace],- );-- /**- * `deltaPx` is how far the CONTENT moves, so the grabbed moment stays under- * the pointer: dragging right shows earlier time, which means the window start- * goes DOWN. Without the negation the bars slid the opposite way to the finger- * β and to the wheel, whose caller negates the scroll delta for the same- * reason.- */- const panBy = useCallback(- (deltaPx: number) =>- setView((current) => {- const from = current ?? fitView(traceSpace);- const pxPerMs = chartWidth > 0 ? chartWidth / from.duration : 0;- return panView(from, traceSpace, pxPerMs > 0 ? -deltaPx / pxPerMs : 0);- }),- [traceSpace, chartWidth],- );-- /**- * The viewport ref does two things React cannot express declaratively: a- * non-passive wheel listener (React's own onWheel is passive, so it cannot- * stop the page scrolling during a zoom) and a ResizeObserver for the- * measured box. Both are external browser systems, wired through React 19's- * ref cleanup rather than an effect.- */- const attachViewport = useCallback(- (element: HTMLDivElement | null) => {- scrollRef.current = element;- if (!element) return;-- const measure = () =>- setViewport((current) =>- current?.width === element.clientWidth &&- current?.height === element.clientHeight- ? current- : { width: element.clientWidth, height: element.clientHeight },- );- const observer = new ResizeObserver(measure);- observer.observe(element);- measure();-- const onWheel = (event: WheelEvent) => {- const zooming = event.ctrlKey || event.metaKey;- const panning = !zooming && (event.shiftKey || event.deltaX !== 0);- if (!zooming && !panning) return; // plain wheel scrolls the row list-- event.preventDefault();- if (zooming) {- const rect = element.getBoundingClientRect();- const anchorRatio =- chartWidth > 0- ? (event.clientX - rect.left - gutterWidth) / chartWidth- : 0.5;- zoomBy(event.deltaY < 0 ? ZOOM_STEP : 1 / ZOOM_STEP, anchorRatio);- } else {- panBy(-(event.deltaX || event.deltaY));- }- };-- element.addEventListener("wheel", onWheel, { passive: false });- return () => {- observer.disconnect();- element.removeEventListener("wheel", onWheel);- };- },- [chartWidth, gutterWidth, zoomBy, panBy],- );-- const gesture = useRef<{- pointers: Map<number, number>;- startX: number;- lastX: number;- pinchDistance: number;- dragging: boolean;- }>({- pointers: new Map(),- startX: 0,- lastX: 0,- pinchDistance: 0,- dragging: false,- });-- const onPointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {- gesture.current.pointers.set(event.pointerId, event.clientX);- gesture.current.startX = event.clientX;- gesture.current.lastX = event.clientX;- gesture.current.dragging = false;- if (gesture.current.pointers.size === 2) {- const [a, b] = [...gesture.current.pointers.values()];- gesture.current.pinchDistance = Math.abs((a ?? 0) - (b ?? 0));- }- // Deliberately NOT capturing here. Pointer capture retargets the derived- // `click` to the capture element, so capturing on pointerdown means a plain- // click lands on this scroll container and no row is ever selected.- // Capture is taken on the first move past DRAG_THRESHOLD_PX instead, which- // also gives us "a drag does not select" for free.- };-- const onPointerMove = (event: ReactPointerEvent<HTMLDivElement>) => {- const state = gesture.current;- if (!state.pointers.has(event.pointerId)) return;- state.pointers.set(event.pointerId, event.clientX);-- if (state.pointers.size >= 2) {- const [a, b] = [...state.pointers.values()];- const distance = Math.abs((a ?? 0) - (b ?? 0));- if (state.pinchDistance > 0 && distance > 0) {- const rect = event.currentTarget.getBoundingClientRect();- const midpoint = ((a ?? 0) + (b ?? 0)) / 2 - rect.left - gutterWidth;- zoomBy(- distance / state.pinchDistance,- chartWidth > 0 ? midpoint / chartWidth : 0.5,- );- }- state.pinchDistance = distance;- return;- }-- if (!state.dragging) {- if (Math.abs(event.clientX - state.startX) < DRAG_THRESHOLD_PX) return;- state.dragging = true;- // Now that this really is a drag, capture so it survives leaving the box.- event.currentTarget.setPointerCapture(event.pointerId);- }-- panBy(event.clientX - state.lastX);- state.lastX = event.clientX;- };-- const onPointerUp = (event: ReactPointerEvent<HTMLDivElement>) => {- const state = gesture.current;- state.pointers.delete(event.pointerId);- state.pinchDistance = 0;- state.dragging = false;- // Lifting one finger of a pinch does not end the gesture, and startX/lastX- // still hold where the OTHER finger went down β so the survivor's next small- // move would clear the drag threshold at once and pan by the whole finger- // separation. Re-anchor both on the finger that is still there.- const survivor = state.pointers.values().next().value;- if (survivor !== undefined) {- state.startX = survivor;- state.lastX = survivor;- }- };-- const toggleCollapsed = (id: string) =>- setCollapsed((current) => {- const next = new Set(current);- if (next.has(id)) next.delete(id);- else next.add(id);- return next;- });-- /** Double-tap a bar to fit it; double-tap again to go back to the whole trace. */- const zoomToNode = (node: PositionedNode) => {- const target = {- start: compression.toCompressedMs(node.startMs),- duration: Math.max(- compression.toCompressedMs(node.endMs) -- compression.toCompressedMs(node.startMs),- 0,- ),- };- setView((current) => {- const next = zoomToSpan(target, traceSpace);- const isAlreadyThere =- current != null &&- Math.abs(current.start - next.start) < 1 &&- Math.abs(current.duration - next.duration) < 1;- return isAlreadyThere ? null : next;- });- };-- const showGutter = gutterWidth > 0;- const showChart = chartWidth > 0;-- return (- <div- className="bg-background border-border text-foreground flex flex-col overflow-hidden rounded border"- style={{ width: `${box.width}px`, height: `${box.height}px` }}- >- <div- className="border-border flex shrink-0 items-center gap-1 border-b px-1"- style={{ height: `${TOOLBAR_HEIGHT}px` }}- >- {composition === "modes" ? (- <div className="flex gap-0.5">- {(["tree", "timeline"] as const).map((candidate) => (- <button- key={candidate}- type="button"- onClick={() => setMode(candidate)}- className={cn(- "rounded px-2 py-0.5 text-xs capitalize",- mode === candidate ? "bg-muted" : "hover:bg-muted/60",- )}- >- {candidate}- </button>- ))}- </div>- ) : null}- <ToolbarButton- label="Zoom out"- onClick={() => zoomBy(1 / ZOOM_STEP, 0.5)}- >- <Minus className="h-3 w-3" />- </ToolbarButton>- <ToolbarButton label="Zoom in" onClick={() => zoomBy(ZOOM_STEP, 0.5)}>- <Plus className="h-3 w-3" />- </ToolbarButton>- <ToolbarButton label="Fit whole trace" onClick={() => setView(null)}>- <Maximize2 className="h-3 w-3" />- </ToolbarButton>- <span- className="text-muted-foreground truncate text-xs"- title="Zoom state"- >- {fitted- ? "whole trace"- : `${formatDurationMs(viewEndMs - viewStartMs)} window`}- </span>- </div>-- <div- className="border-border relative shrink-0 border-b"- style={{ height: `${AXIS_HEIGHT}px` }}- >- {showChart ? (- <div- className="absolute inset-y-0"- style={{ left: `${gutterWidth}px`, width: `${chartWidth}px` }}- >- {result.ticks.map((tick) => (- <div- key={tick.realMs}- className="border-border-contrast absolute inset-y-0 border-l"- style={{ left: `${tick.x}px` }}- >- <span- className="text-muted-foreground absolute top-0.5 left-1 whitespace-nowrap"- style={{ fontSize: `${density.labelFontPx - 1}px` }}- >- {tick.label}- </span>- </div>- ))}- </div>- ) : null}- </div>-- <div className="relative min-h-0 flex-1">- {showChart ? (- <div- className="pointer-events-none absolute inset-y-0"- style={{ left: `${gutterWidth}px`, width: `${chartWidth}px` }}- >- {result.ticks.map((tick) => (- <div- key={tick.realMs}- className="border-border/40 absolute inset-y-0 border-l"- style={{ left: `${tick.x}px` }}- />- ))}- {result.gaps.map((gap) => (- <div- key={`${gap.x}-${gap.durationMs}`}- className="bg-muted border-border-contrast absolute inset-y-0 flex items-center justify-center border-x border-dashed"- style={{ left: `${gap.x}px`, width: `${gap.width}px` }}- title={`${gap.label} of idle time, collapsed`}- >- <span- className="text-muted-foreground"- style={{ fontSize: `${density.labelFontPx}px` }}- >- β―- </span>- </div>- ))}- </div>- ) : null}-- <div- ref={attachViewport}- className="h-full overflow-x-hidden overflow-y-auto"- data-testid="timeline-v2-scroll"- style={{ touchAction: "pan-y" }}- onPointerDown={showChart ? onPointerDown : undefined}- onPointerMove={showChart ? onPointerMove : undefined}- onPointerUp={onPointerUp}- onPointerCancel={onPointerUp}- >- <div- className="relative"- style={{ height: `${result.contentHeight}px` }}- data-testid="timeline-v2-content"- >- {result.nodes.map((node) => (- <div- key={node.id}- className={cn(- // select-none: the whole row is a click target (select, and- // double-click to fit), so dragging over it must not select- // the names and duration labels it is made of.- // `group` so hovering anywhere in the row recolours its bar.- // transition-COLORS only β a bare `transition` would also ease- // left/width and make zoom lag a frame behind the gesture.- "group absolute inset-x-0 flex cursor-pointer items-center transition-colors duration-150 select-none",- // Selected takes an accent tint rather than a deeper neutral:- // the bars are bg-muted, so a neutral selected row swallows- // them. Hover is the neutral one.- selectedId === node.id- ? "bg-primary-accent/10"- : "hover:bg-muted",- )}- style={{ top: `${node.y}px`, height: `${node.height}px` }}- onClick={() => setSelectedId(node.id)}- onDoubleClick={() => zoomToNode(node)}- >- {selectedId === node.id ? (- <div className="bg-primary-accent absolute inset-y-0 left-0 w-0.5" />- ) : null}- {showGutter ? (- <GutterCell- node={node}- width={gutterWidth}- compact={composition === "icons"}- fontPx={density.labelFontPx}- isSelected={selectedId === node.id}- onToggleCollapsed={() => toggleCollapsed(node.id)}- />- ) : null}- {showChart ? (- <ChartCell- node={node}- width={chartWidth}- barHeight={density.barHeight}- fontPx={density.labelFontPx}- nameMode={- composition === "overlay"- ? "overlay"- : composition === "stacked"- ? "stacked"- : "none"- }- isSelected={selectedId === node.id}- />- ) : null}- </div>- ))}- </div>- </div>- </div>-- {showReadout ? (- <div- className="border-border text-muted-foreground flex shrink-0 items-center gap-2 overflow-hidden border-t px-1 whitespace-nowrap"- style={{ height: `${READOUT_HEIGHT}px`, fontSize: "10px" }}- data-testid="timeline-v2-readout"- >- <span>- {box.width}Γ{box.height} Β· gutter {gutterWidth} Β· lane {chartWidth}- </span>- <span>- view {formatDurationMs(viewStartMs)}β{formatDurationMs(viewEndMs)}- </span>- <span>{result.pxPerMs.toFixed(3)} px/ms</span>- <span>- {result.rowCount} rows @ {density.rowHeight}px ({modality})- </span>- {compression.enabled ? (- <span>{compression.gaps.length} gaps collapsed</span>- ) : null}- </div>- ) : null}- </div>- );-}--function resolveGutterWidth(args: {- composition: TimelineComposition;- contentWidth: number;- mode: "tree" | "timeline";-}): number {- const { composition, contentWidth, mode } = args;- if (composition === "overlay" || composition === "stacked") return 0;- if (composition === "icons") return Math.min(ICON_GUTTER_WIDTH, contentWidth);- if (composition === "modes") return mode === "tree" ? contentWidth : 0;- return Math.round(Math.min(Math.max(contentWidth * 0.4, 96), 280));-}--function ToolbarButton({- label,- onClick,- children,-}: {- label: string;- onClick: () => void;- children: ReactNode;-}) {- return (- <button- type="button"- aria-label={label}- title={label}- onClick={onClick}- className="hover:bg-muted flex h-5 w-5 items-center justify-center rounded"- >- {children}- </button>- );-}--function GutterCell({- node,- width,- compact,- fontPx,- isSelected,- onToggleCollapsed,-}: {- node: PositionedNode;- width: number;- compact: boolean;- fontPx: number;- isSelected: boolean;- onToggleCollapsed: () => void;-}) {- // Depth indentation is capped so a 20-level trace still leaves room for names.- const indent = Math.min(node.depth, GUTTER_MAX_DEPTH) * GUTTER_INDENT;-- return (- <div- className="flex h-full shrink-0 items-center gap-1 overflow-hidden pr-1"- style={{ width: `${width}px`, paddingLeft: `${indent + 2}px` }}- >- {node.hasChildren ? (- <button- type="button"- aria-label={node.isCollapsed ? "Expand" : "Collapse"}- aria-expanded={!node.isCollapsed}- onClick={(event) => {- event.stopPropagation();- onToggleCollapsed();- }}- // The row zooms to its span on double-click. Collapsing twice in- // quick succession is a no-op the user cannot see, so without this the- // only visible outcome of an impatient click is the view jumping.- onDoubleClick={(event) => event.stopPropagation()}- className="hover:bg-muted-foreground/10 flex h-4 w-4 shrink-0 items-center justify-center rounded"- >- <ChevronRight- className={cn("h-3 w-3", !node.isCollapsed && "rotate-90")}- />- </button>- ) : (- <span className="w-4 shrink-0" />- )}- <span className="shrink-0">- <ItemBadge type={node.type as LangfuseItemType} isSmall />- </span>- {compact ? null : (- <span- className={cn("truncate", isSelected && "font-bold")}- style={{ fontSize: `${fontPx}px` }}- title={node.name}- >- {node.name}- </span>- )}- </div>- );-}--function ChartCell({- node,- width,- barHeight,- fontPx,- nameMode,- isSelected,-}: {- node: PositionedNode;- width: number;- barHeight: number;- fontPx: number;- nameMode: "none" | "overlay" | "stacked";- isSelected: boolean;-}) {- return (- <div- className="relative h-full shrink-0 overflow-hidden"- style={{ width: `${width}px` }}- data-testid="timeline-v2-lane"- >- {node.offscreen ? null : (- <>- <div- className={cn(- "absolute border transition-colors duration-150",- nameMode === "stacked" ? "bottom-1" : "top-1/2 -translate-y-1/2",- node.durationMs == null && "border-dashed",- !node.clippedLeft && "rounded-l-sm",- !node.clippedRight && "rounded-r-sm",- // The bar itself takes the focus colour on row hover, and a- // stronger fill plus a ring when the row is the selected one.- isSelected- ? "bg-primary-accent/40 border-primary-accent ring-primary-accent ring-2"- : "bg-muted border-border group-hover:bg-primary-accent/25 group-hover:border-primary-accent/40",- )}- style={{- left: `${node.x}px`,- width: `${node.width}px`,- height: `${barHeight}px`,- }}- data-testid="timeline-v2-bar"- />- {node.firstTokenX == null ? null : (- <div- className={cn(- "bg-border-contrast absolute w-px",- nameMode === "stacked"- ? "bottom-1"- : "top-1/2 -translate-y-1/2",- )}- style={{- left: `${node.firstTokenX}px`,- height: `${barHeight}px`,- }}- title="Time to first token"- />- )}- {node.labelPlacement === "hidden" ? null : (- <span- className={cn(- "absolute whitespace-nowrap",- nameMode === "stacked"- ? "bottom-1"- : "top-1/2 -translate-y-1/2",- node.labelPlacement === "inside"- ? "text-foreground"- : "text-muted-foreground",- )}- style={{- left: `${node.labelX}px`,- maxWidth: `${Math.max(width - node.labelX, 0)}px`,- fontSize: `${fontPx}px`,- }}- >- {node.label}- </span>- )}- </>- )}- {nameMode === "overlay" ? (- // Names ride over the bars: a gradient keeps them readable without- // stealing a column from the chart.- <span- className="from-background via-background/90 pointer-events-none absolute top-1/2 left-1 max-w-[70%] -translate-y-1/2 truncate bg-gradient-to-r to-transparent pr-3"- style={{ fontSize: `${fontPx}px` }}- title={node.name}- >- {node.name}- </span>- ) : null}- {nameMode === "stacked" ? (- // Name above, bar below: the chart keeps the full width and the name- // keeps its full length, at the cost of a taller row.- <span- className="text-foreground pointer-events-none absolute top-0 right-1 truncate"- style={{- left: `${Math.min(node.depth, GUTTER_MAX_DEPTH) * GUTTER_INDENT + 4}px`,- fontSize: `${fontPx}px`,- }}- title={node.name}- >- {node.name}- </span>- ) : null}- </div>- );-}diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2Compression.stories.tsx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2Compression.stories.tsxdeleted file mode 100644index 78c1681557..0000000000--- a/web/src/features/traces/components/TraceTimelineV2/TimelineV2Compression.stories.tsx+++ /dev/null@@ -1,74 +0,0 @@-import preview from "../../../../../.storybook/preview";-import { TimelineV2 } from "./TimelineV2";-import {- longTailTrace,- manySpans,-} from "../../fns/timeline/__tests__/timelineV2.fixtures";--const meta = preview.meta({- component: TimelineV2,-});--const PEEK = { width: 320, height: 260 };-const DESKTOP = { width: 1280, height: 360 };--/**- * One 36s span, three 40ms spans. Fitted honestly the work is invisible;- * compressed it is legible but the axis no longer reads linearly. Both halves- * of the trade-off, same shape, same box.- */-export const LongTailHonest = meta.story({- args: {- roots: longTailTrace(),- box: PEEK,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const LongTailCompressed = meta.story({- args: {- roots: longTailTrace(),- box: PEEK,- pointer: "fine",- compress: true,- composition: "split",- showReadout: true,- },-});--export const LongTailHonestWide = meta.story({- args: {- roots: longTailTrace(),- box: DESKTOP,- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const LongTailCompressedWide = meta.story({- args: {- roots: longTailTrace(),- box: DESKTOP,- pointer: "fine",- compress: true,- composition: "split",- showReadout: true,- },-});--/** A dense trace with no real idle stretch: compression should do nothing. */-export const DenseTraceCompressed = meta.story({- args: {- roots: manySpans(500),- box: DESKTOP,- pointer: "fine",- compress: true,- composition: "split",- showReadout: true,- },-});diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2Mobile.stories.tsx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2Mobile.stories.tsxdeleted file mode 100644index 19c31e07a6..0000000000--- a/web/src/features/traces/components/TraceTimelineV2/TimelineV2Mobile.stories.tsx+++ /dev/null@@ -1,97 +0,0 @@-import preview from "../../../../../.storybook/preview";-import { TimelineV2, type TimelineComposition } from "./TimelineV2";-import { reporterTrace } from "../../fns/timeline/__tests__/timelineV2.fixtures";--const meta = preview.meta({- component: TimelineV2,-});--/**- * Fit-to-box fixes the time axis. What still breaks below ~480px is the name- * gutter and the chart sharing one row, so these are the takes on that.- */-const PHONE = { width: 320, height: 300 };-const COMPOSITIONS: TimelineComposition[] = [- "split",- "icons",- "overlay",- "stacked",- "modes",-];--export const GutterAndChart = meta.story({- args: {- roots: reporterTrace(),- box: PHONE,- pointer: "coarse",- compress: false,- composition: "split",- showReadout: true,- },-});--export const IconGutter = meta.story({- args: {- roots: reporterTrace(),- box: PHONE,- pointer: "coarse",- compress: false,- composition: "icons",- showReadout: true,- },-});--export const NamesOverBars = meta.story({- args: {- roots: reporterTrace(),- box: PHONE,- pointer: "coarse",- compress: false,- composition: "overlay",- showReadout: true,- },-});--export const NameAboveBar = meta.story({- args: {- roots: reporterTrace(),- box: PHONE,- pointer: "coarse",- compress: false,- composition: "stacked",- showReadout: true,- },-});--export const ModeToggle = meta.story({- args: {- roots: reporterTrace(),- box: PHONE,- pointer: "coarse",- compress: false,- composition: "modes",- showReadout: true,- },-});--/** All four takes side by side, at touch density. */-export const VariantMatrix = meta.story({- args: {- roots: reporterTrace(),- box: PHONE,- pointer: "coarse",- compress: false,- composition: "split",- showReadout: true,- },- render: (args) => (- <div className="flex flex-wrap gap-4">- {COMPOSITIONS.map((composition) => (- <div key={composition} className="flex flex-col gap-1">- <span className="text-muted-foreground text-xs">{composition}</span>- <TimelineV2 {...args} composition={composition} />- </div>- ))}- </div>- ),-});diff --git a/web/src/features/traces/components/TraceTimelineV2/TimelineV2Sizes.stories.tsx b/web/src/features/traces/components/TraceTimelineV2/TimelineV2Sizes.stories.tsxdeleted file mode 100644index c62c808c40..0000000000--- a/web/src/features/traces/components/TraceTimelineV2/TimelineV2Sizes.stories.tsx+++ /dev/null@@ -1,144 +0,0 @@-import preview from "../../../../../.storybook/preview";-import { TimelineV2 } from "./TimelineV2";-import { reporterTrace } from "../../fns/timeline/__tests__/timelineV2.fixtures";--const meta = preview.meta({- component: TimelineV2,-});--/** The five review widths; short and tall so density resolution is visible too. */-const WIDTHS = [320, 480, 768, 1280, 1920];-const SHORT = 220;-const TALL = 560;--export const Narrow320Short = meta.story({- args: {- roots: reporterTrace(),- box: { width: 320, height: SHORT },- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const Narrow320Tall = meta.story({- args: {- roots: reporterTrace(),- box: { width: 320, height: TALL },- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const Mobile480Short = meta.story({- args: {- roots: reporterTrace(),- box: { width: 480, height: SHORT },- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const Mobile480Tall = meta.story({- args: {- roots: reporterTrace(),- box: { width: 480, height: TALL },- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const Tablet768Short = meta.story({- args: {- roots: reporterTrace(),- box: { width: 768, height: SHORT },- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const Tablet768Tall = meta.story({- args: {- roots: reporterTrace(),- box: { width: 768, height: TALL },- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const Desktop1280Short = meta.story({- args: {- roots: reporterTrace(),- box: { width: 1280, height: SHORT },- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const Desktop1280Tall = meta.story({- args: {- roots: reporterTrace(),- box: { width: 1280, height: TALL },- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const Wide1920Short = meta.story({- args: {- roots: reporterTrace(),- box: { width: 1920, height: SHORT },- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--export const Wide1920Tall = meta.story({- args: {- roots: reporterTrace(),- box: { width: 1920, height: TALL },- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },-});--/** Every width at once: the same trace, whole, in each box. */-export const VariantMatrix = meta.story({- args: {- roots: reporterTrace(),- box: { width: 320, height: 300 },- pointer: "fine",- compress: false,- composition: "split",- showReadout: true,- },- render: (args) => (- <div className="flex flex-col gap-4">- {WIDTHS.map((width) => (- <div key={width} className="flex flex-col gap-1">- <span className="text-muted-foreground text-xs">{width}px</span>- <TimelineV2 {...args} box={{ width, height: 300 }} />- </div>- ))}- </div>- ),-});diff --git a/web/src/features/traces/fns/timeline/__tests__/timelineV2.fixtures.ts b/web/src/features/traces/fns/timeline/__tests__/timelineV2.fixtures.tsindex a7867c60d9..d567b7a5fc 100644--- a/web/src/features/traces/fns/timeline/__tests__/timelineV2.fixtures.ts+++ b/web/src/features/traces/fns/timeline/__tests__/timelineV2.fixtures.ts@@ -194,7 +194,7 @@ export const longTailTrace = (): LayoutNode[] =>},]);-export const allInstantaneous = (): LayoutNode[] =>+const allInstantaneous = (): LayoutNode[] =>build([{name: "fanout",@@ -208,7 +208,7 @@ export const allInstantaneous = (): LayoutNode[] =>},]);-export const missingEndTimes = (): LayoutNode[] =>+const missingEndTimes = (): LayoutNode[] =>build([{name: "in-flight-run",@@ -227,7 +227,7 @@ export const missingEndTimes = (): LayoutNode[] =>]);/** Single instantaneous span: the fully collapsed trace. */-export const zeroDurationTrace = (): LayoutNode[] =>+const zeroDurationTrace = (): LayoutNode[] =>build([{ name: "ping", startMs: 0, durationMs: 0 }]);/**diff --git a/web/src/features/traces/fns/timeline/layout.clienttest.ts b/web/src/features/traces/fns/timeline/layout.clienttest.tsindex 6896d49e19..4c11fab14d 100644--- a/web/src/features/traces/fns/timeline/layout.clienttest.ts+++ b/web/src/features/traces/fns/timeline/layout.clienttest.ts@@ -307,53 +307,6 @@ describe("textMeasurer", () => {expect(measure("abc")).toBeCloseTo(60, 6);});- it("reads the SIZE out of a weighted font, not the weight", () => {- // The bold twin asks for `700 20px β¦`. Reading the leading number takes 700,- // which against a context reporting 10px scales every width by seventy.- const stubborn = {- measureText: (text: string) =>- ({ width: text.length * 10 }) as TextMetrics,- };- Object.defineProperty(stubborn, "font", {- get: () => "10px sans-serif",- set: () => undefined,- });- const measurer = createTextMeasurerFrom(- stubborn as unknown as CanvasRenderingContext2D,- "20px test",- );- // Bold asks for the same 20px, so it corrects by two β never by seventy.- expect(measurer.measureBold("abc")).toBeCloseTo(60, 6);- });-- it("measures bold wider than regular, and neither twin sets the other's font", () => {- // Width follows the FONT this context was last given, so an interleaved call- // that forgot to set it reads as the other weight β which is the bug: both- // twins share one canvas, and the run measurement happens lazily at measure- // time rather than when the twin was built.- const byWeight: {- font: string;- measureText: (text: string) => TextMetrics;- } = {- font: "",- measureText: (text: string) =>- ({- width: text.length * (byWeight.font.startsWith("700") ? 20 : 10),- }) as TextMetrics,- };- const measurer = createTextMeasurerFrom(- byWeight as unknown as CanvasRenderingContext2D,- "12px test",- );-- expect(measurer.measure("abc")).toBeCloseTo(30, 6);- expect(measurer.measureBold("abc")).toBeCloseTo(60, 6);- // Interleaved, and each still its own weight.- expect(measurer.measure("abcd")).toBeCloseTo(40, 6);- expect(measurer.measureBold("abcd")).toBeCloseTo(80, 6);- expect(measurer.measure("ab")).toBeCloseTo(20, 6);- });-it("falls back to a flat per-letter width with no canvas", () => {expect(createTextMeasurerFrom(null).measure("1m 35s")).toBeCloseTo(6 * PX_PER_LETTER,diff --git a/web/src/features/traces/fns/timeline/layout.ts b/web/src/features/traces/fns/timeline/layout.tsindex 72d1bd5b8e..c8e34f91fb 100644--- a/web/src/features/traces/fns/timeline/layout.ts+++ b/web/src/features/traces/fns/timeline/layout.ts@@ -108,7 +108,7 @@ export type PositionedNode<TNode extends LayoutNode = LayoutNode> = {endMs: number;};-export type Tick = { realMs: number; x: number; label: string };+type Tick = { realMs: number; x: number; label: string };type GapMarker = {x: number;@@ -175,7 +175,7 @@ const TICK_LABEL_PADDING_PX = 16;/** The tick line itself β a `border-l`, which the label is positioned inside of. */const TICK_LINE_PX = 1;/** The gap between that line and its label. */-export const TICK_LABEL_GAP_PX = 4;+const TICK_LABEL_GAP_PX = 4;/*** What a label costs to the right of its tick's `x`: the line, then the gap.* Derived rather than written down, and exported, because the renderer positions@@ -188,7 +188,7 @@ export const TICK_LABEL_GAP_PX = 4;* then gets truncated by its clamp. A reservation that does not match the render* is wrong even when it errs safely, because nothing says which way it errs next.*/-export const TICK_LABEL_INSET_PX = TICK_LINE_PX + TICK_LABEL_GAP_PX;+const TICK_LABEL_INSET_PX = TICK_LINE_PX + TICK_LABEL_GAP_PX;// Nice tick steps in ms. Above a minute they land on time-nice boundaries so// hour-scale traces get clean labels instead of "1500s".diff --git a/web/src/features/traces/fns/timeline/metricCluster.ts b/web/src/features/traces/fns/timeline/metricCluster.tsdeleted file mode 100644index d966bba0ca..0000000000--- a/web/src/features/traces/fns/timeline/metricCluster.ts+++ /dev/null@@ -1,219 +0,0 @@-/**- * What a row's metric cluster COSTS, in px, measured rather than guessed.- *- * A cluster is the duration, the subtree total, the cost, a comment icon and the- * score badges, laid beside a bar in whatever room the lane has left. The box it- * lives in clips, so a reservation that comes out under what the DOM renders- * cuts the last item mid-glyph β which is why every number here is measured from- * the thing it is paying for, and why the widest candidates are priced rather- * than the likeliest: over-reserving drops a badge and says so in the row's- * title, under-reserving clips one and says nothing.- *- * Pure and shared, because two renderers place this cluster and a second copy of- * the arithmetic is a second chance to get it wrong.- */--import { groupScoresByName } from "@/src/components/grouped-score-badge";-import {- SCORE_LEVEL_LABELS,- scoreLevelFromScore,-} from "@/src/components/score-tag";-import { type TextMeasurer } from "./textMeasurer";-import type { ScoreDomain } from "@langfuse/shared";-import type { WithStringifiedMetadata } from "@/src/utils/clientSideDomainTypes";--/** The score shape the badges render, and therefore the one this prices. */-type ClusterScore = WithStringifiedMetadata<ScoreDomain>;--/**- * The cluster's own `gap-2`. The budget has to reserve the gap the cluster- * actually renders with, not a smaller one: five admitted items multiply a 2px- * under-reservation into a clipped last item.- */-export const CLUSTER_ITEM_GAP_PX = 8;-/** The speech bubble of a comment icon, plus its own `mr-1`. */-const ICON_GLYPH_PX = 20;-/** Its count badge overlaps the bubble by `-ml-2`, so only the rest is width. */-const ICON_BADGE_OVERLAP_PX = 7;-/** `px-[0.2rem]` both sides plus the badge's 1px border. */-const ICON_BADGE_CHROME_PX = 8;-/** `min-w-[0.8rem]` floors a single digit. */-const ICON_BADGE_MIN_PX = 12;--/**- * A comment icon is its bubble plus a count badge, and the badge grows with the- * count β 99 comments is wider than 9, and "99+" wider again. A flat number for- * "an icon" under-reserved every 2-digit count, which is the direction that- * clips: the badge is in the flow now, so what it takes is what it takes.- *- * The digits are measured at the cluster's own font, a little larger than the- * badge's `text-[8px]`, which over-reserves by a px or two and never under.- */-export function commentIconWidth(- count: number,- measurer: TextMeasurer,-): number {- const label = count > 99 ? "99+" : String(count);- const badge = Math.max(- measurer.measure(label) + ICON_BADGE_CHROME_PX,- ICON_BADGE_MIN_PX,- );- return ICON_GLYPH_PX - ICON_BADGE_OVERLAP_PX + badge;-}-/** `px-2.5` both sides plus the 1px border of a score chip. */-const SCORE_CHIP_CHROME_PX = 22;-/** `max-w-20` truncates a score's name. */-const SCORE_NAME_MAX_PX = 80;-/** `gap-1`, which a score chip applies between EVERY one of its flex children. */-const SCORE_GAP_PX = 4;-/** `gap-1` plus the value span's own `ml-1`, between two values of one name. */-const SCORE_VALUE_SEPARATOR_PX = 8;-/**- * One `size-3` icon plus its gap, rounded up (the app's root font scale makes a- * `size-3` 10.8px). A value can carry BOTH a comment and metadata, and they- * render as two separate icons.- */-const SCORE_VALUE_ICON_PX = 16;-/** `px-1` both sides of a ScoreTag level pill; the label itself is measured. */-const SCORE_PILL_CHROME_PX = 8;-/** `px-1` both sides of the "+N" button for groups past `maxVisible`, and its border. */-const SCORE_OVERFLOW_CHROME_PX = 10;-/** `gap-1` on the score-badges wrapper β not the cluster's own `gap-2`. */-export const SCORE_GROUP_GAP_PX = 4;-/**- * A canvas measurement and the browser's own layout of the same string agree to- * a fraction of a px, not exactly β enough that a chip priced to the last tenth- * came out 0.09px short on another font stack. One px a chip, in the direction- * that does not clip.- */-const MEASURE_MARGIN_PX = 1;--/**- * The trailing "+N" button, plus the `gap-1` before it. Its digits are measured- * because a flat number for it under-priced every count past 9 β a node can- * carry a dozen distinct score names, and "+10" is wider than "+9".- */-export function overflowButtonWidth(- hidden: number,- measurer: TextMeasurer,-): number {- // Bold, and measured as bold: at the regular weight this came out ~4% short,- // which fitted on one font stack and clipped on another. Two px of margin on- // top, because this is the one item whose own measurement was observed to- // disagree with layout by more than a rounding error, and it is admitted last- // β over-reserving it can only drop badges in a lane that was borderline- // anyway, while under-reserving it cuts a digit off.- return (- measurer.measureBold(`+${hidden}`) +- SCORE_OVERFLOW_CHROME_PX +- SCORE_GROUP_GAP_PX +- MEASURE_MARGIN_PX * 2- );-}--/**- * What `GroupedScoreBadges` will actually take, measured rather than guessed.- *- * A flat 48px reservation was the bug: two real scores render 100-300px, so a- * leftover budget anywhere in between admitted the badges and then let the- * cluster's overflow box cut them mid-glyph β exactly the clipping this layout- * exists to remove, in exactly the narrow lanes it targets. The widest groups are- * priced, because over-reserving drops a badge (recoverable, and the title says- * so) while under-reserving clips one (not recoverable).- *- * Every term here is one the DOM actually charges, and the gap between this sum- * and the rendered width is pinned in Storybook β three rounds of missing terms- * (a flat 48px, a flat level pill, one gap instead of one per child) all passed- * stories that could only see the admit-or-drop decision at one lane width.- */-export function scoreBadgesWidth(- scores: ClusterScore[],- measurer: TextMeasurer,- maxVisible: number,-): number {- // Bucketed by the badges' own grouping rule, so this cannot price a chip that- // never renders β or miss one that does.- const groups = Object.entries(groupScoresByName(scores));- // Level pills appear only when the row MIXES levels; a row whose scores share- // one level needs no per-chip disambiguation. Same rule the badges use.- const mixesLevels =- new Set(scores.map((score) => scoreLevelFromScore(score))).size > 1;-- const comma = measurer.measure(",");-- const widths = groups- .map(([name, group]) => {- // Each value is its own flex span: the text, one icon per comment and per- // metadata (a value carrying both grows two), and a comma on all but the- // last. Two spans are separated by the box's `gap-1` AND the span's `ml-1`.- const values = group.reduce((total, score, index) => {- const text = score.stringValue ?? score.value?.toFixed(2) ?? "";- const icons = (score.comment ? 1 : 0) + (score.metadata ? 1 : 0);- const separator =- index === group.length - 1- ? 0- : SCORE_GAP_PX + comma + SCORE_VALUE_SEPARATOR_PX;- return (- total +- measurer.measure(text) +- icons * SCORE_VALUE_ICON_PX +- separator- );- }, 0);- // The pill spells its level out ("Observation" is not "Trace"), so it is- // measured rather than assumed.- const levels = mixesLevels- ? [...new Set(group.map((score) => scoreLevelFromScore(score)))]- : [];- const pills = levels.reduce(- (total, level) =>- total +- measurer.measure(SCORE_LEVEL_LABELS[level]) +- SCORE_PILL_CHROME_PX,- 0,- );- // The chip is one `gap-1` flex row whose direct children are every level- // pill, the name, and the values box β so N pills mean N + 1 gaps. Pricing- // the name-to-values gap alone under-reserved a mixed-level chip by 4px- // per extra pill, and the cluster's overflow box cuts what it admits.- const gaps = (levels.length + 1) * SCORE_GAP_PX;- return (- Math.min(measurer.measure(`${name}:`), SCORE_NAME_MAX_PX) +- values +- pills +- gaps +- SCORE_CHIP_CHROME_PX +- MEASURE_MARGIN_PX- );- })- .sort((a, b) => b - a)- .slice(0, maxVisible);-- // Groups past the cap collapse into a "+N" button, which is also width.- const hidden = groups.length - maxVisible;- const overflow = hidden > 0 ? overflowButtonWidth(hidden, measurer) : 0;- return widths.reduce(- (total, width, index) =>- total + width + (index > 0 ? SCORE_GROUP_GAP_PX : 0),- overflow,- );-}--/** How many score groups a cluster shows before the rest collapse into "+N". */-export const MAX_SCORE_GROUPS = 3;--/**- * Admit items into the room the lane has left, in priority order, charging each- * the gap the cluster actually renders with. The flex gap sits BETWEEN children,- * so the first item is charged none: billing it for a gap it does not have- * rejected content that renders perfectly well alone.- */-export function createClusterFitter(budgetPx: number, gapPx: number) {- let spentPx = 0;- return (widthPx: number): boolean => {- const next = spentPx + widthPx + (spentPx > 0 ? gapPx : 0);- if (next > budgetPx) return false;- spentPx = next;- return true;- };-}diff --git a/web/src/features/traces/fns/timeline/textMeasurer.ts b/web/src/features/traces/fns/timeline/textMeasurer.tsindex ec582b0ba4..c5fd5a7c54 100644--- a/web/src/features/traces/fns/timeline/textMeasurer.ts+++ b/web/src/features/traces/fns/timeline/textMeasurer.ts@@ -5,10 +5,7 @@* Measures each digit and unit string ONCE against a canvas, then sums cached* glyph widths per label. That is what lets `layout()` decide inside the pure* function whether a duration label fits in its bar or has to sit outside it β- * a decision CSS flow currently makes, and makes wrong in a narrow lane.- *- * Production code, arriving one PR before its callers: the renderer beside it- * (`TimelineV2.tsx`) is a Storybook harness and says so, this is not.+ * a decision CSS flow makes wrong in a narrow lane.*//** Manual measurement average; used when no 2D context is available. */@@ -35,13 +32,6 @@ const unitAt = (text: string, index: number): string | null => {export type TextMeasurer = {measure: (text: string) => number;- /**- * The same text as the browser will set it in BOLD. Callers that reserve room- * for bold content need this: measuring it at the regular weight came out- * ~4% short on one font stack and fitted on another, which is a reservation- * that clips only on some machines.- */- measureBold: (text: string) => number;};export function createTextMeasurer(font = "12px ui-sans-serif"): TextMeasurer {@@ -62,19 +52,14 @@ export function createTextMeasurerFrom(context: CanvasRenderingContext2D | null,font = "12px ui-sans-serif",): TextMeasurer {- return {- measure: measurerFor(context, font),- // A CSS font shorthand takes the weight first, and the callers here build- // theirs from a probe's `font-size` + `font-family`.- measureBold: measurerFor(context, `700 ${font}`),- };+ return { measure: measurerFor(context, font) };}/*** The px size out of a CSS font shorthand β the SIZE, not the first number in- * the string. A bold twin's font is `700 11px β¦`, so reading the leading number- * takes the weight: paired with a canvas that refused the font and reports- * `10px sans-serif`, that scales every width by seventy rather than by one.+ * the string. A shorthand can lead with a weight (`700 11px β¦`), and reading the+ * leading number there takes the weight: paired with the correction below, that+ * scales every width by seventy rather than by one.*/function pxSizeOf(font: string): number {const match = /(\d*\.?\d+)px/.exec(font);@@ -134,8 +119,8 @@ function measurerFor(const flush = () => {if (!run) return;if (context) {- // Set every time: the bold twin shares this context, and whichever- // measured last would otherwise decide the font for both.+ // Set every time: the context is not ours alone, and whatever drew on+ // it last would otherwise decide the font for these widths.context.font = font;width += context.measureText(run).width * scale;} else {diff --git a/web/src/features/traces/fns/timeline/viewTransform.ts b/web/src/features/traces/fns/timeline/viewTransform.tsindex 09f539ff7e..7821ad6f2f 100644--- a/web/src/features/traces/fns/timeline/viewTransform.ts+++ b/web/src/features/traces/fns/timeline/viewTransform.ts@@ -114,17 +114,6 @@ export function zoomView();}-export function panView(- view: TimeSpan,- space: TimeSpan,- deltaMs: number,-): TimeSpan {- return clampView(- { start: view.start + finite(deltaMs, 0), duration: view.duration },- space,- );-}-/** Zoom-to-fit one span, with breathing room on both sides. */export function zoomToSpan(target: TimeSpan,@@ -144,6 +133,3 @@ export function zoomToSpan(space,);}--export const isFitted = (view: TimeSpan, space: TimeSpan): boolean =>- view.start <= space.start && view.duration >= space.duration;