diff --git a/apps/cli-docs/src/fragments/commands/local.md b/apps/cli-docs/src/fragments/commands/local.md index e575e0440..81457b9be 100644 --- a/apps/cli-docs/src/fragments/commands/local.md +++ b/apps/cli-docs/src/fragments/commands/local.md @@ -281,8 +281,14 @@ 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. 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 208f82c1d..3a76f8054 100644 --- a/design/sentry-local.md +++ b/design/sentry-local.md @@ -41,6 +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 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 59496d3eb..78cb5d3c3 100644 --- a/docs/cli/local-control-plane.md +++ b/docs/cli/local-control-plane.md @@ -50,8 +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. -Names must be unique for name-based queries; ambiguous names return HTTP 409 with guidance -to use the session ID. +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`. 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/plugins/sentry-cli/skills/sentry-cli/references/local.md b/packages/cli/plugins/sentry-cli/skills/sentry-cli/references/local.md index 8079869e9..ee6a6d20e 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 28f8d3fab..8d96427d2 100644 --- a/packages/cli/src/commands/local/control-plane.ts +++ b/packages/cli/src/commands/local/control-plane.ts @@ -39,8 +39,10 @@ import { logger } from "../../lib/logger.js"; import { AMBIGUOUS_SESSION_CODE, createLocalSessionStore, - AmbiguousLocalSessionError, + type LocalSessionChoice, type LocalSessionStore, + SESSION_CHOICE_HEADER, + SESSION_CHOICE_LIMIT, } from "./session-store.js"; import { @@ -219,28 +221,65 @@ 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) { - 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; + return undefined; + } + 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, { + res: Response.json( + { + error: `Local session name "${reference}" is ambiguous; use its session ID.`, + code: AMBIGUOUS_SESSION_CODE, + reference, + ...(control && { + sessionIds: sessions.map(({ id }) => id), + sessions: sessions.map(({ id, state, createdAt }) => ({ + id, + state, + createdAt, + })), + }), + }, + { status: 409 }, + ), + }); } + if (control) + 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) => { @@ -424,10 +463,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({ @@ -487,23 +527,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"); @@ -532,24 +572,24 @@ export function createLocalControlPlane({ return result; }); if (outcome === 410) return closed(); - if (typeof outcome === "object") sessionStore.recordActivity(reference); + if (typeof outcome === "object") sessionStore.recordActivity(id); return ingestResponse(c, outcome); }; 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(); @@ -592,7 +632,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 () => { @@ -607,7 +647,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); @@ -626,7 +666,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 @@ -634,67 +674,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(); @@ -718,11 +763,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(); @@ -736,12 +782,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(); @@ -776,11 +823,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 95a60afc9..7a5b55518 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,11 @@ 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 { + AMBIGUOUS_SESSION_CODE, + type LocalSession, + SESSION_CHOICE_HEADER, +} from "./session-store.js"; type DaemonFlags = { readonly foreground: boolean; @@ -91,7 +96,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", }, @@ -115,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(); @@ -146,9 +152,108 @@ async function controlJson( return (await response.json()) as ControlResult; } +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( + (other: unknown) => + typeof other === "object" && + other !== null && + "id" in other && + typeof other.id === "string" && + "createdAt" in other && + Number.isFinite(other.createdAt), + ) + ); +} + +/** Sessions already named in a note, so one command says it once. */ +const notedSessionChoices = new Set(); + /** - * Turn the control plane'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). + * 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 || + notedSessionChoices.has(choice.id) + ) { + return; + } + notedSessionChoices.add(choice.id); + const more = choice.more ?? 0; + const others = choice.others + .map(({ id, createdAt }) => `${id} (${describeSession("open", createdAt)})`) + .join(", "); + logger.warn( + `${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` : ""}.`, + ); +} + +/** 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 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 ( @@ -161,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. @@ -199,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 93bf43905..8d79b133b 100644 --- a/packages/cli/src/commands/local/session-store.ts +++ b/packages/cli/src/commands/local/session-store.ts @@ -52,21 +52,25 @@ export type CreateLocalSessionInput = { /** `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[]; +/** + * 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"; - 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; - } -} +/** 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. + */ +export type LocalSessionChoice = { + readonly session: LocalSession; + readonly others: LocalSession[]; +}; /** In-memory session lifecycle and access to isolated telemetry buffers. */ export type LocalSessionStore = { @@ -87,6 +91,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 +133,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; - } - const matches = [...sessions.values()].filter( - (session) => session.label === reference, - ); - if (matches.length === 0) { - throw new Error(`Local session "${reference}" was not found.`); + return { session: byId, others: [] }; } - 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 || (left.id < right.id ? 1 : -1), ); - } - 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 +286,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 7b3f5f1e7..9b7c1dbf1 100644 --- a/packages/cli/test/commands/local/control-plane.test.ts +++ b/packages/cli/test/commands/local/control-plane.test.ts @@ -5,6 +5,7 @@ import { createLocalControlPlane } from "../../../src/commands/local/control-pla 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"; @@ -481,38 +482,42 @@ 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"], - ["POST", "/reset"], + ["GET", "/retention"], ] 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", { @@ -520,6 +525,104 @@ describe("Local control plane", () => { }) ).status, ).toBe(404); + + plane.sessionStore.close(newer.id); + 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("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 }, + ], + }); + } + // 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, + }); + 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 () => { diff --git a/packages/cli/test/commands/local/management.test.ts b/packages/cli/test/commands/local/management.test.ts index fe7d0eb8d..eb46b1e38 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,119 @@ 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("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( + { + error: OLD_DAEMON_MESSAGE, + code: "ambiguous_session", + reference: "spike", + sessionIds: ["one", "two"], + }, + { status: 409 }, + ); const error = await viewError("spike"); @@ -144,8 +255,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 98b1f3774..d029f9078 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 5e88ec9c6..3df744454 100644 --- a/packages/cli/test/e2e/local.test.ts +++ b/packages/cli/test/e2e/local.test.ts @@ -463,24 +463,42 @@ 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`); + if (parts[0] === "session") + expect(JSON.parse(result.stdout)).toMatchObject({ id: second.id }); } - expect((await cli("session", "view", first.id)).exitCode).toBe(0); + + 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); + 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 () => {