From c0e3575def5a7e8bd36baacf48bc4698f89a8f9b Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 17:58:04 +0000 Subject: [PATCH 1/4] fix(cli): Resolve a reused Local session name to its newest open session Every `local run --session web` creates a new session, so after two runs `web` matched two sessions and every lookup by that name failed with "matches more than one session", even when the older run had closed. The session store now resolves a name to its newest open session, or to its newest session when none is open; session IDs still resolve exactly. When several open sessions share the name, control responses name the chosen session and the others in a header, and the CLI prints one stderr note with each other session's ID, state, and age. The CLI still reports an older daemon's 409 for a shared name as a user error. Co-Authored-By: Aditya Mathur <57684218+MathurAditya724@users.noreply.github.com> --- apps/cli-docs/src/fragments/commands/local.md | 8 ++- design/sentry-local.md | 3 + docs/cli/local-control-plane.md | 8 ++- .../skills/sentry-cli/references/local.md | 12 ++-- .../cli/src/commands/local/control-plane.ts | 47 +++++++----- packages/cli/src/commands/local/management.ts | 67 ++++++++++++++++- .../cli/src/commands/local/session-store.ts | 71 ++++++++++--------- .../test/commands/local/control-plane.test.ts | 65 +++++++++++------ .../test/commands/local/management.test.ts | 47 ++++++++++-- .../test/commands/local/session-store.test.ts | 35 +++++++-- packages/cli/test/e2e/local.test.ts | 28 ++++++-- 11 files changed, 291 insertions(+), 100 deletions(-) diff --git a/apps/cli-docs/src/fragments/commands/local.md b/apps/cli-docs/src/fragments/commands/local.md index a40d0a9701..be42844eb3 100644 --- a/apps/cli-docs/src/fragments/commands/local.md +++ b/apps/cli-docs/src/fragments/commands/local.md @@ -275,8 +275,12 @@ same way without wrapping a command. `sentry local session create --json` returns separate SDK ingest and viewer read capability URLs. Keep these URLs private. `--clientId ` makes -retried session creation idempotent. Use the session ID when multiple sessions -share a label. +retried session creation idempotent. + +Each `local run --session` creates a new session, so names repeat. A name +picks its newest open session, or its newest session when none is open. When +several open sessions share the name, the command uses the newest and notes the +others on stderr; pass a session ID to pick one of them. How an SDK reaches a session depends on its Spotlight support: diff --git a/design/sentry-local.md b/design/sentry-local.md index 208f82c1d3..d15e88773f 100644 --- a/design/sentry-local.md +++ b/design/sentry-local.md @@ -41,6 +41,9 @@ account. `sentry-local#stop-clears`). - Each session or receiver keeps its most recent envelopes, 500 by default, and a user can set the limit from 1 to 50,000. +- A session name selects its newest open session, or its newest session when + none is open, because every `local run --session` creates a new one. A + session ID always selects that session. - A missing or evicted session, event, or envelope is a not-found error that names what is missing and the list command to run (`sentry-local#missing-session-exit`). diff --git a/docs/cli/local-control-plane.md b/docs/cli/local-control-plane.md index 04a530ce48..6aa54c96c4 100644 --- a/docs/cli/local-control-plane.md +++ b/docs/cli/local-control-plane.md @@ -50,8 +50,12 @@ Treat those URLs as credentials. Terminal output redacts them, including the `Starting:` line of `local run --session`; the wrapped app still gets the real URL. Use `--clientId ` to make session creation idempotent for retries. Once a retained session expires, reusing its key creates a fresh session with new capabilities. -Names must be unique for name-based queries; ambiguous names return HTTP 409 with guidance -to use the session ID. +A name resolves to its newest open session, or to its newest session when none is +open, and a session ID resolves to exactly that session. When several open sessions +share the name, control responses carry an `X-Sentry-Local-Session-Choice` header, +JSON with the chosen `id` and the `others` (each `id` and `createdAt`), and the CLI +prints a one-line note to stderr. Daemons from older CLIs answered a shared name with +HTTP 409 `ambiguous_session`; the CLI still reports that as a user error. Session lookup commands accept names quoted or as separate words. For `event view` and `envelope view`, the final argument is the telemetry ID; preceding arguments form the session name. Event lookup uses the Sentry event ID from the envelope diff --git a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md index b648fa4bc2..84c1a98707 100644 --- a/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md +++ b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md @@ -40,7 +40,7 @@ List retained envelopes for a Local session | Argument | Description | |----------|-------------| -| `` | Session ID or unique name | +| `` | Session ID or name | ### `sentry local envelope view ` @@ -60,7 +60,7 @@ List decoded events for a Local session | Argument | Description | |----------|-------------| -| `` | Session ID or unique name | +| `` | Session ID or name | ### `sentry local event view ` @@ -139,7 +139,7 @@ View or change session envelope retention | Argument | Description | |----------|-------------| -| `` | Session ID or unique name | +| `` | Session ID or name | **Flags:** - `--max-envelopes - Maximum envelopes retained by this receiver or session` @@ -156,7 +156,7 @@ View a Local telemetry session | Argument | Description | |----------|-------------| -| `` | Session ID or unique name | +| `` | Session ID or name | ### `sentry local session close ` @@ -166,7 +166,7 @@ Close a Local telemetry session | Argument | Description | |----------|-------------| -| `` | Session ID or unique name | +| `` | Session ID or name | ### `sentry local session reset ` @@ -176,7 +176,7 @@ Clear a Local telemetry session | Argument | Description | |----------|-------------| -| `` | Session ID or unique name | +| `` | Session ID or name | ### `sentry local run ` diff --git a/packages/cli/src/commands/local/control-plane.ts b/packages/cli/src/commands/local/control-plane.ts index cc7fc2202b..9a5ecdc19c 100644 --- a/packages/cli/src/commands/local/control-plane.ts +++ b/packages/cli/src/commands/local/control-plane.ts @@ -20,7 +20,6 @@ import { } from "./receiver-ingest.js"; import { type Context, Hono } from "hono"; import { cors } from "hono/cors"; -import { HTTPException } from "hono/http-exception"; import { streamSSE } from "hono/streaming"; import { stringifyUnknown } from "../../lib/errors.js"; import { SENTRY_CONTENT_TYPE } from "../../lib/formatters/local.js"; @@ -36,9 +35,7 @@ import { } from "./server.js"; import { logger } from "../../lib/logger.js"; import { - AMBIGUOUS_SESSION_CODE, createLocalSessionStore, - AmbiguousLocalSessionError, type LocalSessionStore, } from "./session-store.js"; @@ -56,6 +53,12 @@ import { } from "./retention-buffer.js"; export const CONTROL_PLANE_PREFIX = "/_local/v1"; + +/** + * Response header naming the session a shared name resolved to and the other + * open sessions with that name, as JSON `{ id, others: [{ id, createdAt }] }`. + */ +export const SESSION_CHOICE_HEADER = "X-Sentry-Local-Session-Choice"; const LOOPBACK_ORIGIN_RE = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/; const SESSION_UI_ACTION_RE = @@ -224,19 +227,6 @@ export function createLocalControlPlane({ sessionStore.resolve(reference); return true; } catch (error) { - if (error instanceof AmbiguousLocalSessionError) { - throw new HTTPException(409, { - res: Response.json( - { - error: error.message, - code: AMBIGUOUS_SESSION_CODE, - reference: error.reference, - sessionIds: error.sessionIds, - }, - { status: 409 }, - ), - }); - } logger.debug("Local session was not found", error); return false; } @@ -278,6 +268,31 @@ export function createLocalControlPlane({ await next(); return; }); + // Tell the CLI which session a shared name picked so it can say so. + // Capability-scoped stream and ingest requests never see sibling IDs. + for (const path of [ + `${CONTROL_PLANE_PREFIX}/sessions/:id`, + `${CONTROL_PLANE_PREFIX}/sessions/:id/*`, + ]) + app.use(path, async (c, next) => { + const reference = c.req.param("id"); + if ( + reference !== undefined && + hasControlCapability(c.req.raw, controlToken) && + sessionExists(reference) + ) { + const { session, others } = sessionStore.choose(reference); + if (others.length > 0) + c.header( + SESSION_CHOICE_HEADER, + JSON.stringify({ + id: session.id, + others: others.map(({ id, createdAt }) => ({ id, createdAt })), + }), + ); + } + await next(); + }); const loopbackCors = cors({ allowHeaders: [ "Content-Type", diff --git a/packages/cli/src/commands/local/management.ts b/packages/cli/src/commands/local/management.ts index 95a60afc92..0f97fa9775 100644 --- a/packages/cli/src/commands/local/management.ts +++ b/packages/cli/src/commands/local/management.ts @@ -16,6 +16,7 @@ import { ValidationError, } from "../../lib/errors.js"; import { formatLocalControlResult } from "../../lib/formatters/local.js"; +import { formatRelativeTime } from "../../lib/formatters/time-utils.js"; import { formatLocalEnvelopeList, formatLocalEventList, @@ -44,7 +45,8 @@ import { OPTIONAL_MAX_ENVELOPES_FLAG, } from "./retention-buffer.js"; import { LOOPBACK_HOSTS } from "./loopback.js"; -import { AMBIGUOUS_SESSION_CODE, type LocalSession } from "./session-store.js"; +import type { LocalSession } from "./session-store.js"; +import { SESSION_CHOICE_HEADER } from "./control-plane.js"; type DaemonFlags = { readonly foreground: boolean; @@ -91,7 +93,7 @@ const DAEMON_CONNECTION_FLAGS = { const SESSION_REFERENCE_POSITIONAL = { kind: "array", parameter: { - brief: "Session ID or unique name", + brief: "Session ID or name", parse: parseLocalSession, placeholder: "session", }, @@ -140,15 +142,74 @@ async function controlJson( 1, ); } + noteSessionChoice(response.headers.get(SESSION_CHOICE_HEADER)); if (response.status === 204 || response.status === 202) { return { ok: true }; } return (await response.json()) as ControlResult; } +type SessionChoice = { + id: string; + others: { id: string; createdAt: number }[]; +}; + +function isSessionChoice(value: unknown): value is SessionChoice { + return ( + typeof value === "object" && + value !== null && + "id" in value && + typeof value.id === "string" && + "others" in value && + Array.isArray(value.others) && + value.others.every( + (other: unknown) => + typeof other === "object" && + other !== null && + "id" in other && + typeof other.id === "string" && + "createdAt" in other && + Number.isFinite(other.createdAt), + ) + ); +} + +/** + * Say which session a name shared by several open sessions resolved to, so a + * caller that meant another one can pass its ID. + */ +function noteSessionChoice(header: string | null): void { + if (!header) { + return; + } + let choice: unknown; + try { + choice = JSON.parse(header); + } catch (error) { + logger.debug("Could not read the Local session choice", error); + return; + } + if (!isSessionChoice(choice) || choice.others.length === 0) { + return; + } + const others = choice.others + .map( + ({ id, createdAt }) => + `${id} (open, started ${formatRelativeTime(new Date(createdAt).toISOString())})`, + ) + .join(", "); + logger.warn( + `${choice.others.length + 1} open sessions share that name; using the newest, ${choice.id}. Pass a session ID to use another: ${others}.`, + ); +} + +/** `code` of the ambiguous-name 409 from a daemon that an older CLI started. */ +const AMBIGUOUS_SESSION_CODE = "ambiguous_session"; + /** - * Turn the control plane's ambiguous-name 409 into a user-input error. Session + * Turn an older daemon's ambiguous-name 409 into a user-input error. Session * labels may repeat, so a shared label is not a CLI failure (CLI-4T6, CLI-4FP). + * Current daemons resolve a shared name instead; see `noteSessionChoice`. */ function ambiguousSessionError(body: unknown): ResolutionError | undefined { if ( diff --git a/packages/cli/src/commands/local/session-store.ts b/packages/cli/src/commands/local/session-store.ts index 93bf43905c..f932d1f970 100644 --- a/packages/cli/src/commands/local/session-store.ts +++ b/packages/cli/src/commands/local/session-store.ts @@ -49,24 +49,14 @@ export type CreateLocalSessionInput = { readonly maxEnvelopes?: number | undefined; }; -/** `code` of the control plane's 409 body for an ambiguous session name. */ -export const AMBIGUOUS_SESSION_CODE = "ambiguous_session"; - -/** A label matches multiple sessions; callers must select an explicit ID. */ -export class AmbiguousLocalSessionError extends Error { - readonly reference: string; - /** IDs of the sessions that share the label. */ - readonly sessionIds: string[]; - - constructor(reference: string, sessionIds: string[]) { - super( - `Local session name "${reference}" is ambiguous; use its session ID.`, - ); - this.name = "AmbiguousLocalSessionError"; - this.reference = reference; - this.sessionIds = sessionIds; - } -} +/** + * The session a reference resolved to and the other open sessions that share + * its name; `others` is empty for a session ID or a name with one open session. + */ +export type LocalSessionChoice = { + readonly session: LocalSession; + readonly others: LocalSession[]; +}; /** In-memory session lifecycle and access to isolated telemetry buffers. */ export type LocalSessionStore = { @@ -87,6 +77,8 @@ export type LocalSessionStore = { list: () => LocalSession[]; pruneExpired: () => string[]; recordActivity: (reference: string) => LocalSession; + /** Resolve a session ID or name; see {@link LocalSessionChoice}. */ + choose: (reference: string) => LocalSessionChoice; resolve: (reference: string) => LocalSession; }; @@ -127,29 +119,33 @@ export function createLocalSessionStore({ ); const changed = () => onChange?.(list()); - const resolveStored = (reference: string): StoredSession => { + /** + * Resolve a session ID, or a name to the newest of its open sessions, or to + * its newest session when none is open. Names repeat because each + * `local run --session` creates a session. + */ + const chooseStored = ( + reference: string, + ): { session: StoredSession; others: StoredSession[] } => { const byId = sessions.get(reference); if (byId) { - return byId; + return { session: byId, others: [] }; } - const matches = [...sessions.values()].filter( - (session) => session.label === reference, - ); - if (matches.length === 0) { - throw new Error(`Local session "${reference}" was not found.`); - } - if (matches.length > 1) { - throw new AmbiguousLocalSessionError( - reference, - matches.map((session) => session.id), + const named = [...sessions.values()] + .filter((session) => session.label === reference) + .sort( + (left, right) => + right.createdAt - left.createdAt || right.id.localeCompare(left.id), ); - } - const [match] = matches; - if (!match) { + const open = named.filter((session) => session.state === "open"); + const [session] = open.length > 0 ? open : named; + if (!session) { throw new Error(`Local session "${reference}" was not found.`); } - return match; + return { session, others: open.filter((other) => other !== session) }; }; + const resolveStored = (reference: string): StoredSession => + chooseStored(reference).session; const update = ( session: StoredSession, @@ -276,6 +272,13 @@ export function createLocalSessionStore({ if (session.state === "retained") return toPublicSession(session); return toPublicSession(update(session, { lastActivityAt: now() })); }, + choose(reference) { + const { session, others } = chooseStored(reference); + return { + session: toPublicSession(session), + others: others.map(toPublicSession), + }; + }, resolve(reference) { return toPublicSession(resolveStored(reference)); }, diff --git a/packages/cli/test/commands/local/control-plane.test.ts b/packages/cli/test/commands/local/control-plane.test.ts index 76c34cdd93..ad78f713d9 100644 --- a/packages/cli/test/commands/local/control-plane.test.ts +++ b/packages/cli/test/commands/local/control-plane.test.ts @@ -1,7 +1,10 @@ import { request } from "node:http"; import { gzipSync } from "node:zlib"; import { describe, expect, test } from "vitest"; -import { createLocalControlPlane } from "../../../src/commands/local/control-plane.js"; +import { + createLocalControlPlane, + SESSION_CHOICE_HEADER, +} from "../../../src/commands/local/control-plane.js"; import { tryListen } from "../../../src/commands/local/server.js"; import { createLocalSessionStore, @@ -445,38 +448,43 @@ describe("Local control plane", () => { expect(plane.sessionStore.resolve(session.id).maxEnvelopes).toBe(50000); }); - test("reports ambiguous session names with ID guidance across control routes", async () => { + test("resolves a shared session name to its newest open session on every control route", async () => { const plane = createLocalControlPlane({ controlToken: CONTROL_TOKEN }); - const one = plane.sessionStore.create({ label: "My App", cwd: "/one" }); - const two = plane.sessionStore.create({ label: "My App", cwd: "/two" }); + const older = plane.sessionStore.create({ label: "My App", cwd: "/one" }); + const newer = plane.sessionStore.create({ label: "My App", cwd: "/two" }); + const closed = plane.sessionStore.create({ + label: "My App", + cwd: "/three", + }); + plane.sessionStore.close(closed.id); for (const [method, suffix] of [ ["GET", ""], ["GET", "/events"], ["GET", "/envelopes"], - ["GET", "/events/id"], - ["GET", "/envelopes/id"], - ["POST", "/close"], + ["GET", "/retention"], ["POST", "/reset"], ] as const) { const response = await plane.app.request( `/_local/v1/sessions/My%20App${suffix}`, { method, headers: controlHeaders() }, ); - expect(response.status).toBe(409); - await expect(response.json()).resolves.toEqual({ - error: 'Local session name "My App" is ambiguous; use its session ID.', - code: "ambiguous_session", - reference: "My App", - sessionIds: [one.id, two.id], + expect(response.status, suffix).toBeLessThan(300); + expect( + JSON.parse(response.headers.get(SESSION_CHOICE_HEADER) ?? "null"), + ).toEqual({ + id: newer.id, + others: [{ id: older.id, createdAt: older.createdAt }], }); } - expect( - ( - await plane.app.request(`/_local/v1/sessions/${one.id}`, { - headers: controlHeaders(), - }) - ).status, - ).toBe(200); + const viewed = await plane.app.request("/_local/v1/sessions/My%20App", { + headers: controlHeaders(), + }); + await expect(viewed.json()).resolves.toMatchObject({ id: newer.id }); + const byId = await plane.app.request(`/_local/v1/sessions/${older.id}`, { + headers: controlHeaders(), + }); + expect(byId.status).toBe(200); + expect(byId.headers.get(SESSION_CHOICE_HEADER)).toBeNull(); expect( ( await plane.app.request("/_local/v1/sessions/missing", { @@ -484,6 +492,23 @@ describe("Local control plane", () => { }) ).status, ).toBe(404); + + const closedResponse = await plane.app.request( + "/_local/v1/sessions/My%20App/close", + { method: "POST", headers: controlHeaders() }, + ); + await expect(closedResponse.json()).resolves.toMatchObject({ + id: newer.id, + state: "retained", + }); + const remaining = await plane.app.request("/_local/v1/sessions/My%20App", { + headers: controlHeaders(), + }); + expect(remaining.headers.get(SESSION_CHOICE_HEADER)).toBeNull(); + await expect(remaining.json()).resolves.toMatchObject({ + id: older.id, + state: "open", + }); }); test("creates isolated sessions through its authenticated control API", async () => { diff --git a/packages/cli/test/commands/local/management.test.ts b/packages/cli/test/commands/local/management.test.ts index fe70baa0aa..2327fd57ed 100644 --- a/packages/cli/test/commands/local/management.test.ts +++ b/packages/cli/test/commands/local/management.test.ts @@ -10,6 +10,7 @@ import { } from "../../../src/commands/local/management.js"; import { classifySilenced } from "../../../src/lib/error-reporting.js"; import { CliError, EXIT, ResolutionError } from "../../../src/lib/errors.js"; +import { logger } from "../../../src/lib/logger.js"; const CONTROL_TOKEN = "control-token"; const plane = createLocalControlPlane({ controlToken: CONTROL_TOKEN }); @@ -132,9 +133,45 @@ describe("local session view", () => { daemonResponse = undefined; }); - test("reports a shared session name as a user error that lists the IDs", async () => { - const one = plane.sessionStore.create({ label: "spike", cwd: "/one" }); - const two = plane.sessionStore.create({ label: "spike", cwd: "/two" }); + test("uses the newest open session for a reused name and notes the others", async () => { + const closed = plane.sessionStore.create({ label: "reused", cwd: "/old" }); + plane.sessionStore.close(closed.id); + const older = plane.sessionStore.create({ label: "reused", cwd: "/one" }); + const newer = plane.sessionStore.create({ label: "reused", cwd: "/two" }); + await ingestEvent(older.id, "a".repeat(32), "older run"); + await ingestEvent(newer.id, "b".repeat(32), "newer run"); + const warn = vi.spyOn(logger, "warn").mockImplementation(() => {}); + try { + const listed = await runCommand(eventRoute, "list", true, "reused"); + expect(listed.error).toBeUndefined(); + const { events } = JSON.parse(listed.stdout) as { + events: { eventId: string }[]; + }; + expect(events.map(({ eventId }) => eventId)).toEqual(["b".repeat(32)]); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn).toHaveBeenCalledWith( + `2 open sessions share that name; using the newest, ${newer.id}. Pass a session ID to use another: ${older.id} (open, started 0m ago).`, + ); + + warn.mockClear(); + const viewed = await runCommand(sessionRoute, "view", true, newer.id); + expect(JSON.parse(viewed.stdout)).toMatchObject({ id: newer.id }); + expect(warn).not.toHaveBeenCalled(); + } finally { + warn.mockRestore(); + } + }); + + test("reports an older daemon's shared-name 409 as a user error that lists the IDs", async () => { + daemonResponse = Response.json( + { + error: OLD_DAEMON_MESSAGE, + code: "ambiguous_session", + reference: "spike", + sessionIds: ["one", "two"], + }, + { status: 409 }, + ); const error = await viewError("spike"); @@ -144,8 +181,8 @@ describe("local session view", () => { /^Local session name "spike" matches more than one session\./, ); expect(message).not.toContain("HTTP 409"); - expect(message).toContain(`Use session ID ${one.id}`); - expect(message).toContain(`Use session ID ${two.id}`); + expect(message).toContain("Use session ID one"); + expect(message).toContain("Use session ID two"); expect(classifySilenced(error)).toBe("user_input_error"); }); diff --git a/packages/cli/test/commands/local/session-store.test.ts b/packages/cli/test/commands/local/session-store.test.ts index 98b1f37744..d029f9078e 100644 --- a/packages/cli/test/commands/local/session-store.test.ts +++ b/packages/cli/test/commands/local/session-store.test.ts @@ -90,12 +90,37 @@ describe("LocalSessionStore", () => { }); }); - test("rejects ambiguous labels instead of selecting an arbitrary session", () => { - const store = createLocalSessionStore({ now: () => 1000 }); - store.create({ label: "web", cwd: "/work/one" }); - store.create({ label: "web", cwd: "/work/two" }); + test("resolves a reused label to its open session, else the newest one", () => { + let now = 1000; + const store = createLocalSessionStore({ now: () => now }); + const first = store.create({ label: "web", cwd: "/work/one" }); + now = 2000; + const second = store.create({ label: "web", cwd: "/work/two" }); + store.close(second.id); + + expect(store.resolve("web").id).toBe(first.id); + expect(store.choose("web").others).toEqual([]); + store.close(first.id); + expect(store.resolve("web").id).toBe(second.id); + expect(() => store.resolve("api")).toThrow(/not found/); + }); - expect(() => store.resolve("web")).toThrow(/ambiguous/i); + test("picks the newest open session for a shared label and names the others", () => { + let now = 1000; + const store = createLocalSessionStore({ now: () => now }); + const older = store.create({ label: "web", cwd: "/work/one" }); + now = 2000; + const newer = store.create({ label: "web", cwd: "/work/two" }); + now = 3000; + store.recordActivity(older.id); + + const choice = store.choose("web"); + expect(choice.session.id).toBe(newer.id); + expect(choice.others.map(({ id }) => id)).toEqual([older.id]); + expect(store.choose(older.id)).toMatchObject({ + session: { id: older.id }, + others: [], + }); }); test("reuses a session when an agent retries with the same client ID", () => { diff --git a/packages/cli/test/e2e/local.test.ts b/packages/cli/test/e2e/local.test.ts index 08b75d7ac3..3e14dc6cd7 100644 --- a/packages/cli/test/e2e/local.test.ts +++ b/packages/cli/test/e2e/local.test.ts @@ -463,24 +463,38 @@ describe("Local daemon E2E", () => { 30_000, ); - test("surfaces duplicate session name guidance through the CLI", async () => { + test("resolves a reused session name to its newest open session through the CLI", async () => { const port = await availablePort(); const first = await createSession("duplicate", port); - await createSession("duplicate", port); + const second = await createSession("duplicate", port); for (const parts of [ ["session", "view"], - ["session", "close"], ["event", "list"], ["envelope", "list"], ]) { const result = await cli(...parts, "duplicate"); - expect(result.exitCode).toBe(23); + expect(result.exitCode, result.stderr).toBe(0); expect(result.stderr).toContain( - 'Local session name "duplicate" matches more than one session.', + `2 open sessions share that name; using the newest, ${second.id}.`, ); - expect(result.stderr).toContain(`Use session ID ${first.id}`); + expect(result.stderr).toContain(`${first.id} (open, started`); } - expect((await cli("session", "view", first.id)).exitCode).toBe(0); + const viewed = await cli("session", "view", "duplicate"); + expect(JSON.parse(viewed.stdout)).toMatchObject({ id: second.id }); + + const closed = await cli("session", "close", "duplicate"); + expect(closed.exitCode, closed.stderr).toBe(0); + expect(JSON.parse(closed.stdout)).toMatchObject({ + id: second.id, + state: "retained", + }); + const remaining = await cli("session", "view", "duplicate"); + expect(remaining.exitCode, remaining.stderr).toBe(0); + expect(remaining.stderr).not.toContain("share that name"); + expect(JSON.parse(remaining.stdout)).toMatchObject({ + id: first.id, + state: "open", + }); }, 30_000); test("isolates sessions and capabilities, queries retained telemetry and clears only one session", async () => { From bb5ee0063989fd759febfc21cb77e67d82832287 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:13:26 +0000 Subject: [PATCH 2/4] test(cli): Reuse the loop's session view in the reused-name e2e Co-Authored-By: Aditya Mathur <57684218+MathurAditya724@users.noreply.github.com> --- packages/cli/test/e2e/local.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/cli/test/e2e/local.test.ts b/packages/cli/test/e2e/local.test.ts index 3e14dc6cd7..097e7c1633 100644 --- a/packages/cli/test/e2e/local.test.ts +++ b/packages/cli/test/e2e/local.test.ts @@ -478,9 +478,9 @@ describe("Local daemon E2E", () => { `2 open sessions share that name; using the newest, ${second.id}.`, ); expect(result.stderr).toContain(`${first.id} (open, started`); + if (parts[0] === "session") + expect(JSON.parse(result.stdout)).toMatchObject({ id: second.id }); } - const viewed = await cli("session", "view", "duplicate"); - expect(JSON.parse(viewed.stdout)).toMatchObject({ id: second.id }); const closed = await cli("session", "close", "duplicate"); expect(closed.exitCode, closed.stderr).toBe(0); From ea9be5d2b2e96584a1cf914334ce6d7c87438e3f Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:36:43 +0000 Subject: [PATCH 3/4] fix(cli): Refuse ambiguous Local session names for changes Reads by a name that several open sessions share still use the newest, but close, reset, and retention changes now answer 409 ambiguous_session with each match's state and age, so a second `session close ` cannot close a live run in another terminal. The CLI lists them as hints. The choice header now names at most five other sessions plus a `more` count, so a pile of runs that were killed and never closed cannot push it past fetch's header limit. Each route resolves its session once, the note also prints on error responses and only once per session, and the header name lives in the session store instead of the Hono app module. Co-Authored-By: Aditya Mathur <57684218+MathurAditya724@users.noreply.github.com> --- apps/cli-docs/src/fragments/commands/local.md | 10 +- design/sentry-local.md | 7 +- docs/cli/local-control-plane.md | 14 +- .../cli/src/commands/local/control-plane.ts | 194 ++++++++++-------- packages/cli/src/commands/local/management.ts | 96 ++++++--- .../cli/src/commands/local/session-store.ts | 16 +- .../test/commands/local/control-plane.test.ts | 92 +++++++-- .../test/commands/local/management.test.ts | 74 +++++++ packages/cli/test/e2e/local.test.ts | 14 +- 9 files changed, 375 insertions(+), 142 deletions(-) diff --git a/apps/cli-docs/src/fragments/commands/local.md b/apps/cli-docs/src/fragments/commands/local.md index be42844eb3..f2b888fe75 100644 --- a/apps/cli-docs/src/fragments/commands/local.md +++ b/apps/cli-docs/src/fragments/commands/local.md @@ -277,10 +277,12 @@ same way without wrapping a command. viewer read capability URLs. Keep these URLs private. `--clientId ` makes retried session creation idempotent. -Each `local run --session` creates a new session, so names repeat. A name -picks its newest open session, or its newest session when none is open. When -several open sessions share the name, the command uses the newest and notes the -others on stderr; pass a session ID to pick one of them. +Each `local run --session` creates a new session, so names repeat. Commands +that read, such as `event list` and `session view`, use the name's newest open +session, or its newest session when none is open. When several open sessions +share the name, they use the newest and note the others on stderr. `session +close` and other commands that change a session refuse a name that several open +sessions share and list them, so pass the session ID instead. How an SDK reaches a session depends on its Spotlight support: diff --git a/design/sentry-local.md b/design/sentry-local.md index d15e88773f..3a76f80544 100644 --- a/design/sentry-local.md +++ b/design/sentry-local.md @@ -41,9 +41,10 @@ account. `sentry-local#stop-clears`). - Each session or receiver keeps its most recent envelopes, 500 by default, and a user can set the limit from 1 to 50,000. -- A session name selects its newest open session, or its newest session when - none is open, because every `local run --session` creates a new one. A - session ID always selects that session. +- A session name reads from its newest open session, or its newest session + when none is open, because every `local run --session` creates a new one. + Close, reset, and retention changes refuse a name that several open sessions + share. A session ID always selects that session. - A missing or evicted session, event, or envelope is a not-found error that names what is missing and the list command to run (`sentry-local#missing-session-exit`). diff --git a/docs/cli/local-control-plane.md b/docs/cli/local-control-plane.md index 6aa54c96c4..8d2041fd69 100644 --- a/docs/cli/local-control-plane.md +++ b/docs/cli/local-control-plane.md @@ -50,12 +50,14 @@ Treat those URLs as credentials. Terminal output redacts them, including the `Starting:` line of `local run --session`; the wrapped app still gets the real URL. Use `--clientId ` to make session creation idempotent for retries. Once a retained session expires, reusing its key creates a fresh session with new capabilities. -A name resolves to its newest open session, or to its newest session when none is -open, and a session ID resolves to exactly that session. When several open sessions -share the name, control responses carry an `X-Sentry-Local-Session-Choice` header, -JSON with the chosen `id` and the `others` (each `id` and `createdAt`), and the CLI -prints a one-line note to stderr. Daemons from older CLIs answered a shared name with -HTTP 409 `ambiguous_session`; the CLI still reports that as a user error. +A session ID resolves to exactly that session. For reads, a name resolves to its newest +open session, or to its newest session when none is open. When several open sessions +share the name, read responses carry an `X-Sentry-Local-Session-Choice` header, JSON +with the chosen `id`, up to five `others` (each `id` and `createdAt`), and a `more` +count of the rest, and the CLI prints a one-line note to stderr. Close, reset, and +retention changes refuse such a name with HTTP 409 `ambiguous_session`, listing every +match in `sessions` with its `id`, `state`, and `createdAt`; the CLI reports that as a +user error. Daemons from older CLIs answered every shared-name lookup with that 409. Session lookup commands accept names quoted or as separate words. For `event view` and `envelope view`, the final argument is the telemetry ID; preceding arguments form the session name. Event lookup uses the Sentry event ID from the envelope diff --git a/packages/cli/src/commands/local/control-plane.ts b/packages/cli/src/commands/local/control-plane.ts index 9a5ecdc19c..0b8cbc37ee 100644 --- a/packages/cli/src/commands/local/control-plane.ts +++ b/packages/cli/src/commands/local/control-plane.ts @@ -20,6 +20,7 @@ import { } from "./receiver-ingest.js"; import { type Context, Hono } from "hono"; import { cors } from "hono/cors"; +import { HTTPException } from "hono/http-exception"; import { streamSSE } from "hono/streaming"; import { stringifyUnknown } from "../../lib/errors.js"; import { SENTRY_CONTENT_TYPE } from "../../lib/formatters/local.js"; @@ -35,8 +36,12 @@ import { } from "./server.js"; import { logger } from "../../lib/logger.js"; import { + AMBIGUOUS_SESSION_CODE, createLocalSessionStore, + type LocalSessionChoice, type LocalSessionStore, + SESSION_CHOICE_HEADER, + SESSION_CHOICE_LIMIT, } from "./session-store.js"; import { @@ -53,12 +58,6 @@ import { } from "./retention-buffer.js"; export const CONTROL_PLANE_PREFIX = "/_local/v1"; - -/** - * Response header naming the session a shared name resolved to and the other - * open sessions with that name, as JSON `{ id, others: [{ id, createdAt }] }`. - */ -export const SESSION_CHOICE_HEADER = "X-Sentry-Local-Session-Choice"; const LOOPBACK_ORIGIN_RE = /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/; const SESSION_UI_ACTION_RE = @@ -221,15 +220,62 @@ export function createLocalControlPlane({ // This token dies with the daemon and never authorizes the control API. const viewerCapability = randomBytes(24).toString("base64url"); const directoryUrl = `${baseUrl}${VIEWER_SESSIONS_PATH}?cap=${viewerCapability}`; - const sessionExists = (reference: string): boolean => { + /** + * Resolve the route's session ID or name once per request, so a session + * created or closed mid-request cannot switch the target. A name that + * several open sessions share reads from the newest, which control clients + * see in {@link SESSION_CHOICE_HEADER}. A `write` refuses it with a 409 that + * lists them, so close, reset, and retention never act on a guess. + */ + const routeSessionId = ( + c: Context, + access: "read" | "write" = "read", + ): string | undefined => { + const reference = c.req.param("id") ?? ""; sessionStore.pruneExpired(); + let choice: LocalSessionChoice; try { - sessionStore.resolve(reference); - return true; + choice = sessionStore.choose(reference); } catch (error) { logger.debug("Local session was not found", error); - return false; + return undefined; + } + const { session, others } = choice; + if (others.length === 0) return session.id; + if (access === "write") { + const sessions = [session, ...others]; + throw new HTTPException(409, { + res: Response.json( + { + error: `Local session name "${reference}" is ambiguous; use its session ID.`, + code: AMBIGUOUS_SESSION_CODE, + reference, + sessionIds: sessions.map(({ id }) => id), + sessions: sessions.map(({ id, state, createdAt }) => ({ + id, + state, + createdAt, + })), + }, + { status: 409 }, + ), + }); } + // Capability-scoped stream and ingest requests never see sibling IDs. + if (hasControlCapability(c.req.raw, controlToken)) + c.header( + SESSION_CHOICE_HEADER, + JSON.stringify({ + id: session.id, + others: others + .slice(0, SESSION_CHOICE_LIMIT) + .map(({ id, createdAt }) => ({ id, createdAt })), + ...(others.length > SESSION_CHOICE_LIMIT && { + more: others.length - SESSION_CHOICE_LIMIT, + }), + }), + ); + return session.id; }; app.use("*", async (c, next) => { @@ -268,31 +314,6 @@ export function createLocalControlPlane({ await next(); return; }); - // Tell the CLI which session a shared name picked so it can say so. - // Capability-scoped stream and ingest requests never see sibling IDs. - for (const path of [ - `${CONTROL_PLANE_PREFIX}/sessions/:id`, - `${CONTROL_PLANE_PREFIX}/sessions/:id/*`, - ]) - app.use(path, async (c, next) => { - const reference = c.req.param("id"); - if ( - reference !== undefined && - hasControlCapability(c.req.raw, controlToken) && - sessionExists(reference) - ) { - const { session, others } = sessionStore.choose(reference); - if (others.length > 0) - c.header( - SESSION_CHOICE_HEADER, - JSON.stringify({ - id: session.id, - others: others.map(({ id, createdAt }) => ({ id, createdAt })), - }), - ); - } - await next(); - }); const loopbackCors = cors({ allowHeaders: [ "Content-Type", @@ -438,10 +459,11 @@ export function createLocalControlPlane({ }); app.get(`${CONTROL_PLANE_PREFIX}/sessions/:id`, (c) => { - if (!sessionExists(c.req.param("id"))) { + const id = routeSessionId(c); + if (!id) { return c.body(null, 404); } - const session = sessionStore.resolve(c.req.param("id")); + const session = sessionStore.resolve(id); const capabilities = sessionStore.getCapabilities(session.id); const path = `${CONTROL_PLANE_PREFIX}/sessions/${session.id}`; return c.json({ @@ -501,23 +523,23 @@ export function createLocalControlPlane({ // Node SDK Spotlight transports send pathname only, so the ingest capability // must live in the path. Keep query-based ingestion for existing raw clients. const ingest = async (c: Context) => { - const reference = c.req.param("id") ?? ""; - if (!sessionExists(reference)) { + const id = routeSessionId(c); + if (!id) { return c.body(null, 404); } - const capabilities = sessionStore.getCapabilities(reference); + const capabilities = sessionStore.getCapabilities(id); if ((c.req.param("cap") ?? c.req.query("cap")) !== capabilities.ingest) { return c.body(null, 401); } - const isClosed = () => sessionStore.resolve(reference).state === "retained"; + const isClosed = () => sessionStore.resolve(id).state === "retained"; const closed = () => c.json( { error: "Session is closed; create a new session to capture events." }, 410, ); if (isClosed()) return closed(); - const buffer = sessionStore.getBuffer(reference); + const buffer = sessionStore.getBuffer(id); const browserBeacon = c.req.query("sentry_client")?.startsWith("sentry.javascript.browser") && c.req.header("origin"); @@ -547,24 +569,24 @@ export function createLocalControlPlane({ }); if (status === 410) return closed(); if (status === 503) c.header("Retry-After", "1"); - if (status === 204) sessionStore.recordActivity(reference); + if (status === 204) sessionStore.recordActivity(id); return c.body(null, status); }; for (const path of SESSION_INGEST_PATHS) app.post(path, ingest); app.post(`${CONTROL_PLANE_PREFIX}/sessions/:id/stream`, ingest); app.get(`${CONTROL_PLANE_PREFIX}/sessions/:id/stream`, (c) => { - if (!sessionExists(c.req.param("id"))) { + const id = routeSessionId(c); + if (!id) { return c.body(null, 404); } - const capabilities = sessionStore.getCapabilities(c.req.param("id")); - const buffer = sessionStore.getBuffer(c.req.param("id")); + const capabilities = sessionStore.getCapabilities(id); + const buffer = sessionStore.getBuffer(id); if (c.req.query("cap") !== capabilities.stream) { return c.body(null, 401); } return streamSSE(c, async (stream) => { - const reference = c.req.param("id"); - const retention = sessionStore.getRetention(reference); + const retention = sessionStore.getRetention(id); // Serialize metadata and envelopes so a close notification is the final // message, after every envelope accepted before capture stopped. let pending = Promise.resolve(); @@ -607,7 +629,7 @@ export function createLocalControlPlane({ const finished = new Promise((resolve) => { finish = resolve; }); - const unsubscribeSession = sessionStore.subscribe(reference, (event) => { + const unsubscribeSession = sessionStore.subscribe(id, (event) => { if (event.state === "retained" && event.action !== "reset") { void drainReceiver(buffer) .then(async () => { @@ -622,7 +644,7 @@ export function createLocalControlPlane({ }); stream.onAbort(finish); try { - const { state, expiresAt } = sessionStore.resolve(reference); + const { state, expiresAt } = sessionStore.resolve(id); if (state === "retained") { await drainReceiver(buffer); buffer.stream(readerId); @@ -641,7 +663,7 @@ export function createLocalControlPlane({ }); }); - const updateRetention = async (c: Context) => { + const updateRetention = async (c: Context, id: string) => { const input: unknown = await c.req.json().catch(() => undefined); const value = typeof input === "object" && input !== null && "maxEnvelopes" in input @@ -649,67 +671,72 @@ export function createLocalControlPlane({ : undefined; try { validateMaxEnvelopes(value); - await sessionStore.setMaxEnvelopes(c.req.param("id") ?? "", value); - return c.json( - sessionStore.getRetention(c.req.param("id") ?? "").getSettings(), - ); + await sessionStore.setMaxEnvelopes(id, value); + return c.json(sessionStore.getRetention(id).getSettings()); } catch (error) { if (error instanceof RetentionLimitError) return c.json({ error: error.message }, error.status); throw error; } }; - app.get(`${CONTROL_PLANE_PREFIX}/sessions/:id/retention`, (c) => - sessionExists(c.req.param("id")) - ? c.json(sessionStore.getRetention(c.req.param("id")).getSettings()) - : c.body(null, 404), - ); + app.get(`${CONTROL_PLANE_PREFIX}/sessions/:id/retention`, (c) => { + const id = routeSessionId(c); + return id + ? c.json(sessionStore.getRetention(id).getSettings()) + : c.body(null, 404); + }); app.post(`${CONTROL_PLANE_PREFIX}/sessions/:id/retention`, async (c) => { - if (!sessionExists(c.req.param("id"))) { + const id = routeSessionId(c, "write"); + if (!id) { return c.body(null, 404); } - return await updateRetention(c); + return await updateRetention(c, id); }); app.post(`${CONTROL_PLANE_PREFIX}/sessions/:id/reset`, (c) => { - if (!sessionExists(c.req.param("id"))) { + const id = routeSessionId(c, "write"); + if (!id) { return c.body(null, 404); } - sessionStore.reset(c.req.param("id")); + sessionStore.reset(id); return c.body(null, 204); }); app.post(`${CONTROL_PLANE_PREFIX}/sessions/:id/close`, (c) => { - if (!sessionExists(c.req.param("id"))) { + const id = routeSessionId(c, "write"); + if (!id) { return c.body(null, 404); } - return c.json(sessionStore.close(c.req.param("id"))); + return c.json(sessionStore.close(id)); }); app.post(`${CONTROL_PLANE_PREFIX}/sessions/:id/ui/:action`, async (c) => { - if (!(isSessionUiAction(c.req.path) && sessionExists(c.req.param("id")))) { + if (!isSessionUiAction(c.req.path)) { return c.body(null, 404); } - if ( - c.req.query("cap") !== - sessionStore.getCapabilities(c.req.param("id")).stream - ) { + const id = routeSessionId(c, "write"); + if (!id) { + return c.body(null, 404); + } + if (c.req.query("cap") !== sessionStore.getCapabilities(id).stream) { return c.body(null, 401); } - if (c.req.param("action") === "retention") return await updateRetention(c); + if (c.req.param("action") === "retention") + return await updateRetention(c, id); if (c.req.param("action") === "reset") { - sessionStore.reset(c.req.param("id")); + sessionStore.reset(id); return c.body(null, 204); } - return c.json(sessionStore.close(c.req.param("id"))); + return c.json(sessionStore.close(id)); }); app.get(`${CONTROL_PLANE_PREFIX}/sessions/:id/envelopes`, (c) => { - if (!sessionExists(c.req.param("id"))) { + const id = routeSessionId(c); + if (!id) { return c.body(null, 404); } const envelopes = sessionStore - .getBuffer(c.req.param("id")) + .getBuffer(id) .read({ all: true }) .map((container) => { const parsed = container.getParsedEnvelope(); @@ -733,11 +760,12 @@ export function createLocalControlPlane({ }); app.get(`${CONTROL_PLANE_PREFIX}/sessions/:id/events`, (c) => { - if (!sessionExists(c.req.param("id"))) { + const id = routeSessionId(c); + if (!id) { return c.body(null, 404); } const events = sessionStore - .getBuffer(c.req.param("id")) + .getBuffer(id) .read({ all: true }) .flatMap((container) => { const parsed = container.getParsedEnvelope(); @@ -751,12 +779,13 @@ export function createLocalControlPlane({ }); app.get(`${CONTROL_PLANE_PREFIX}/sessions/:id/events/:eventId`, (c) => { - if (!sessionExists(c.req.param("id"))) { + const id = routeSessionId(c); + if (!id) { return c.body(null, 404); } const reference = c.req.param("eventId"); const events = sessionStore - .getBuffer(c.req.param("id")) + .getBuffer(id) .read({ all: true }) .flatMap((container) => { const parsed = container.getParsedEnvelope(); @@ -791,11 +820,12 @@ export function createLocalControlPlane({ }); app.get(`${CONTROL_PLANE_PREFIX}/sessions/:id/envelopes/:envelopeId`, (c) => { - if (!sessionExists(c.req.param("id"))) { + const id = routeSessionId(c); + if (!id) { return c.body(null, 404); } const container = sessionStore - .getBuffer(c.req.param("id")) + .getBuffer(id) .read({ envelopeId: c.req.param("envelopeId") })[0]; if (!container) { return c.body(null, 404); diff --git a/packages/cli/src/commands/local/management.ts b/packages/cli/src/commands/local/management.ts index 0f97fa9775..7a5b555181 100644 --- a/packages/cli/src/commands/local/management.ts +++ b/packages/cli/src/commands/local/management.ts @@ -45,8 +45,11 @@ import { OPTIONAL_MAX_ENVELOPES_FLAG, } from "./retention-buffer.js"; import { LOOPBACK_HOSTS } from "./loopback.js"; -import type { LocalSession } from "./session-store.js"; -import { SESSION_CHOICE_HEADER } from "./control-plane.js"; +import { + AMBIGUOUS_SESSION_CODE, + type LocalSession, + SESSION_CHOICE_HEADER, +} from "./session-store.js"; type DaemonFlags = { readonly foreground: boolean; @@ -117,6 +120,7 @@ async function controlJson( ): Promise { const state = await ensureLocalDaemon(daemon); const response = await requestLocalDaemon(state, path, init); + noteSessionChoice(response.headers.get(SESSION_CHOICE_HEADER)); if (response.status === 404 && notFound) { await response.body?.cancel(); throw await notFound(); @@ -142,7 +146,6 @@ async function controlJson( 1, ); } - noteSessionChoice(response.headers.get(SESSION_CHOICE_HEADER)); if (response.status === 204 || response.status === 202) { return { ok: true }; } @@ -152,14 +155,21 @@ async function controlJson( type SessionChoice = { id: string; others: { id: string; createdAt: number }[]; + more?: number; }; +/** A session's state and when it started, such as `open, started 4m ago`. */ +function describeSession(state: unknown, createdAt: number): string { + return `${state === "open" ? "open" : "closed"}, started ${formatRelativeTime(new Date(createdAt).toISOString())}`; +} + function isSessionChoice(value: unknown): value is SessionChoice { return ( typeof value === "object" && value !== null && "id" in value && typeof value.id === "string" && + (!("more" in value) || Number.isInteger(value.more)) && "others" in value && Array.isArray(value.others) && value.others.every( @@ -174,6 +184,9 @@ function isSessionChoice(value: unknown): value is SessionChoice { ); } +/** Sessions already named in a note, so one command says it once. */ +const notedSessionChoices = new Set(); + /** * Say which session a name shared by several open sessions resolved to, so a * caller that meant another one can pass its ID. @@ -189,27 +202,58 @@ function noteSessionChoice(header: string | null): void { logger.debug("Could not read the Local session choice", error); return; } - if (!isSessionChoice(choice) || choice.others.length === 0) { + if ( + !isSessionChoice(choice) || + choice.others.length === 0 || + notedSessionChoices.has(choice.id) + ) { return; } + notedSessionChoices.add(choice.id); + const more = choice.more ?? 0; const others = choice.others - .map( - ({ id, createdAt }) => - `${id} (open, started ${formatRelativeTime(new Date(createdAt).toISOString())})`, - ) + .map(({ id, createdAt }) => `${id} (${describeSession("open", createdAt)})`) .join(", "); logger.warn( - `${choice.others.length + 1} open sessions share that name; using the newest, ${choice.id}. Pass a session ID to use another: ${others}.`, + `${choice.others.length + more + 1} open sessions share that name; using the newest, ${choice.id}. Pass a session ID to use another: ${others}${more > 0 ? ` and ${more} more` : ""}.`, ); } -/** `code` of the ambiguous-name 409 from a daemon that an older CLI started. */ -const AMBIGUOUS_SESSION_CODE = "ambiguous_session"; +/** Most matching sessions or events that an ambiguity error lists. */ +const AMBIGUOUS_HINT_LIMIT = 10; + +/** Hints for the first {@link AMBIGUOUS_HINT_LIMIT} matches, then a count. */ +function ambiguityHints(hints: string[]): string[] { + return hints.length > AMBIGUOUS_HINT_LIMIT + ? [ + ...hints.slice(0, AMBIGUOUS_HINT_LIMIT), + `+${hints.length - AMBIGUOUS_HINT_LIMIT} more`, + ] + : hints; +} + +/** The `sessions` of an ambiguous-name 409 as hints with state and age. */ +function sessionHints(sessions: unknown[]): string[] { + return sessions.flatMap((session) => + typeof session === "object" && + session !== null && + "id" in session && + typeof session.id === "string" && + "createdAt" in session && + typeof session.createdAt === "number" && + Number.isFinite(session.createdAt) + ? [ + `Use session ID ${session.id} (${describeSession("state" in session ? session.state : undefined, session.createdAt)})`, + ] + : [], + ); +} /** - * Turn an older daemon's ambiguous-name 409 into a user-input error. Session - * labels may repeat, so a shared label is not a CLI failure (CLI-4T6, CLI-4FP). - * Current daemons resolve a shared name instead; see `noteSessionChoice`. + * Turn the control plane's ambiguous-name 409 into a user-input error. A + * current daemon returns it when a change such as close names a session that + * several open sessions share; an older daemon returns it for any lookup. + * Session labels may repeat, so this is not a CLI failure (CLI-4T6, CLI-4FP). */ function ambiguousSessionError(body: unknown): ResolutionError | undefined { if ( @@ -222,21 +266,22 @@ function ambiguousSessionError(body: unknown): ResolutionError | undefined { ) { return; } - const sessionIds = - "sessionIds" in body && Array.isArray(body.sessionIds) - ? body.sessionIds.filter((id): id is string => typeof id === "string") - : []; + const hints = + "sessions" in body && Array.isArray(body.sessions) + ? sessionHints(body.sessions) + : "sessionIds" in body && Array.isArray(body.sessionIds) + ? body.sessionIds + .filter((id): id is string => typeof id === "string") + .map((id) => `Use session ID ${id}`) + : []; return new ResolutionError( `Local session name "${redactCredentialText(body.reference)}"`, "matches more than one session", sentry`local session list`, - sessionIds.map((id) => `Use session ID ${id}`), + ambiguityHints(hints), ); } -/** Most matching event IDs that an ambiguous `local event view` error lists. */ -const AMBIGUOUS_EVENT_HINT_LIMIT = 10; - /** * Turn the control plane's 409 for an event ID prefix that matches several * events into a user-input error that lists them. @@ -260,12 +305,7 @@ function ambiguousEventError(body: unknown): ResolutionError | undefined { const eventIds = body.eventIds.filter( (id): id is string => typeof id === "string", ); - const hints = eventIds - .slice(0, AMBIGUOUS_EVENT_HINT_LIMIT) - .map((id) => `Use event ID ${id}`); - if (eventIds.length > AMBIGUOUS_EVENT_HINT_LIMIT) { - hints.push(`+${eventIds.length - AMBIGUOUS_EVENT_HINT_LIMIT} more`); - } + const hints = ambiguityHints(eventIds.map((id) => `Use event ID ${id}`)); return new ResolutionError( `Local event ID "${redactCredentialText(body.reference)}"`, `matches more than one event in session "${session}"`, diff --git a/packages/cli/src/commands/local/session-store.ts b/packages/cli/src/commands/local/session-store.ts index f932d1f970..8d79b133b9 100644 --- a/packages/cli/src/commands/local/session-store.ts +++ b/packages/cli/src/commands/local/session-store.ts @@ -49,6 +49,20 @@ export type CreateLocalSessionInput = { readonly maxEnvelopes?: number | undefined; }; +/** `code` of the control plane's 409 body for an ambiguous session name. */ +export const AMBIGUOUS_SESSION_CODE = "ambiguous_session"; + +/** + * Response header naming the session a shared name resolved to for a read, + * as JSON `{ id, others: [{ id, createdAt }], more? }`. `others` lists at most + * {@link SESSION_CHOICE_LIMIT} of the other open sessions and `more` counts + * the rest, which keeps the header small however many runs were left open. + */ +export const SESSION_CHOICE_HEADER = "X-Sentry-Local-Session-Choice"; + +/** Most other open sessions that {@link SESSION_CHOICE_HEADER} names. */ +export const SESSION_CHOICE_LIMIT = 5; + /** * The session a reference resolved to and the other open sessions that share * its name; `others` is empty for a session ID or a name with one open session. @@ -135,7 +149,7 @@ export function createLocalSessionStore({ .filter((session) => session.label === reference) .sort( (left, right) => - right.createdAt - left.createdAt || right.id.localeCompare(left.id), + right.createdAt - left.createdAt || (left.id < right.id ? 1 : -1), ); const open = named.filter((session) => session.state === "open"); const [session] = open.length > 0 ? open : named; diff --git a/packages/cli/test/commands/local/control-plane.test.ts b/packages/cli/test/commands/local/control-plane.test.ts index ad78f713d9..4bf4a1ebf4 100644 --- a/packages/cli/test/commands/local/control-plane.test.ts +++ b/packages/cli/test/commands/local/control-plane.test.ts @@ -1,13 +1,11 @@ import { request } from "node:http"; import { gzipSync } from "node:zlib"; import { describe, expect, test } from "vitest"; -import { - createLocalControlPlane, - SESSION_CHOICE_HEADER, -} from "../../../src/commands/local/control-plane.js"; +import { createLocalControlPlane } from "../../../src/commands/local/control-plane.js"; import { tryListen } from "../../../src/commands/local/server.js"; import { createLocalSessionStore, + SESSION_CHOICE_HEADER, SESSION_RETENTION_MS, } from "../../../src/commands/local/session-store.js"; import { at } from "../../helpers.js"; @@ -462,7 +460,6 @@ describe("Local control plane", () => { ["GET", "/events"], ["GET", "/envelopes"], ["GET", "/retention"], - ["POST", "/reset"], ] as const) { const response = await plane.app.request( `/_local/v1/sessions/My%20App${suffix}`, @@ -493,14 +490,7 @@ describe("Local control plane", () => { ).status, ).toBe(404); - const closedResponse = await plane.app.request( - "/_local/v1/sessions/My%20App/close", - { method: "POST", headers: controlHeaders() }, - ); - await expect(closedResponse.json()).resolves.toMatchObject({ - id: newer.id, - state: "retained", - }); + plane.sessionStore.close(newer.id); const remaining = await plane.app.request("/_local/v1/sessions/My%20App", { headers: controlHeaders(), }); @@ -511,6 +501,82 @@ describe("Local control plane", () => { }); }); + test("refuses to change a session by a name that several open sessions share", async () => { + const plane = createLocalControlPlane({ controlToken: CONTROL_TOKEN }); + const older = plane.sessionStore.create({ label: "p", cwd: "/one" }); + const newer = plane.sessionStore.create({ label: "p", cwd: "/two" }); + const { stream } = plane.sessionStore.getCapabilities(newer.id); + for (const [suffix, body] of [ + ["/close", "{}"], + ["/reset", "{}"], + ["/retention", JSON.stringify({ maxEnvelopes: 10 })], + [`/ui/close?cap=${stream}`, "{}"], + ] as const) { + const response = await plane.app.request( + `/_local/v1/sessions/p${suffix}`, + { + method: "POST", + headers: { ...controlHeaders(), "Content-Type": "application/json" }, + body, + }, + ); + expect(response.status, suffix).toBe(409); + expect(response.headers.get(SESSION_CHOICE_HEADER)).toBeNull(); + await expect(response.json()).resolves.toMatchObject({ + code: "ambiguous_session", + reference: "p", + sessionIds: [newer.id, older.id], + sessions: [ + { id: newer.id, state: "open", createdAt: newer.createdAt }, + { id: older.id, state: "open", createdAt: older.createdAt }, + ], + }); + } + expect(plane.sessionStore.resolve(newer.id)).toMatchObject({ + state: "open", + maxEnvelopes: newer.maxEnvelopes, + }); + expect(plane.sessionStore.resolve(older.id).state).toBe("open"); + + const byId = await plane.app.request( + `/_local/v1/sessions/${newer.id}/close`, + { + method: "POST", + headers: controlHeaders(), + }, + ); + expect(byId.status).toBe(200); + const byName = await plane.app.request("/_local/v1/sessions/p/close", { + method: "POST", + headers: controlHeaders(), + }); + await expect(byName.json()).resolves.toMatchObject({ + id: older.id, + state: "retained", + }); + }); + + test("caps the sessions it names when many open sessions share a name", async () => { + const plane = createLocalControlPlane({ controlToken: CONTROL_TOKEN }); + const sessions = Array.from({ length: 300 }, () => + plane.sessionStore.create({ label: "busy", cwd: "/busy" }), + ); + const response = await plane.app.request("/_local/v1/sessions/busy", { + headers: controlHeaders(), + }); + expect(response.status).toBe(200); + const header = response.headers.get(SESSION_CHOICE_HEADER) ?? ""; + expect(header.length).toBeLessThan(1024); + const choice = JSON.parse(header) as { + id: string; + others: { id: string }[]; + more: number; + }; + expect(choice.id).toBe(sessions.at(-1)?.id); + expect(choice.others).toHaveLength(5); + expect(choice.more).toBe(294); + }); + test("creates isolated sessions through its authenticated control API", async () => { const controlPlane = createLocalControlPlane({ controlToken: CONTROL_TOKEN, diff --git a/packages/cli/test/commands/local/management.test.ts b/packages/cli/test/commands/local/management.test.ts index 2327fd57ed..ca39532c97 100644 --- a/packages/cli/test/commands/local/management.test.ts +++ b/packages/cli/test/commands/local/management.test.ts @@ -162,6 +162,80 @@ describe("local session view", () => { } }); + test("refuses to close a name that several open sessions share and lists their state and age", async () => { + const older = plane.sessionStore.create({ label: "shared", cwd: "/one" }); + const newer = plane.sessionStore.create({ label: "shared", cwd: "/two" }); + + const error = await commandError(sessionRoute, "close", "shared"); + + expect(error).toBeInstanceOf(ResolutionError); + const { message } = error as ResolutionError; + expect(message).toMatch( + /^Local session name "shared" matches more than one session\./, + ); + expect(message).toContain( + `Use session ID ${newer.id} (open, started 0m ago)`, + ); + expect(message).toContain( + `Use session ID ${older.id} (open, started 0m ago)`, + ); + expect(classifySilenced(error)).toBe("user_input_error"); + expect(plane.sessionStore.resolve(newer.id).state).toBe("open"); + expect(plane.sessionStore.resolve(older.id).state).toBe("open"); + }); + + test("notes the chosen session once, even when the lookup fails", async () => { + const older = plane.sessionStore.create({ label: "noted", cwd: "/one" }); + const newer = plane.sessionStore.create({ label: "noted", cwd: "/two" }); + await ingestEvent(newer.id, `${"c".repeat(8)}1${"0".repeat(23)}`, "one"); + await ingestEvent(newer.id, `${"c".repeat(8)}2${"0".repeat(23)}`, "two"); + const warn = vi.spyOn(logger, "warn").mockImplementation(() => {}); + try { + const ambiguous = await commandError( + eventRoute, + "view", + "noted", + "cccccccc", + ); + expect(ambiguous).toBeInstanceOf(ResolutionError); + expect(warn).toHaveBeenCalledTimes(1); + expect(warn.mock.calls[0]?.[0]).toContain( + `using the newest, ${newer.id}. Pass a session ID to use another: ${older.id}`, + ); + + const missing = await commandError( + eventRoute, + "view", + "noted", + "d".repeat(32), + ); + expect(missing).toBeInstanceOf(ResolutionError); + expect(warn).toHaveBeenCalledTimes(1); + } finally { + warn.mockRestore(); + } + }); + + test("counts the open sessions it does not name", async () => { + const sessions = Array.from({ length: 8 }, () => + plane.sessionStore.create({ label: "crowd", cwd: "/crowd" }), + ); + const warn = vi.spyOn(logger, "warn").mockImplementation(() => {}); + try { + await runCommand(sessionRoute, "view", true, "crowd"); + expect(warn).toHaveBeenCalledTimes(1); + const note = String(warn.mock.calls[0]?.[0]); + expect(note).toMatch( + new RegExp( + `^8 open sessions share that name; using the newest, ${sessions.at(-1)?.id}\\.`, + ), + ); + expect(note).toMatch(/\(open, started 0m ago\) and 2 more\.$/); + } finally { + warn.mockRestore(); + } + }); + test("reports an older daemon's shared-name 409 as a user error that lists the IDs", async () => { daemonResponse = Response.json( { diff --git a/packages/cli/test/e2e/local.test.ts b/packages/cli/test/e2e/local.test.ts index 097e7c1633..c7bf5c9757 100644 --- a/packages/cli/test/e2e/local.test.ts +++ b/packages/cli/test/e2e/local.test.ts @@ -482,12 +482,16 @@ describe("Local daemon E2E", () => { expect(JSON.parse(result.stdout)).toMatchObject({ id: second.id }); } - const closed = await cli("session", "close", "duplicate"); + const refused = await cli("session", "close", "duplicate"); + expect(refused.exitCode).toBe(23); + expect(refused.stderr).toContain( + 'Local session name "duplicate" matches more than one session.', + ); + expect(refused.stderr).toContain( + `Use session ID ${first.id} (open, started`, + ); + const closed = await cli("session", "close", second.id); expect(closed.exitCode, closed.stderr).toBe(0); - expect(JSON.parse(closed.stdout)).toMatchObject({ - id: second.id, - state: "retained", - }); const remaining = await cli("session", "view", "duplicate"); expect(remaining.exitCode, remaining.stderr).toBe(0); expect(remaining.stderr).not.toContain("share that name"); From ab0d2e661964120877993bb35a7a552005a4ee72 Mon Sep 17 00:00:00 2001 From: "sentry-junior[bot]" <264270552+sentry-junior[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 18:46:47 +0000 Subject: [PATCH 4/4] fix(cli): Keep sibling sessions out of capability-scoped 409s Viewer UI actions authenticate with the session's stream capability, not the control token, so the ambiguous-name 409 now lists the matching sessions only for control clients, as the read-side choice header does. --- docs/cli/local-control-plane.md | 6 +++--- .../cli/src/commands/local/control-plane.ts | 19 +++++++++++-------- .../test/commands/local/control-plane.test.ts | 12 ++++++++++++ 3 files changed, 26 insertions(+), 11 deletions(-) diff --git a/docs/cli/local-control-plane.md b/docs/cli/local-control-plane.md index 8d2041fd69..4effa6a072 100644 --- a/docs/cli/local-control-plane.md +++ b/docs/cli/local-control-plane.md @@ -55,9 +55,9 @@ open session, or to its newest session when none is open. When several open sess share the name, read responses carry an `X-Sentry-Local-Session-Choice` header, JSON with the chosen `id`, up to five `others` (each `id` and `createdAt`), and a `more` count of the rest, and the CLI prints a one-line note to stderr. Close, reset, and -retention changes refuse such a name with HTTP 409 `ambiguous_session`, listing every -match in `sessions` with its `id`, `state`, and `createdAt`; the CLI reports that as a -user error. Daemons from older CLIs answered every shared-name lookup with that 409. +retention changes refuse such a name with HTTP 409 `ambiguous_session`. For control +clients it lists every match in `sessions` with its `id`, `state`, and `createdAt`; +capability-scoped requests get the code only. The CLI reports it as a user error. Daemons from older CLIs answered every shared-name lookup with that 409. Session lookup commands accept names quoted or as separate words. For `event view` and `envelope view`, the final argument is the telemetry ID; preceding arguments form the session name. Event lookup uses the Sentry event ID from the envelope diff --git a/packages/cli/src/commands/local/control-plane.ts b/packages/cli/src/commands/local/control-plane.ts index 0b8cbc37ee..bc9ac9bf29 100644 --- a/packages/cli/src/commands/local/control-plane.ts +++ b/packages/cli/src/commands/local/control-plane.ts @@ -242,6 +242,8 @@ export function createLocalControlPlane({ } const { session, others } = choice; if (others.length === 0) return session.id; + // Capability-scoped stream, ingest, and UI requests never see sibling IDs. + const control = hasControlCapability(c.req.raw, controlToken); if (access === "write") { const sessions = [session, ...others]; throw new HTTPException(409, { @@ -250,19 +252,20 @@ export function createLocalControlPlane({ error: `Local session name "${reference}" is ambiguous; use its session ID.`, code: AMBIGUOUS_SESSION_CODE, reference, - sessionIds: sessions.map(({ id }) => id), - sessions: sessions.map(({ id, state, createdAt }) => ({ - id, - state, - createdAt, - })), + ...(control && { + sessionIds: sessions.map(({ id }) => id), + sessions: sessions.map(({ id, state, createdAt }) => ({ + id, + state, + createdAt, + })), + }), }, { status: 409 }, ), }); } - // Capability-scoped stream and ingest requests never see sibling IDs. - if (hasControlCapability(c.req.raw, controlToken)) + if (control) c.header( SESSION_CHOICE_HEADER, JSON.stringify({ diff --git a/packages/cli/test/commands/local/control-plane.test.ts b/packages/cli/test/commands/local/control-plane.test.ts index 4bf4a1ebf4..51fe8f825c 100644 --- a/packages/cli/test/commands/local/control-plane.test.ts +++ b/packages/cli/test/commands/local/control-plane.test.ts @@ -532,6 +532,18 @@ describe("Local control plane", () => { ], }); } + // A stream capability alone must not reveal the other sessions. + const viewer = await plane.app.request( + `/_local/v1/sessions/p/ui/close?cap=${stream}`, + { method: "POST", headers: { "Content-Type": "application/json" } }, + ); + expect(viewer.status).toBe(409); + const viewerBody: Record = await viewer.json(); + expect(viewerBody).toMatchObject({ code: "ambiguous_session" }); + expect(viewerBody).not.toHaveProperty("sessionIds"); + expect(viewerBody).not.toHaveProperty("sessions"); + expect(JSON.stringify(viewerBody)).not.toContain(older.id); + expect(plane.sessionStore.resolve(newer.id)).toMatchObject({ state: "open", maxEnvelopes: newer.maxEnvelopes,