diff --git a/apps/local/src/App.tsx b/apps/local/src/App.tsx
index 8de4e93df..6094d240a 100644
--- a/apps/local/src/App.tsx
+++ b/apps/local/src/App.tsx
@@ -84,6 +84,7 @@ import {
getConnectionPresentation,
getWorkspaceEmptyState,
type ConnectionState,
+ pluralize,
} from "@/lib/presentation.ts";
import {
DEFAULT_STREAM_URL,
@@ -1505,9 +1506,10 @@ export default function App() {
{activeWorkspace.label}
- {searchedItems.length}{" "}
- {activeWorkspace.singularLabel}
- {searchedItems.length === 1 ? "" : "s"}
+ {pluralize(
+ searchedItems.length,
+ activeWorkspace.singularLabel,
+ )}
{newItemCount > 0 ? (
@@ -1521,9 +1523,11 @@ export default function App() {
}
}}
>
- View {newItemCount} new{" "}
- {activeWorkspace.singularLabel}
- {newItemCount === 1 ? "" : "s"}
+ View{" "}
+ {pluralize(
+ newItemCount,
+ `new ${activeWorkspace.singularLabel}`,
+ )}
) : null}
diff --git a/apps/local/src/components/event-filter-controls.tsx b/apps/local/src/components/event-filter-controls.tsx
index ba1afc69c..651624356 100644
--- a/apps/local/src/components/event-filter-controls.tsx
+++ b/apps/local/src/components/event-filter-controls.tsx
@@ -7,6 +7,7 @@ import {
} from "@/lib/event-filters.ts";
import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover.tsx";
import { Button } from "./ui/button.tsx";
+import { pluralize } from "@/lib/presentation.ts";
function toggle(values: string[], value: string) {
return values.includes(value)
? values.filter((entry) => entry !== value)
@@ -154,7 +155,7 @@ export function EventFilterControls({
})
}
>
- Clear {count} filter{count === 1 ? "" : "s"}
+ Clear {pluralize(count, "filter")}
) : null}
{count ? (
diff --git a/apps/local/src/components/performance-workspace.tsx b/apps/local/src/components/performance-workspace.tsx
index 0341d4186..a11978383 100644
--- a/apps/local/src/components/performance-workspace.tsx
+++ b/apps/local/src/components/performance-workspace.tsx
@@ -8,6 +8,7 @@ import {
type VitalName,
} from "@/lib/performance.ts";
import { ResizableWorkspace } from "./resizable-workspace.tsx";
+import { pluralize } from "@/lib/presentation.ts";
function ms(value?: number) {
return value === undefined ? "—" : `${value.toFixed(1)} ms`;
}
@@ -249,8 +250,7 @@ export function WebVitalsWorkspace({
>
{page.name}
- {page.visits.length} captured visit
- {page.visits.length === 1 ? "" : "s"}
+ {pluralize(page.visits.length, "captured visit")}
diff --git a/apps/local/src/components/trace-waterfall.test.tsx b/apps/local/src/components/trace-waterfall.test.tsx
index 7ea7ce1d0..38c963069 100644
--- a/apps/local/src/components/trace-waterfall.test.tsx
+++ b/apps/local/src/components/trace-waterfall.test.tsx
@@ -255,13 +255,61 @@ test("sampled profile rows stay folded under their span until shown", () => {
screen.getAllByRole("button", { name: "Inspect span work" }).length,
).toBeGreaterThan(0);
fireEvent.click(
- screen.getByRole("button", { name: "Hide sampled functions" }),
+ screen.getByRole("button", { name: /^Hide sampled functions/ }),
);
expect(
screen.queryAllByRole("button", { name: "Inspect span work" }),
).toEqual([]);
});
+test("each sampled-functions toggle names its span", () => {
+ const trace = buildTraceGroups(profiledRequest())[0]!;
+ render( undefined} />);
+ const toggle = screen.getByRole("button", {
+ name: /^Show \d+ sampled functions? under GET \/slow$/,
+ });
+ fireEvent.click(toggle);
+ expect(
+ screen.getByRole("button", {
+ name: "Hide sampled functions under GET /slow",
+ }),
+ ).toBeDefined();
+});
+
+test("search unfolds sampled rows only when a sampled row matches", () => {
+ const trace = buildTraceGroups(profiledRequest())[0]!;
+ render( undefined} />);
+ const search = screen.getByLabelText("Search in trace");
+ fireEvent.change(search, { target: { value: "SELECT" } });
+ expect(
+ screen.queryAllByRole("button", { name: "Inspect span work" }),
+ ).toEqual([]);
+ fireEvent.change(search, { target: { value: "work" } });
+ expect(
+ screen.getAllByRole("button", { name: "Inspect span work" }).length,
+ ).toBeGreaterThan(0);
+});
+
+test("selecting a sampled row after mount shows its folded siblings", () => {
+ const trace = buildTraceGroups(profiledRequest())[0]!;
+ const sampled = trace.spans.find((span) => span.sampled)!;
+ const { rerender } = render(
+ undefined} />,
+ );
+ rerender(
+ undefined}
+ />,
+ );
+ expect(
+ screen
+ .getAllByRole("button", { name: "Inspect span work" })
+ .some((button) => button.getAttribute("aria-pressed") === "true"),
+ ).toBe(true);
+});
+
test("a selected sampled row stays visible when returning to the trace", () => {
const trace = buildTraceGroups(profiledRequest())[0]!;
const sampled = trace.spans.find((span) => span.sampled)!;
diff --git a/apps/local/src/components/trace-waterfall.tsx b/apps/local/src/components/trace-waterfall.tsx
index d3b77bd3d..65403a285 100644
--- a/apps/local/src/components/trace-waterfall.tsx
+++ b/apps/local/src/components/trace-waterfall.tsx
@@ -141,6 +141,9 @@ function SpanRow({
const position = getSpanPosition(span, trace);
const visualDepth = Math.min(depth, 4);
const failed = isFailingSpan(span);
+ const samplesLabel = samplesShown
+ ? "Hide sampled functions"
+ : `Show ${pluralize(sampleCount, "sampled function")}`;
// Guides start under the parent's expand control and end at this row's.
const guideLeft =
CELL_PADDING_REM + (visualDepth - 1) * INDENT_REM + TOGGLE_REM / 2;
@@ -228,12 +231,11 @@ function SpanRow({
) : null}
@@ -284,13 +286,19 @@ export function TraceWaterfall({
const [collapsed, setCollapsed] = useState>(new Set());
const allSpans = useMemo(() => flattenSpans(trace.roots), [trace]);
// Sampled profile rows stay folded under their captured span until shown.
- // A selected or revealed sampled row starts with its siblings shown.
- const [shownSamples, setShownSamples] = useState>(() => {
- const owner = allSpans.find(
- ({ span }) => span.id === (revealSpanId ?? selectedSpanId),
- )?.owner;
- return new Set(owner ? [owner] : []);
- });
+ // A selected or revealed sampled row shows its siblings whenever that
+ // selection changes, starting with the first render so focus can return
+ // to it. This runs during render: an effect would run after the
+ // workspace's focus restore and trips react(set-state-in-effect).
+ const revealedId = revealSpanId ?? selectedSpanId;
+ const [shownSamples, setShownSamples] = useState>(new Set());
+ const [seededFor, setSeededFor] = useState();
+ if (revealedId !== seededFor) {
+ setSeededFor(revealedId);
+ const owner = allSpans.find(({ span }) => span.id === revealedId)?.owner;
+ if (owner && !shownSamples.has(owner))
+ setShownSamples(new Set(shownSamples).add(owner));
+ }
const [treeWidth, setTreeWidth] = useState(40);
const sampleCounts = useMemo(() => {
const counts = new Map();
@@ -357,15 +365,22 @@ export function TraceWaterfall({
);
}
- // Search shows every sampled row so matches are not hidden.
+ // Search also unfolds the owners of matching sampled rows.
+ const searchedOwners = new Set(
+ query.trim()
+ ? allSpans.flatMap(({ owner, span }) =>
+ owner && matching.has(span.id) ? [owner] : [],
+ )
+ : [],
+ );
const samplesVisible = (owner: string) =>
- Boolean(query.trim()) || shownSamples.has(owner);
+ shownSamples.has(owner) || searchedOwners.has(owner);
const spans: PositionedSpan[] = [];
let hiddenBelow: number | undefined;
for (const entry of allSpans) {
+ if (entry.owner && !samplesVisible(entry.owner)) continue;
if (!query.trim()) {
if (hiddenBelow !== undefined && entry.depth > hiddenBelow) continue;
- if (entry.owner && !samplesVisible(entry.owner)) continue;
hiddenBelow = collapsed.has(entry.span.id) ? entry.depth : undefined;
}
if (!query.trim() || !onlyMatches || matching.has(entry.span.id))
diff --git a/apps/local/src/components/trace-workspace.test.tsx b/apps/local/src/components/trace-workspace.test.tsx
index 26c57d30b..047897a97 100644
--- a/apps/local/src/components/trace-workspace.test.tsx
+++ b/apps/local/src/components/trace-workspace.test.tsx
@@ -321,7 +321,7 @@ test("returning from a sampled function keeps its row shown and focused", () =>
(document.activeElement as HTMLElement | null)?.dataset["spanId"],
).toBe(id);
fireEvent.click(
- screen.getByRole("button", { name: "Hide sampled functions" }),
+ screen.getByRole("button", { name: /^Hide sampled functions/ }),
);
expect(
screen.queryAllByRole("button", { name: "Inspect span work" }),
diff --git a/apps/local/src/lib/trace-model.test.ts b/apps/local/src/lib/trace-model.test.ts
index 9952cfa51..bbd928477 100644
--- a/apps/local/src/lib/trace-model.test.ts
+++ b/apps/local/src/lib/trace-model.test.ts
@@ -1175,6 +1175,62 @@ test.each([
},
);
+test.each([
+ [
+ "http.server",
+ "GET",
+ {
+ "url.template": "/api/items/{id}",
+ "url.full": "http://localhost:3000/api/items/7",
+ },
+ "GET /api/items/{id}",
+ ],
+ [
+ "http.client",
+ "GET",
+ { "url.full": "https://api.stripe.com/v1/charges?limit=1" },
+ "GET api.stripe.com/v1/charges",
+ ],
+ ["http.server", "get", { "url.path": "/api/edge" }, "get /api/edge"],
+ [
+ "http.server",
+ "GET",
+ { "url.full": "/api/edge?x=1", "url.path": "/api/edge" },
+ "GET /api/edge",
+ ],
+ [
+ "resource.script",
+ "get localhost",
+ { "url.full": "http://localhost:5173/src/app.js?v=1" },
+ "get http://localhost:5173/src/app.js",
+ ],
+])(
+ "a %s span named %o is labeled with its target",
+ (op, name, attributes, title) => {
+ const [trace] = buildTraceGroups(
+ decodeEnvelope(
+ spanEnvelope([
+ {
+ trace_id: "target",
+ span_id: "segment",
+ is_segment: true,
+ name,
+ start_timestamp: 1,
+ end_timestamp: 1.1,
+ attributes: Object.fromEntries(
+ Object.entries({ "sentry.op": op, ...attributes }).map(
+ ([key, value]) => [key, { type: "string", value }],
+ ),
+ ),
+ },
+ ]),
+ "target",
+ ),
+ );
+ expect(trace?.title).toBe(title);
+ },
+);
+
test("span counts leave out the transaction and segment like the tail's [N spans]", () => {
// Django /queries/: the tail printed [7 spans] while the viewer showed 8.
const children = Array.from({ length: 7 }, (_, index) => ({
diff --git a/apps/local/src/lib/trace-model.ts b/apps/local/src/lib/trace-model.ts
index 90f141eb7..e580c9b1c 100644
--- a/apps/local/src/lib/trace-model.ts
+++ b/apps/local/src/lib/trace-model.ts
@@ -1,4 +1,5 @@
import { parseEventTimestamp } from "../../../../packages/cli/src/commands/local/timestamp.ts";
+import { httpTargetAttribute } from "../../../../packages/cli/src/commands/local/http-target.ts";
import {
getEventMetadata,
type EventMetadata,
@@ -94,6 +95,7 @@ function getPayloadSpan(
operation ??
item.type,
payload,
+ operation,
);
return withoutUndefined({
@@ -143,10 +145,18 @@ const HTTP_METHODS = new Set([
* (span v2 attributes or transaction span data).
* Label them with the URL's origin and path so rows can be told apart,
* grouped and searched. The query (cache busters, tokens) and fragment
- * stay in the span's attributes. Spans named by method only get the
- * route, or else the path, after the method.
+ * stay in the span's attributes.
+ *
+ * Spans named by method only ("GET", any case) get a target after the
+ * method, read in the CLI's `httpTargetAttribute` order. A server span
+ * (`http.server`) shows the route or path; any other span keeps the
+ * host it called, such as `GET api.stripe.com/v1/charges`.
*/
-function withCapturedUrl(description: string, payload: unknown): string {
+function withCapturedUrl(
+ description: string,
+ payload: unknown,
+ operation: string | undefined,
+): string {
const data = spanData(payload);
const url = getString(data["url.full"]);
let parsed: URL | undefined;
@@ -155,16 +165,19 @@ function withCapturedUrl(description: string, payload: unknown): string {
} catch {
parsed = undefined;
}
- // Next.js edge `http.server` segments are named by method only ("GET").
- if (HTTP_METHODS.has(description)) {
- const path =
- getString(data["http.route"]) ??
- getString(data["url.path"]) ??
- parsed?.pathname;
+ if (HTTP_METHODS.has(description.toUpperCase())) {
+ if (operation !== "http.server" && parsed)
+ return `${description} ${parsed.host}${parsed.pathname}`;
+ // A `url.full` that isn't an absolute URL has no path to show, so
+ // skip it and fall through to `url.path`.
+ const target = httpTargetAttribute((key) =>
+ key === "url.full" && !parsed ? undefined : getString(data[key]),
+ );
+ const path = target?.key === "url.full" ? parsed?.pathname : target?.value;
return path ? `${description} ${path}` : description;
}
if (!parsed) return description;
- const match = description.match(/^([A-Z]+ )?(.*)$/);
+ const match = description.match(/^([a-z]+ )?(.*)$/i);
const method = match?.[1] ?? "";
const target = match?.[2] ?? description;
return target === parsed.hostname || target === parsed.host
@@ -201,7 +214,8 @@ function mergeSpan(
].some(
(value) =>
typeof value === "string" &&
- withCapturedUrl(value.trim(), span.payload) === description,
+ withCapturedUrl(value.trim(), span.payload, span.operation) ===
+ description,
);
return named ? (captured ? 4 : 2) : 0;
};
@@ -290,6 +304,7 @@ function getChildSpans(payload: unknown, item: LocalFeedItem): TraceSpan[] {
description: withCapturedUrl(
getString(value["description"]) ?? operation ?? id,
value,
+ operation,
),
startTimestamp,
endTimestamp,
diff --git a/docs/cli/local-control-plane.md b/docs/cli/local-control-plane.md
index 0a65dc51f..78f9749f4 100644
--- a/docs/cli/local-control-plane.md
+++ b/docs/cli/local-control-plane.md
@@ -325,8 +325,11 @@ transactions, show their op and transaction name.
A trace's error count is its error events: exceptions and error-level messages.
Failing spans and error-level logs are not counted again. A span or segment
-named only by its HTTP method, such as a Next.js edge `GET`, is labeled with its
-`http.route`, or else its `url.path` or URL path.
+named only by its HTTP method (in any case), such as a Next.js edge `GET`, gets
+a target after the method. The viewer and the tail read the same attributes, in
+order: `http.route`, `url.template`, `url.full`, then `url.path`. A server span
+(`http.server`) shows the route or path; any other span keeps the host it called,
+such as `GET api.stripe.com/v1/charges`.
Log inspectors show the message, level, and attributes. Requests summarize useful
metadata and related telemetry. Waterfall spans are keyboard-selectable and open
diff --git a/packages/cli/src/commands/local/http-target.ts b/packages/cli/src/commands/local/http-target.ts
new file mode 100644
index 000000000..bc3b2f8f2
--- /dev/null
+++ b/packages/cli/src/commands/local/http-target.ts
@@ -0,0 +1,26 @@
+/** Browser-safe HTTP target lookup shared by the Local tail and viewer. */
+
+/**
+ * Span attributes that name an HTTP request's target, best first: the route
+ * template, then the full URL, then the path. Callers decide how to show the
+ * value; the viewer, for example, shows only a URL's path for server spans.
+ */
+const HTTP_TARGET_ATTRIBUTES = [
+ "http.route",
+ "url.template",
+ "url.full",
+ "url.path",
+] as const;
+
+export type HttpTargetAttribute = (typeof HTTP_TARGET_ATTRIBUTES)[number];
+
+/** The first target attribute, in `HTTP_TARGET_ATTRIBUTES` order, with a value. */
+export function httpTargetAttribute(
+ read: (key: HttpTargetAttribute) => string | undefined,
+): { key: HttpTargetAttribute; value: string } | undefined {
+ for (const key of HTTP_TARGET_ATTRIBUTES) {
+ const value = read(key);
+ if (value) return { key, value };
+ }
+ return undefined;
+}
diff --git a/packages/cli/src/lib/formatters/semantic-display.ts b/packages/cli/src/lib/formatters/semantic-display.ts
index 0b99bb0f0..852eec5c9 100644
--- a/packages/cli/src/lib/formatters/semantic-display.ts
+++ b/packages/cli/src/lib/formatters/semantic-display.ts
@@ -11,6 +11,7 @@
*/
import { logger } from "../logger.js";
+import { httpTargetAttribute } from "../../commands/local/http-target.js";
const log = logger.withTag("semantic-display");
@@ -637,24 +638,15 @@ function getHttpTarget(
includeFullUrl = true,
}: { includeServerTarget?: boolean; includeFullUrl?: boolean } = {},
): string | undefined {
- const route = getAttr(
- attrs,
- ["http.route", "url.template"],
- SPAN_ATTRIBUTE_MAX_LENGTH,
+ const target = httpTargetAttribute((key) =>
+ key === "url.full" && !includeFullUrl
+ ? undefined
+ : getAttr(attrs, [key], SPAN_ATTRIBUTE_MAX_LENGTH),
);
- const fullUrl = getAttr(attrs, ["url.full"], SPAN_ATTRIBUTE_MAX_LENGTH);
- const path = getAttr(attrs, ["url.path"], SPAN_ATTRIBUTE_MAX_LENGTH);
- const serverTarget = getServerTarget(attrs);
-
- if (route) {
- return formatHttpTarget(route);
- }
- if (fullUrl && includeFullUrl) {
- return formatHttpTarget(fullUrl);
- }
- if (path) {
- return formatHttpTarget(path);
+ if (target) {
+ return formatHttpTarget(target.value);
}
+ const serverTarget = getServerTarget(attrs);
if (includeServerTarget && serverTarget) {
return formatHttpTarget(serverTarget);
}
diff --git a/packages/cli/test/commands/local/http-target.test.ts b/packages/cli/test/commands/local/http-target.test.ts
new file mode 100644
index 000000000..d90bbbec6
--- /dev/null
+++ b/packages/cli/test/commands/local/http-target.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, test } from "vitest";
+import { httpTargetAttribute } from "../../../src/commands/local/http-target.js";
+
+describe("httpTargetAttribute", () => {
+ test.each([
+ [
+ { "http.route": "/r", "url.template": "/t", "url.full": "http://h/f" },
+ { key: "http.route", value: "/r" },
+ ],
+ [
+ { "url.template": "/t", "url.full": "http://h/f", "url.path": "/p" },
+ { key: "url.template", value: "/t" },
+ ],
+ [
+ { "url.full": "http://h/f", "url.path": "/p" },
+ { key: "url.full", value: "http://h/f" },
+ ],
+ [
+ { "http.route": "", "url.path": "/p" },
+ { key: "url.path", value: "/p" },
+ ],
+ [{}, undefined],
+ ])("picks the best target from %o", (attributes, expected) => {
+ const attrs: Record = attributes;
+ expect(httpTargetAttribute((key) => attrs[key])).toEqual(expected);
+ });
+});