diff --git a/apps/local/src/App.capture-lifecycle.test.tsx b/apps/local/src/App.capture-lifecycle.test.tsx index 618271fd0..bfaea7f92 100644 --- a/apps/local/src/App.capture-lifecycle.test.tsx +++ b/apps/local/src/App.capture-lifecycle.test.tsx @@ -790,3 +790,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 34985f687..8eb61264d 100644 --- a/apps/local/src/App.sessions.integration.test.tsx +++ b/apps/local/src/App.sessions.integration.test.tsx @@ -729,3 +729,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 8de4e93df..a81e1d8b3 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, @@ -261,7 +263,7 @@ function EventEntry({ ) : null} {columns.includes("time") ? ( ) : null} @@ -710,18 +712,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 }, @@ -935,11 +941,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 2f286d3e1..94ad68f4b 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"; @@ -213,7 +213,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 71a2c35a2..a688de724 100644 --- a/apps/local/src/components/inspector-data.ts +++ b/apps/local/src/components/inspector-data.ts @@ -11,13 +11,16 @@ export function attributeFields(value: unknown): DetailField[] { return Object.entries(detailRecord(value)).map(([label, attribute]) => { const record = detailRecord(attribute); const content = "value" in record ? record["value"] : attribute; - const serialized = JSON.stringify(content) as string | undefined; + const serialized = JSON.stringify(content, (_key, nested: unknown) => + typeof nested === "string" ? stripAnsi(nested) : nested, + ) as string | undefined; return { label, // Display only: the JSON tab keeps SDK text exactly as captured. - value: stripAnsi( - typeof content === "string" ? content : (serialized ?? String(content)), - ), + value: + typeof content === "string" + ? stripAnsi(content) + : (serialized ?? 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 7e498c603..db6087a72 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 6815f5ad6..3e973c88a 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 { jsonText } from "@/lib/objects.ts"; import { JsonView } from "./json-view.tsx"; @@ -219,7 +219,7 @@ export function SpanDetail({ : [ { label: "Start timestamp", - value: formatTimestamp(span.startTimestamp), + value: formatDateTime(span.startTimestamp, { milliseconds: true }), code: true, }, ]), @@ -228,7 +228,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 cde7c18bb..9fdeccfa4 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 147024501..d029957b7 100644 --- a/apps/local/src/lib/inspection.ts +++ b/apps/local/src/lib/inspection.ts @@ -1,6 +1,6 @@ import { classifyEvent } from "../../../../packages/cli/src/commands/local/event-kind.ts"; import { jsonText } from "./objects.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 { @@ -258,7 +258,7 @@ export function sdkInventory(items: readonly LocalFeedItem[]): SdkEntry[] { key = `${name}@${version}`; const previous = entries.get(key); const lastSeen = - item.timestamp ?? + itemTime(item) ?? text(item.envelopeHeader?.["sent_at"]) ?? previous?.lastSeen; entries.set(key, { diff --git a/apps/local/src/lib/presentation.ts b/apps/local/src/lib/presentation.ts index 2ab6eff4b..1700d4dbf 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 3591dc2a2..661a1cea5 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 0e62ad2e3..fd15ed015 100644 --- a/apps/local/src/lib/spotlight.ts +++ b/apps/local/src/lib/spotlight.ts @@ -25,6 +25,8 @@ export type LocalFeedItem = { id: string; type: string; timestamp?: number | string | undefined; + /** When the receiver got the item's envelope, in epoch milliseconds. */ + receivedAt?: number | undefined; text: string; payload: unknown; metadata?: EventMetadata; @@ -292,11 +294,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. */