From 9d711edf2feb5702fa15ad14b67ab562116144b3 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:30:38 +0000 Subject: [PATCH] fix(local): Keep receive times out of trace timing Items with no SDK time showed their receive time by writing it into `timestamp`, which trace timing also reads. A check-in that arrived minutes after its transaction stretched the trace to match. Keep the receive time in its own field, used only to show and sort items. Also from review of the earlier viewer fixes: - Span start and end times show milliseconds, and the date when it is not today. - Attribute values strip ANSI codes from nested strings too. - A pasted link is cleared from the address bar even when its stream is refused; fragment parsing is shared in readConnectionLink. Co-Authored-By: Aditya Mathur <57684218+MathurAditya724@users.noreply.github.com> --- apps/local/src/App.capture-lifecycle.test.tsx | 54 ++++++++++++++++++ .../src/App.sessions.integration.test.tsx | 21 +++++++ apps/local/src/App.tsx | 34 +++++------ apps/local/src/components/event-detail.tsx | 4 +- .../src/components/inspector-data.test.ts | 15 +++++ apps/local/src/components/inspector-data.ts | 9 +-- .../local/src/components/span-detail.test.tsx | 56 ++++++++++++++++++- apps/local/src/components/span-detail.tsx | 6 +- apps/local/src/lib/event-filters.ts | 4 +- apps/local/src/lib/inspection.ts | 4 +- apps/local/src/lib/presentation.ts | 24 ++++++-- apps/local/src/lib/session-directory.ts | 12 ++-- apps/local/src/lib/spotlight.ts | 33 ++++++++++- 13 files changed, 233 insertions(+), 43 deletions(-) create mode 100644 apps/local/src/components/inspector-data.test.ts diff --git a/apps/local/src/App.capture-lifecycle.test.tsx b/apps/local/src/App.capture-lifecycle.test.tsx index b654df824e..05551baf78 100644 --- a/apps/local/src/App.capture-lifecycle.test.tsx +++ b/apps/local/src/App.capture-lifecycle.test.tsx @@ -807,3 +807,57 @@ test("replay recordings show when they were received instead of unknown time", a expect(row.textContent).not.toContain("unknown time"); expect(row.textContent).toContain(new Date(receivedAt).toLocaleTimeString()); }); + +test("an untimed item in a trace does not stretch the trace to its receive time", async () => { + // A 400 ms transaction, then a sentry-python cron check-in in the same + // trace that the receiver got 222 s later. Check-ins carry no timestamp. + const uuidv7 = (ms: number) => + `${ms + .toString(16) + .padStart(12, "0") + .replace(/^(.{8})(.{4})$/, "$1-$2")}-7abc-8def-0123456789ab`; + const finishedAt = 1_794_947_420.913; + const traceId = "8f2a6c1e4b7d4f0a9c3e5b1d7a2f6c8e"; + renderCapture({ path: "/traces" }); + const source = await openSource(); + const send = (lastEventId: string, items: unknown[]) => + act(async () => + source.dispatchEvent( + new MessageEvent("application/x-sentry-envelope", { + data: JSON.stringify([{}, items]), + lastEventId, + }), + ), + ); + await send(uuidv7(finishedAt * 1000 + 50), [ + [ + { type: "transaction" }, + { + type: "transaction", + transaction: "nightly-report", + start_timestamp: finishedAt - 0.4, + timestamp: finishedAt, + contexts: { + trace: { trace_id: traceId, span_id: "a1b2c3d4e5f60718", op: "task" }, + }, + }, + ], + ]); + await send(uuidv7(finishedAt * 1000 + 222_000), [ + [ + { type: "check_in" }, + { + check_in_id: "5f1c0e8a2b9d4c7e8f3a1b6d0c9e2f4a", + monitor_slug: "nightly-report", + status: "ok", + duration: 0.4, + contexts: { trace: { trace_id: traceId, span_id: "a1b2c3d4e5f60718" } }, + }, + ], + ]); + const row = await screen.findByRole("button", { + name: "View trace nightly-report", + }); + expect(row.textContent).toMatch(/400(\.0+)? ms/); + expect(row.textContent).not.toContain("222"); +}); diff --git a/apps/local/src/App.sessions.integration.test.tsx b/apps/local/src/App.sessions.integration.test.tsx index c4ce523b3f..f7b8bce0f5 100644 --- a/apps/local/src/App.sessions.integration.test.tsx +++ b/apps/local/src/App.sessions.integration.test.tsx @@ -783,3 +783,24 @@ test("a new session link in an open tab switches to that run's sessions", async await second.stop(); } }); + +test("a pasted link with a stream the viewer refuses still leaves the address bar", async () => { + const daemon = await startDaemon(); + try { + const web = await daemon.create("web"); + await daemon.ingest(web, "/first-run"); + renderSession(web); + await screen.findAllByText("/first-run"); + await act(async () => { + window.location.hash = new URLSearchParams({ + stream: "https://collector.example.com/stream", + directory: web.directoryUrl, + }).toString(); + }); + await waitFor(() => expect(window.location.hash).toBe("")); + expect(screen.getAllByText("/first-run").length).toBeGreaterThan(0); + } finally { + cleanup(); + await daemon.stop(); + } +}); diff --git a/apps/local/src/App.tsx b/apps/local/src/App.tsx index 2fa2d85744..99e1578faf 100644 --- a/apps/local/src/App.tsx +++ b/apps/local/src/App.tsx @@ -89,6 +89,8 @@ import { DEFAULT_STREAM_URL, decodeEnvelope, getStreamUrlFromHash, + itemTime, + readConnectionLink, parseStreamEndpoint, isLoopbackHost, REMOTE_STREAM_STORAGE_KEY, @@ -258,7 +260,7 @@ function EventEntry({ ) : null} {columns.includes("time") ? ( ) : null} @@ -711,18 +713,22 @@ export default function App() { }); useEffect(() => { const onHashChange = () => { + const link = readConnectionLink(window.location.hash); + if (!link.present) return; const linkedStreamUrl = getStreamUrlFromHash(window.location.hash); - if (!linkedStreamUrl) return; - const directory = parseSessionDirectoryUrl( - new URLSearchParams(window.location.hash.slice(1)).get("directory"), - linkedStreamUrl, - ); - connectToEndpointRef.current(linkedStreamUrl); - if (directory) { - saveSessionDirectory(directory); - setDirectoryUrl(directory); + if (linkedStreamUrl) { + connectToEndpointRef.current(linkedStreamUrl); + const directory = parseSessionDirectoryUrl( + link.directory, + linkedStreamUrl, + ); + if (directory) { + saveSessionDirectory(directory); + setDirectoryUrl(directory); + } } - // The link carries capabilities; keep them out of the address bar. + // The link carries capabilities, even a refused one; keep them out of + // the address bar. void navigate( { pathname: window.location.pathname, search: window.location.search }, { replace: true }, @@ -936,11 +942,7 @@ export default function App() { envelopeReceivedAt(eventId) ?? (Number.isNaN(sentAtMs) ? Date.now() : sentAtMs); // Items with no SDK time, such as replay recordings, show when they arrived. - items = items?.map((item) => - item.timestamp === undefined - ? { ...item, timestamp: receivedAt / 1000 } - : item, - ); + items = items?.map((item) => ({ ...item, receivedAt })); const itemTypes = [...new Set(items?.map((item) => item.type))]; setLatestEventTime((latest) => latest === undefined ? receivedAt : Math.max(latest, receivedAt), diff --git a/apps/local/src/components/event-detail.tsx b/apps/local/src/components/event-detail.tsx index e36ba9a5ea..f515837080 100644 --- a/apps/local/src/components/event-detail.tsx +++ b/apps/local/src/components/event-detail.tsx @@ -18,7 +18,7 @@ import { type DetailField, } from "./inspector-data.ts"; import type { LocalFeedItem } from "@/lib/spotlight.ts"; -import { getEventMetadata } from "@/lib/spotlight.ts"; +import { getEventMetadata, itemTime } from "@/lib/spotlight.ts"; import { formatTimestamp } from "@/lib/presentation.ts"; import { getEventExceptions } from "@/lib/exceptions.ts"; import type { TraceGroup } from "@/lib/trace-model.ts"; @@ -217,7 +217,7 @@ export function EventDetail({ ) : null} { + // uvicorn's logging record, kept as breadcrumb data by sentry-python. + const [field] = attributeFields({ + record: { + color_message: "Started server process [\u001b[36m%d\u001b[0m]", + args: ["\u001b[1m41234\u001b[0m"], + }, + }); + expect(field?.value).toBe( + '{"color_message":"Started server process [%d]","args":["41234"]}', + ); +}); diff --git a/apps/local/src/components/inspector-data.ts b/apps/local/src/components/inspector-data.ts index b20af2c97f..56637c7b9e 100644 --- a/apps/local/src/components/inspector-data.ts +++ b/apps/local/src/components/inspector-data.ts @@ -14,11 +14,12 @@ export function attributeFields(value: unknown): DetailField[] { return { label, // Display only: the JSON tab keeps SDK text exactly as captured. - value: stripAnsi( + value: typeof content === "string" - ? content - : (JSON.stringify(content) ?? String(content)), - ), + ? stripAnsi(content) + : (JSON.stringify(content, (_key, nested: unknown) => + typeof nested === "string" ? stripAnsi(nested) : nested, + ) ?? String(content)), code: true, }; }); diff --git a/apps/local/src/components/span-detail.test.tsx b/apps/local/src/components/span-detail.test.tsx index 7e498c6038..db6087a722 100644 --- a/apps/local/src/components/span-detail.test.tsx +++ b/apps/local/src/components/span-detail.test.tsx @@ -1,5 +1,12 @@ -import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { + cleanup, + fireEvent, + render, + screen, + within, +} from "@testing-library/react"; import { afterEach, expect, test, vi } from "vitest"; +import { formatDateTime } from "@/lib/presentation.ts"; import { decodeEnvelope } from "@/lib/spotlight.ts"; import { buildTraceGroups } from "@/lib/trace-model.ts"; import { SpanDetail } from "./span-detail.tsx"; @@ -99,6 +106,49 @@ test("span start and end times use local time, not raw epoch seconds", () => { const details = screen.getByRole("table", { name: "Span details" }).textContent ?? ""; expect(details).not.toContain("1795010400.538"); - expect(details).toContain(new Date(1795010400538).toLocaleTimeString()); - expect(details).toContain(new Date(1795010400650).toLocaleTimeString()); + expect(details).toContain( + formatDateTime(1795010400.538, { milliseconds: true }), + ); + expect(details).toContain( + formatDateTime(1795010400.65, { milliseconds: true }), + ); +}); + +test("span times keep milliseconds and show the date when it is not today", () => { + // A 40 ms span from an earlier day. + const [trace] = buildTraceGroups( + decodeEnvelope( + JSON.stringify([ + {}, + [ + [ + { type: "transaction" }, + { + transaction: "GET /orders", + start_timestamp: 1_700_000_000.538, + timestamp: 1_700_000_000.578, + contexts: { trace: { trace_id: "trace", span_id: "root" } }, + }, + ], + ], + ]), + "fixture", + ), + ); + const span = trace?.spans.find((entry) => entry.id === "root"); + if (!trace || !span) throw new Error("Expected trace span"); + render(); + const details = screen.getByRole("table", { name: "Span details" }); + const time = (ms: number) => + new Date(ms).toLocaleTimeString(undefined, { + hour: "numeric", + minute: "2-digit", + second: "2-digit", + fractionalSecondDigits: 3, + }); + const start = within(details).getByRole("row", { name: /Start timestamp/ }); + const end = within(details).getByRole("row", { name: /End timestamp/ }); + const day = new Date(1_700_000_000_538).toLocaleDateString(); + expect(start.textContent).toContain(`${day} ${time(1_700_000_000_538)}`); + expect(end.textContent).toContain(`${day} ${time(1_700_000_000_578)}`); }); diff --git a/apps/local/src/components/span-detail.tsx b/apps/local/src/components/span-detail.tsx index e5efaf4d5f..c5f74c3a46 100644 --- a/apps/local/src/components/span-detail.tsx +++ b/apps/local/src/components/span-detail.tsx @@ -4,7 +4,7 @@ import { Check, Copy, ChevronLeft } from "lucide-react"; import { type KeyboardEvent, type ReactNode, useId, useState } from "react"; import type { LocalFeedItem } from "@/lib/spotlight.ts"; import type { TraceGroup, TraceSpan } from "@/lib/trace-model.ts"; -import { formatTimestamp } from "@/lib/presentation.ts"; +import { formatDateTime } from "@/lib/presentation.ts"; import { isErrorEvent } from "@/lib/workspace.ts"; import { JsonView } from "./json-view.tsx"; @@ -222,7 +222,7 @@ export function SpanDetail({ : [ { label: "Start timestamp", - value: formatTimestamp(span.startTimestamp), + value: formatDateTime(span.startTimestamp, { milliseconds: true }), code: true, }, ]), @@ -231,7 +231,7 @@ export function SpanDetail({ : [ { label: "End timestamp", - value: formatTimestamp(span.endTimestamp), + value: formatDateTime(span.endTimestamp, { milliseconds: true }), code: true, }, ]), diff --git a/apps/local/src/lib/event-filters.ts b/apps/local/src/lib/event-filters.ts index cde7c18bb8..9fdeccfa47 100644 --- a/apps/local/src/lib/event-filters.ts +++ b/apps/local/src/lib/event-filters.ts @@ -1,5 +1,5 @@ import { parseEventTimestamp } from "../../../../packages/cli/src/commands/local/timestamp.ts"; -import type { LocalFeedItem } from "./spotlight.ts"; +import { itemTime, type LocalFeedItem } from "./spotlight.ts"; import { spanData, text } from "./inspection.ts"; export type EventColumn = "time" | "type" | "level" | "logger" | "duration"; export type EventFilters = { @@ -18,7 +18,7 @@ export function loggerForItem(item: LocalFeedItem): string | undefined { return text(spanData(item.payload)["sentry.logger.name"]); } function timestamp(item: LocalFeedItem): number { - const value = parseEventTimestamp(item.timestamp); + const value = parseEventTimestamp(itemTime(item)); if (value === undefined) return -Infinity; return value < 1e12 ? value * 1000 : value; } diff --git a/apps/local/src/lib/inspection.ts b/apps/local/src/lib/inspection.ts index a630df19f5..b511d83ce2 100644 --- a/apps/local/src/lib/inspection.ts +++ b/apps/local/src/lib/inspection.ts @@ -1,5 +1,5 @@ import { classifyEvent } from "../../../../packages/cli/src/commands/local/event-kind.ts"; -import { getEventMetadata, type LocalFeedItem } from "./spotlight.ts"; +import { getEventMetadata, itemTime, type LocalFeedItem } from "./spotlight.ts"; import { getEventExceptions, formatExceptionTitle } from "./exceptions.ts"; export function record(value: unknown): Record { @@ -254,7 +254,7 @@ export function sdkInventory(items: readonly LocalFeedItem[]): SdkEntry[] { const version = text(sdk.version) ?? "Unknown", key = `${name}@${version}`; const previous = entries.get(key); - const timestamp = item.timestamp ?? text(item.envelopeHeader?.sent_at); + const timestamp = itemTime(item) ?? text(item.envelopeHeader?.sent_at); entries.set(key, { name, version, diff --git a/apps/local/src/lib/presentation.ts b/apps/local/src/lib/presentation.ts index 2ab6eff4bb..1700d4dbf1 100644 --- a/apps/local/src/lib/presentation.ts +++ b/apps/local/src/lib/presentation.ts @@ -116,11 +116,27 @@ export function formatTimestamp( return toDate(timestamp)?.toLocaleTimeString() ?? String(timestamp); } -/** Like formatTimestamp, with the local date added when it is not today. */ -export function formatDateTime(timestamp: number | string): string { +const TIME_WITH_MILLISECONDS: Intl.DateTimeFormatOptions = { + hour: "numeric", + minute: "2-digit", + second: "2-digit", + fractionalSecondDigits: 3, +}; + +/** + * Like formatTimestamp, with the local date added when it is not today. Pass + * `milliseconds` where events can be closer together than a second. + */ +export function formatDateTime( + timestamp: number | string, + { milliseconds = false }: { milliseconds?: boolean } = {}, +): string { const date = toDate(timestamp); if (!date) return String(timestamp); + const time = milliseconds + ? date.toLocaleTimeString(undefined, TIME_WITH_MILLISECONDS) + : date.toLocaleTimeString(); return date.toDateString() === new Date().toDateString() - ? date.toLocaleTimeString() - : `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`; + ? time + : `${date.toLocaleDateString()} ${time}`; } diff --git a/apps/local/src/lib/session-directory.ts b/apps/local/src/lib/session-directory.ts index a741da17f1..ebc6631e2d 100644 --- a/apps/local/src/lib/session-directory.ts +++ b/apps/local/src/lib/session-directory.ts @@ -1,4 +1,8 @@ -import { isLoopbackHost, parseStreamEndpoint } from "./spotlight.ts"; +import { + isLoopbackHost, + parseStreamEndpoint, + readConnectionLink, +} from "./spotlight.ts"; const DIRECTORY_STORAGE_KEY = "sentry.local.session-directory"; export type ViewerSession = { @@ -39,7 +43,7 @@ export function parseSessionDirectoryUrl( export function getInitialSessionDirectory( streamUrl: string, ): string | undefined { - const fragment = new URLSearchParams(window.location.hash.slice(1)); + const link = readConnectionLink(window.location.hash); let saved: string | null = null; try { saved = window.sessionStorage.getItem(DIRECTORY_STORAGE_KEY); @@ -47,12 +51,12 @@ export function getInitialSessionDirectory( /* Storage may be disabled. */ } const directory = parseSessionDirectoryUrl( - fragment.has("directory") ? fragment.get("directory") : saved, + link.directory ?? saved, streamUrl, ); // The startup effect removes the fragment before discovery can finish. Save // its validated capability now so an early reload cannot lose the picker. - if (directory && fragment.has("directory")) saveSessionDirectory(directory); + if (directory && link.directory !== null) saveSessionDirectory(directory); return directory; } diff --git a/apps/local/src/lib/spotlight.ts b/apps/local/src/lib/spotlight.ts index 4272a48e94..bb45545634 100644 --- a/apps/local/src/lib/spotlight.ts +++ b/apps/local/src/lib/spotlight.ts @@ -24,6 +24,8 @@ export type LocalFeedItem = { id: string; type: string; timestamp?: number | string; + /** When the receiver got the item's envelope, in epoch milliseconds. */ + receivedAt?: number; text: string; payload: unknown; metadata?: EventMetadata; @@ -284,11 +286,36 @@ function normalizeRemoteStreamUrl(stream: string | null): string | undefined { return endpoint?.kind === "remote" ? endpoint.url : undefined; } +/** + * When to show and sort an item by: its SDK time, else when it was received. + * Trace timing reads only `timestamp`, so a late receive time cannot stretch a + * trace. + */ +export function itemTime(item: LocalFeedItem): number | string | undefined { + return item.timestamp ?? item.receivedAt; +} + +/** + * The raw `stream` and `directory` a CLI link carries in the URL fragment. + * `present` is true when either is there, so callers clear both even when a + * value fails validation. + */ +export function readConnectionLink(hash: string): { + present: boolean; + stream: string | null; + directory: string | null; +} { + const fragment = new URLSearchParams(hash.replace(/^#/, "")); + return { + present: fragment.has("stream") || fragment.has("directory"), + stream: fragment.get("stream"), + directory: fragment.get("directory"), + }; +} + /** Read the CLI-provided stream endpoint without allowing arbitrary targets. */ export function getStreamUrlFromHash(hash: string): string | undefined { - return normalizeLoopbackStreamUrl( - new URLSearchParams(hash.replace(/^#/, "")).get("stream"), - ); + return normalizeLoopbackStreamUrl(readConnectionLink(hash).stream); } /** Public viewer query links may select only a credential-free loopback receiver. */