Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(agents): stop a session creation race from reading as no access (#7791)
Eric Hayeseebb1fb8c4b9
diff --git a/.sqlx/query-dd820f788c2b5bac399ee256110e3b596af68da7f9d30e4606ba1161e04f8a9d.json b/.sqlx/query-dd820f788c2b5bac399ee256110e3b596af68da7f9d30e4606ba1161e04f8a9d.jsonnew file mode 100644index 0000000000..35bbf0827d--- /dev/null+++ b/.sqlx/query-dd820f788c2b5bac399ee256110e3b596af68da7f9d30e4606ba1161e04f8a9d.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT EXISTS(SELECT 1 FROM agent_session WHERE id = $1) AS \"exists!\"",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "exists!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "dd820f788c2b5bac399ee256110e3b596af68da7f9d30e4606ba1161e04f8a9d"+}diff --git a/apps/web/src/features/block-agent/agent-session-provider.tsx b/apps/web/src/features/block-agent/agent-session-provider.tsxindex 700f2828f4..5da0e88efb 100644--- a/apps/web/src/features/block-agent/agent-session-provider.tsx+++ b/apps/web/src/features/block-agent/agent-session-provider.tsx@@ -177,7 +177,10 @@ export function AgentSessionProvider(// is the same dead end for the reader as a load that failed.loadFailed: () => live.loadFailed() || failed(),accessDenied: live.accessDenied,- // Retrying a 401 gets the same 401.+ // Retrying a refusal in earnest gets the same refusal. A refusal of+ // a session this tab just created is not one of those, and never+ // reaches here as denied access: `AgentSession` waits it out, and+ // reports a load that can be tried again if it never clears.loadRetryable: () => live.loadFailed() && !live.accessDenied(),retryLoad: live.retry,turn,diff --git a/apps/web/src/features/block-agent/context/pending-session.ts b/apps/web/src/features/block-agent/context/pending-session.tsindex 8e061a56aa..f2ce7b1641 100644--- a/apps/web/src/features/block-agent/context/pending-session.ts+++ b/apps/web/src/features/block-agent/context/pending-session.ts@@ -28,6 +28,7 @@ import {type PromptSubmitSurface,PromptTrace,} from '@core/agent-session/prompt-telemetry';+import { markSessionCreated } from '@core/agent-session/recently-created';import {replenishWarmAgentSession,takeWarmAgentSession,@@ -198,6 +199,11 @@ export function startPendingSession(trace?.stage('created');// Normally the id this tab minted; an older service may mint its own.const created = result.value.session.id;+ // Before anything acquires it: `AgentSession`'s constructor reads the+ // session row at once, and that read can arrive before the create's+ // writes are readable. Marked first, a refusal to that read is waited+ // out rather than reported as a session that is not ours.+ markSessionCreated(created);// A warm claim releases its server reservation before creation answers.replenishWarmAgentSession(result.value.session.ownerId);void refetchSoupEntity(created, 'agentSession', { created: true });diff --git a/apps/web/src/lib/core/agent-session/AgentSession.test.ts b/apps/web/src/lib/core/agent-session/AgentSession.test.tsindex 3eb99b8f76..cc81dcc0f8 100644--- a/apps/web/src/lib/core/agent-session/AgentSession.test.ts+++ b/apps/web/src/lib/core/agent-session/AgentSession.test.ts@@ -154,6 +154,7 @@ import {AgentSessionAccessDenied,AgentSessionReleased,} from './AgentSession';+import { forgetSessionCreated, markSessionCreated } from './recently-created';import { resetSessionTurns, sessionTurn } from './session-turn';const SESSION = '01a0abed-279f-724c-9f49-60dbedc79b6e';@@ -818,6 +819,78 @@ describe('AgentSession', () => {live.release();});+ describe('a session this tab just created', () => {+ beforeEach(() => {+ markSessionCreated(SESSION);+ onTestFinished(() => forgetSessionCreated(SESSION));+ });++ it('waits out a refusal and loads once the create is readable', async () => {+ vi.useFakeTimers();+ onTestFinished(() => void vi.useRealTimers());+ // The create has answered, but what it wrote is not readable yet.+ harness.get+ .mockResolvedValueOnce(err([{ code: 'UNAUTHORIZED' }]))+ .mockResolvedValue(ok(session));++ const live = AgentSession.acquire(SESSION);+ const loaded = live.load();+ await vi.advanceTimersByTimeAsync(1_000);++ expect(await loaded).toEqual({ session, bot });+ // Nothing was thrown away on the strength of a refusal that was a race.+ expect(logSource.forget).not.toHaveBeenCalled();+ live.release();+ });++ it('waits out a 404 from a create whose row is not visible yet', async () => {+ vi.useFakeTimers();+ onTestFinished(() => void vi.useRealTimers());+ harness.get+ .mockResolvedValueOnce(err([{ code: 'NOT_FOUND' }]))+ .mockResolvedValue(ok(session));++ const live = AgentSession.acquire(SESSION);+ const loaded = live.load();+ await vi.advanceTimersByTimeAsync(1_000);++ expect(await loaded).toEqual({ session, bot });+ live.release();+ });++ it('gives up as a retryable failure, not denied access, if it never clears', async () => {+ vi.useFakeTimers();+ onTestFinished(() => void vi.useRealTimers());+ harness.get.mockResolvedValue(err([{ code: 'UNAUTHORIZED' }]));++ const live = AgentSession.acquire(SESSION);+ const settled = live.load().catch((error: unknown) => error);+ // Past every retry, but still inside the window in which this tab's+ // creates are given the benefit of the doubt.+ await vi.advanceTimersByTimeAsync(20_000);++ const error = await settled;+ expect(error).toBeInstanceOf(Error);+ expect(error).not.toBeInstanceOf(AgentSessionAccessDenied);+ live.release();+ });++ it('reports a refusal honestly once a load has proved the grant is there', async () => {+ const first = AgentSession.acquire(SESSION);+ expect(await first.load()).toEqual({ session, bot });+ first.release();++ // Access taken away after a load that worked is a refusal in earnest,+ // not a create still settling, even inside the grace window.+ harness.get.mockResolvedValue(err([{ code: 'UNAUTHORIZED' }]));+ const second = AgentSession.acquire(SESSION);+ await expect(second.load()).rejects.toBeInstanceOf(+ AgentSessionAccessDenied+ );+ second.release();+ });+ });+describe('cached log', () => {it('folds the cached log first and the fetched one over it', async () => {logSource.cached.mockResolvedValue(logOf([row(1), row(2)]));diff --git a/apps/web/src/lib/core/agent-session/AgentSession.ts b/apps/web/src/lib/core/agent-session/AgentSession.tsindex 66dc4328bf..7d1bcda8be 100644--- a/apps/web/src/lib/core/agent-session/AgentSession.ts+++ b/apps/web/src/lib/core/agent-session/AgentSession.ts@@ -57,6 +57,7 @@ import {transcriptSize,} from './load-telemetry';import { frameDelivery, PromptTrace } from './prompt-telemetry';+import { createdRecently, forgetSessionCreated } from './recently-created';import { publishSessionTurn } from './session-turn';export type AgentSessionListener = (events: FoldedStreamEvent[]) => void;@@ -98,6 +99,22 @@ export class AgentSessionAccessDenied extends Error {}}+/**+ * The harness refused a session this tab had just created.+ *+ * Its own type because it is not the refusal it looks like: a create is+ * answered before everything it wrote is readable, and the first read of a+ * brand-new session can arrive inside that gap. Retrying is the right+ * response, which is exactly what {@link AgentSessionAccessDenied} says it+ * is not - so the two cannot share a type.+ */+export class AgentSessionNotReady extends Error {+ constructor(readonly sessionId: string) {+ super(`agent session is not readable yet: ${sessionId}`);+ this.name = 'AgentSessionNotReady';+ }+}+/** The log query answered that the viewer cannot see this session. */const inaccessible = (error: unknown) =>error instanceof AgentSessionLogUnavailable &&@@ -117,6 +134,14 @@ const accessDenied = (errors: { code: string }[]) =>(error) => error.code === 'UNAUTHORIZED' || error.code === 'FORBIDDEN');+/**+ * No session behind this id. The harness answers it apart from a refusal, so+ * a read that has overtaken its own create can be told from one that is not+ * this viewer's at all.+ */+const missing = (errors: { code: string }[]) =>+ errors.some((error) => error.code === 'NOT_FOUND');+/*** Whether this action takes the turn, rather than riding alongside one. ACP* runs a prompt at a time, so these are the ones the harness queues; mirrors@@ -128,6 +153,17 @@ function occupiesTurn(action: AgentAction): boolean {const RESYNC_RETRY_DELAYS_MS = [1_000, 3_000, 10_000];+/**+ * Waits before re-reading a session this tab created and was refused.+ *+ * Front-loaded: the gap being waited out is usually milliseconds, so the+ * first retry lands inside a frame or two and nobody sees anything. The tail+ * is there for a create whose writes take unusually long to become readable;+ * past the last one, a refusal is reported as a failed load - with a Retry -+ * rather than retried forever against a session that may really be gone.+ */+const CREATE_SETTLE_RETRY_DELAYS_MS = [150, 400, 1_000, 2_500, 5_000];+export class AgentSession {private static readonly open = new Map<string, AgentSession>();@@ -295,14 +331,23 @@ export class AgentSession {if (this.loadFailed) {this.loadFailed = false;this.trace = new SessionLoadTrace(this.id);- this.watch.stop();- this.watch = this.openWatch();- this.sessionRow = agentHarnessServiceClient.get(this.id);+ this.reissueReads();this.loading = this.startLoad();}return this.loading;}+ /**+ * Start the row and log reads again, for an attempt that is being made+ * afresh. The old watch is stopped first: its rows belong to a load that+ * is no longer the one in flight.+ */+ private reissueReads(): void {+ this.watch.stop();+ this.watch = this.openWatch();+ this.sessionRow = agentHarnessServiceClient.get(this.id);+ }+/*** Do something to the agent. The action is folded before the harness* answers, so its effect is visible at once: a prompt as a pending bubble,@@ -570,7 +615,7 @@ export class AgentSession {}private startLoad(): Promise<AgentSessionRecord> {- return this.fetchAndFold().then(+ return this.fetchFoldAndSettle().then((record) => {this.trace.end('loaded');return record;@@ -586,6 +631,55 @@ export class AgentSession {);}+ /**+ * The load, waiting out a create that has not finished becoming readable.+ *+ * Only {@link AgentSessionNotReady} is retried, and only for a session this+ * tab created: every other failure is reported on the first attempt, as+ * before. Each attempt re-reads from scratch, because the refused answers+ * are already settled promises.+ */+ private async fetchFoldAndSettle(): Promise<AgentSessionRecord> {+ for (let attempt = 0; ; attempt += 1) {+ try {+ const record = await this.fetchAndFold();+ // Readable: a refusal after this is a real one.+ forgetSessionCreated(this.id);+ return record;+ } catch (error: unknown) {+ const delay = CREATE_SETTLE_RETRY_DELAYS_MS[attempt];+ if (+ delay === undefined ||+ this.closed ||+ !(error instanceof AgentSessionNotReady)+ ) {+ throw error;+ }+ await new Promise((resolve) => setTimeout(resolve, delay));+ if (this.closed) throw new AgentSessionReleased(this.id);+ this.trace.retriedBeforeReady(attempt + 1);+ this.reissueReads();+ }+ }+ }++ /**+ * How a refusal should be reported.+ *+ * A session this tab created seconds ago is far likelier to be mid-create+ * than not ours, and is retried. Anything else is a refusal in earnest, and+ * its cached transcript must not be shown to this viewer again.+ */+ private refused(): Error {+ if (createdRecently(this.id)) {+ this.trace.failing('not_ready');+ return new AgentSessionNotReady(this.id);+ }+ this.forgetCached();+ this.trace.failing('access_denied');+ return new AgentSessionAccessDenied(this.id);+ }+private async fetchAndFold(): Promise<AgentSessionRecord> {const fetchStartedAt = performance.now();const [session, log] = await Promise.all([@@ -602,20 +696,20 @@ export class AgentSession {// not one.if (this.closed) throw new AgentSessionReleased(this.id);if (session.isErr()) {- if (accessDenied(session.error)) {- this.forgetCached();- this.trace.failing('access_denied');- throw new AgentSessionAccessDenied(this.id);+ if (accessDenied(session.error)) throw this.refused();+ // The harness knows of no such session. For one this tab just created+ // that is the create still landing, and worth another read; otherwise+ // it is gone, and the surface should offer a retry rather than claim+ // the viewer was refused.+ if (missing(session.error) && createdRecently(this.id)) {+ this.trace.failing('not_ready');+ throw new AgentSessionNotReady(this.id);}this.trace.failing('session_fetch');throw new Error(`agent session could not be fetched: ${this.id}`);}if (!log.ok) {- if (inaccessible(log.error)) {- this.forgetCached();- this.trace.failing('access_denied');- throw new AgentSessionAccessDenied(this.id);- }+ if (inaccessible(log.error)) throw this.refused();this.trace.failing(logFailure(log.error));throw new Error(`agent session log could not be fetched: ${this.id}`, {cause: log.error,diff --git a/apps/web/src/lib/core/agent-session/load-telemetry.ts b/apps/web/src/lib/core/agent-session/load-telemetry.tsindex 300db8666b..830ed159cd 100644--- a/apps/web/src/lib/core/agent-session/load-telemetry.ts+++ b/apps/web/src/lib/core/agent-session/load-telemetry.ts@@ -38,6 +38,13 @@ export type LoadOutcome =export type LoadFailure =/** The viewer cannot see the session. */| 'access_denied'+ /**+ * The session was refused, but this tab had just created it: a create that+ * had not finished becoming readable, waited out and still refused. Its own+ * value so a race that outlasts the retries does not land among the real+ * refusals.+ */+ | 'not_ready'/** The session row could not be fetched. */| 'session_fetch'/** The log query failed in transport. */@@ -218,6 +225,16 @@ export class SessionLoadTrace {this.stage('fold', foldStartedAt);}+ /**+ * The read was refused and tried again, because this tab had created the+ * session moments earlier and the refusal reads as a create that has not+ * landed. Recorded so the race stays countable once the retry has stopped+ * anyone noticing it.+ */+ retriedBeforeReady(attempts: number): void {+ this.#set('agent.session.load.not_ready_retries', attempts);+ }+/*** A surface handed a transcript to the DOM. `cached` is the warm paint* from the cached log; the other is the fetched one. Measured from thediff --git a/apps/web/src/lib/core/agent-session/recently-created.test.ts b/apps/web/src/lib/core/agent-session/recently-created.test.tsnew file mode 100644index 0000000000..a66c7ac51d--- /dev/null+++ b/apps/web/src/lib/core/agent-session/recently-created.test.ts@@ -0,0 +1,59 @@+/**+ * The window in which this tab's own create explains a refusal.+ */++import { afterEach, describe, expect, it, vi } from 'vitest';++import {+ createdRecently,+ forgetSessionCreated,+ markSessionCreated,+} from './recently-created';++const SESSION = '01a0abed-279f-724c-9f49-60dbedc79b6e';+const OTHER = '01a0abed-279f-724c-9f49-60dbedc79b6f';++afterEach(() => {+ vi.useRealTimers();+ forgetSessionCreated(SESSION);+ forgetSessionCreated(OTHER);+});++describe('recently created sessions', () => {+ it('knows a session this tab created from one it only opened', () => {+ markSessionCreated(SESSION);++ expect(createdRecently(SESSION)).toBe(true);+ expect(createdRecently(OTHER)).toBe(false);+ });++ it('stops vouching for a create once the window has passed', () => {+ vi.useFakeTimers();+ markSessionCreated(SESSION);+ expect(createdRecently(SESSION)).toBe(true);++ vi.advanceTimersByTime(30_000);++ expect(createdRecently(SESSION)).toBe(false);+ });++ it('forgets a session on request, so a later refusal is taken at its word', () => {+ markSessionCreated(SESSION);++ forgetSessionCreated(SESSION);++ expect(createdRecently(SESSION)).toBe(false);+ });++ it('does not grow without bound as sessions are created', () => {+ vi.useFakeTimers();+ markSessionCreated(OTHER);++ vi.advanceTimersByTime(30_000);+ // Any later create prunes what the window has left behind.+ markSessionCreated(SESSION);++ expect(createdRecently(OTHER)).toBe(false);+ expect(createdRecently(SESSION)).toBe(true);+ });+});diff --git a/apps/web/src/lib/core/agent-session/recently-created.ts b/apps/web/src/lib/core/agent-session/recently-created.tsnew file mode 100644index 0000000000..9e3a1fbc4b--- /dev/null+++ b/apps/web/src/lib/core/agent-session/recently-created.ts@@ -0,0 +1,69 @@+/**+ * Sessions this tab created a moment ago.+ *+ * A session's id exists here before it exists on the server: the id is minted+ * on the client and the block opens against it (`pending-session.ts`), so the+ * first read can reach the harness within milliseconds of - sometimes ahead+ * of - the create that makes it real. A read the harness holds no grant for+ * is refused, and a refusal looks the same whether the grant is missing or+ * merely not there yet.+ *+ * An id in here says a refusal has an innocent reading available: this tab+ * created this session seconds ago, so "not yours" is far more likely to be+ * "not yet" than a session that was never ours. {@link AgentSession} retries+ * those instead of reporting a dead end.+ *+ * A wall-clock window rather than a handle passed down from the create on+ * purpose: the read that loses the race is often not the one the create+ * started. A reload, a second surface, or a navigation opens its own read+ * with no reference to the creating code path at all, and that read has to be+ * covered too.+ */++/**+ * How long after its create a session's refusal is read as "not yet".+ *+ * Long enough to cover a create still settling, short enough that a session+ * genuinely shared away from this viewer is reported honestly rather than+ * retried for a visibly long time.+ */+const GRACE_MS = 30_000;++const createdAt = new Map<string, number>();++/** Drop everything past the window, so the map tracks open tabs, not history. */+function prune(now: number): void {+ for (const [id, at] of createdAt) {+ if (now - at >= GRACE_MS) createdAt.delete(id);+ }+}++/** This tab's create for `id` has answered: it is ours, even if not readable yet. */+export function markSessionCreated(id: string): void {+ const now = Date.now();+ prune(now);+ createdAt.set(id, now);+}++/**+ * Whether this tab created `id` recently enough that a refusal should be+ * read as a create that has not landed.+ */+export function createdRecently(id: string): boolean {+ const at = createdAt.get(id);+ if (at === undefined) return false;+ if (Date.now() - at < GRACE_MS) return true;+ createdAt.delete(id);+ return false;+}++/**+ * Stop treating `id` as newly created.+ *+ * Called once a load has succeeded: the grant is demonstrably visible, so a+ * later refusal is a real one - access taken away rather than not yet given -+ * and must be reported rather than retried.+ */+export function forgetSessionCreated(id: string): void {+ createdAt.delete(id);+}diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.tsindex bd0ed36f81..87ece67629 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/client.ts@@ -812,6 +812,10 @@ export const warmAgentSessionHandler = async (};/**+ * A caller holding no grant is answered 401; an id with no session behind it+at all is answered 404. They used to be the same answer, which left a+client that read a session before its create had landed unable to tell a+race it should retry from a refusal it should not.* @summary Get an agent session by id.*/export type getAgentSessionResponse200 = {@@ -829,6 +833,11 @@ export type getAgentSessionResponse403 = {status: 403;};+export type getAgentSessionResponse404 = {+ data: string;+ status: 404;+};+export type getAgentSessionResponse500 = {data: string;status: 500;@@ -840,6 +849,7 @@ export type getAgentSessionResponseSuccess = getAgentSessionResponse200 & {export type getAgentSessionResponseError = (| getAgentSessionResponse401| getAgentSessionResponse403+ | getAgentSessionResponse404| getAgentSessionResponse500) & {headers: Headers;diff --git a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json b/apps/web/src/lib/service-clients/service-agent-harness/openapi.jsonindex 44f6ce700b..735b9993b3 100644--- a/apps/web/src/lib/service-clients/service-agent-harness/openapi.json+++ b/apps/web/src/lib/service-clients/service-agent-harness/openapi.json@@ -588,6 +588,7 @@"get": {"tags": ["agent-sessions"],"summary": "Get an agent session by id.",+ "description": "A caller holding no grant is answered 401; an id with no session behind it\nat all is answered 404. They used to be the same answer, which left a\nclient that read a session before its create had landed unable to tell a\nrace it should retry from a refusal it should not.","operationId": "get_agent_session","parameters": [{@@ -613,7 +614,7 @@}},"401": {- "description": "",+ "description": "the session exists but is not this caller's","content": {"text/plain": {"schema": {@@ -632,6 +633,16 @@}}},+ "404": {+ "description": "no session with this id: not created yet, or deleted since",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },"500": {"description": "","content": {diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rsindex 2b6a69eb5e..3eff1d158a 100644--- a/crates/agent_session/src/inbound/axum_router.rs+++ b/crates/agent_session/src/inbound/axum_router.rs@@ -691,12 +691,22 @@ impl AgentSessionResponse {params(("session_id" = Uuid, Path, description = "ID of the agent session")),responses((status = 200, body = AgentSessionResponse),- (status = 401, body = String),+ (status = 401, body = String, description = "the session exists but is not this caller's"),(status = 403, body = String),+ (+ status = 404,+ body = String,+ description = "no session with this id: not created yet, or deleted since"+ ),(status = 500, body = String),))]/// Get an agent session by id.+///+/// A caller holding no grant is answered 401; an id with no session behind it+/// at all is answered 404. They used to be the same answer, which left a+/// client that read a session before its create had landed unable to tell a+/// race it should retry from a refusal it should not.#[tracing::instrument(skip_all, fields(session_id = %session_id), err(Debug))]pub async fn get_agent_session_handler<T: AgentSessionService,diff --git a/crates/agent_session/src/inbound/axum_router/test.rs b/crates/agent_session/src/inbound/axum_router/test.rsindex 261b8fa646..8ffd7c0630 100644--- a/crates/agent_session/src/inbound/axum_router/test.rs+++ b/crates/agent_session/src/inbound/axum_router/test.rs@@ -73,6 +73,21 @@ fn openapi_documents_session_admission_failures() {assert!(schema["components"]["schemas"]["AiAdmissionErrorBody"].is_object());}+/// A read answers "not yours" and "not there" differently, and says so in the+/// contract: a client that cannot tell them apart has no way to know a+/// refusal of a session it has only just created is worth trying again.+#[test]+fn openapi_separates_a_missing_session_from_a_refused_one() {+ #[derive(utoipa::OpenApi)]+ #[openapi(paths(get_agent_session_handler))]+ struct ApiDoc;++ let schema = serde_json::to_value(<ApiDoc as utoipa::OpenApi>::openapi()).unwrap();+ let responses = &schema["paths"]["/agent-sessions/{session_id}"]["get"]["responses"];+ assert!(responses["401"].is_object());+ assert!(responses["404"].is_object());+}+const BOT_TOKEN: &str = "mbot_self_test";const HARNESS_TOKEN: &str = "mhns_self_test";const OWNER: &str = "macro|[email protected]";diff --git a/crates/entity_access/src/domain/ports.rs b/crates/entity_access/src/domain/ports.rsindex 95965f9180..186852040a 100644--- a/crates/entity_access/src/domain/ports.rs+++ b/crates/entity_access/src/domain/ports.rs@@ -104,6 +104,18 @@ pub trait AccessRepository: Clone + Send + Sync + 'static {agent_session_id: &str,) -> impl Future<Output = Result<Option<AgentSessionParent>, AccessError>> + Send;+ /// Whether a session row exists at all, for anyone.+ ///+ /// Asked only once a viewer has turned out to hold no grant, to tell+ /// "there is no such session" apart from "this one is not yours". The two+ /// used to answer alike, which made a session read before its create had+ /// landed - and a session that had since been deleted - indistinguishable+ /// from a refusal.+ fn agent_session_exists(+ &self,+ agent_session_id: &str,+ ) -> impl Future<Output = Result<bool, AccessError>> + Send;+/// Highest grant on a CRM pipeline.fn get_pipeline_access(&self,diff --git a/crates/entity_access/src/domain/service.rs b/crates/entity_access/src/domain/service.rsindex 448b62e84e..d5c18642d6 100644--- a/crates/entity_access/src/domain/service.rs+++ b/crates/entity_access/src/domain/service.rs@@ -636,13 +636,40 @@ wherelet user_id = user_id.ok_or(AccessError::Unauthorized)?;self.get_team_permission(user_id, entity_id).await}+ // Sessions answer a refusal more precisely than the rest, and say+ // so in the log. A session is read the moment its id exists on a+ // client - which is before its create has landed - so "no grant"+ // here is as often a race as a refusal, and the two have to be+ // told apart by whoever is looking: the caller, from the status,+ // and us, from this event. Existence is only asked on the way to+ // refusing, so the extra round trip never touches a granted read.+ EntityType::AgentSession => {+ let access = self+ .get_optimized_access(entity_id, user_id, entity_type)+ .await?;+ let Some(access_level) = access else {+ let exists = self.repo.agent_session_exists(entity_id).await?;+ tracing::warn!(+ entity_id,+ entity_type = "agent_session",+ viewer = user_id.map_or("anonymous", AsRef::as_ref),+ session_exists = exists,+ "agent session access denied"+ );+ return Err(if exists {+ AccessError::Unauthorized+ } else {+ AccessError::NotFound("agent session")+ });+ };+ Ok(EntityPermission::AccessLevel { access_level })+ }EntityType::Document| EntityType::Chat| EntityType::Project| EntityType::EmailThread| EntityType::Call| EntityType::CalendarEvent- | EntityType::AgentSession| EntityType::Initiative| EntityType::CrmPipeline| EntityType::Databasediff --git a/crates/entity_access/src/domain/service/test.rs b/crates/entity_access/src/domain/service/test.rsindex 5cf5e32492..e0eed32a89 100644--- a/crates/entity_access/src/domain/service/test.rs+++ b/crates/entity_access/src/domain/service/test.rs@@ -35,6 +35,7 @@ struct MockRepo {scheduled_action_access: Arc<Mutex<Option<AccessLevel>>>,accessible_scheduled_action_ids: Arc<Mutex<Vec<Uuid>>>,agent_session_parent: Arc<Mutex<Option<AgentSessionParent>>>,+ agent_session_exists: Arc<Mutex<bool>>,pipeline_access: Arc<Mutex<Option<AccessLevel>>>,pipeline_access_list: Arc<Mutex<Vec<(Uuid, AccessLevel)>>>,database_access: Arc<Mutex<Option<AccessLevel>>>,@@ -90,6 +91,9 @@ impl MockRepo {scheduled_action_access: Arc::new(Mutex::new(None)),accessible_scheduled_action_ids: Arc::new(Mutex::new(Vec::new())),agent_session_parent: Arc::default(),+ // Existing by default: the interesting half of these tests is who+ // may see a session, not whether it is there.+ agent_session_exists: Arc::new(Mutex::new(true)),pipeline_access: Arc::default(),pipeline_access_list: Arc::default(),database_access: Arc::new(Mutex::new(None)),@@ -171,6 +175,12 @@ impl MockRepo {self}+ /// No session row under the asked-for id: never created, or deleted since.+ fn without_agent_session_row(mut self) -> Self {+ self.agent_session_exists = Arc::new(Mutex::new(false));+ self+ }+fn with_database_access(mut self, level: AccessLevel) -> Self {self.database_access = Arc::new(Mutex::new(Some(level)));self@@ -317,6 +327,10 @@ impl AccessRepository for MockRepo {Ok(self.agent_session_parent.lock().await.clone())}+ async fn agent_session_exists(&self, _: &str) -> Result<bool, AccessError> {+ Ok(*self.agent_session_exists.lock().await)+ }+async fn get_document_access(&self,_document_id: &str,@@ -1003,6 +1017,8 @@ async fn test_get_entity_permission_agent_session_returns_access_level() {));}+/// A session that is there, held by someone else: a refusal, and the caller+/// is told to stop asking.#[tokio::test]async fn test_get_entity_permission_agent_session_no_access_returns_unauthorized() {let service = EntityAccessServiceImpl::new(MockRepo::new());@@ -1020,6 +1036,54 @@ async fn test_get_entity_permission_agent_session_no_access_returns_unauthorizedassert!(matches!(result, Err(AccessError::Unauthorized)));}+/// No row under that id - never created, or deleted since. Answered apart+/// from a refusal so a client reading a session whose create has not landed+/// can tell "not yet" from "not yours" and try again.+#[tokio::test]+async fn test_get_entity_permission_agent_session_missing_row_returns_not_found() {+ let service = EntityAccessServiceImpl::new(MockRepo::new().without_agent_session_row());+ let user_id = test_user_id();++ let result = service+ .get_entity_permission(+ Some(&user_id),+ "0198a805-3e22-75b2-97eb-d9c6b91accb0",+ EntityType::AgentSession,+ None,+ )+ .await;++ assert!(matches!(result, Err(AccessError::NotFound(_))));+}++/// Existence is a cost only a refusal pays: a granted read must not spend a+/// round trip proving what the grant already implies.+#[tokio::test]+async fn test_get_entity_permission_agent_session_with_access_skips_existence_check() {+ let repo = MockRepo::new()+ .with_agent_session_access(AccessLevel::Owner)+ .without_agent_session_row();+ let service = EntityAccessServiceImpl::new(repo);+ let user_id = test_user_id();++ let result = service+ .get_entity_permission(+ Some(&user_id),+ "0198a805-3e22-75b2-97eb-d9c6b91accb0",+ EntityType::AgentSession,+ None,+ )+ .await+ .unwrap();++ assert!(matches!(+ result,+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Owner+ }+ ));+}+#[tokio::test]async fn test_get_entity_permission_database_returns_access_level() {let repo = MockRepo::new().with_database_access(AccessLevel::Owner);diff --git a/crates/entity_access/src/inbound/axum_extractors/agent_session.rs b/crates/entity_access/src/inbound/axum_extractors/agent_session.rsindex 75a0eb3c22..d085e061b6 100644--- a/crates/entity_access/src/inbound/axum_extractors/agent_session.rs+++ b/crates/entity_access/src/inbound/axum_extractors/agent_session.rs@@ -135,7 +135,17 @@ wherepermission};+ // The other refusal: a grant exists but does not reach what this route+ // asks for. Logged separately from the no-grant case in the service,+ // because the fix is different - this one is a sharing level, not a+ // missing or not-yet-committed row.if !permission.satisfies::<T>() {+ tracing::warn!(+ entity_id = %session_id,+ entity_type = "agent_session",+ viewer = macro_user_id.as_deref().map_or("anonymous", AsRef::as_ref),+ "agent session access denied: grant does not reach the required permission"+ );return Err(ExtractorError::Unauthorized);}diff --git a/crates/entity_access/src/outbound/pg_access_repo.rs b/crates/entity_access/src/outbound/pg_access_repo.rsindex 40b96d777c..4e3079f8ae 100644--- a/crates/entity_access/src/outbound/pg_access_repo.rs+++ b/crates/entity_access/src/outbound/pg_access_repo.rs@@ -265,6 +265,18 @@ impl AccessRepository for PgAccessRepository {.transpose()}+ async fn agent_session_exists(&self, agent_session_id: &str) -> Result<bool, AccessError> {+ let session = agent_session_id+ .parse::<Uuid>()+ .map_err(|_| AccessError::BadRequest("Invalid agent session ID format"))?;+ Ok(sqlx::query_scalar!(+ r#"SELECT EXISTS(SELECT 1 FROM agent_session WHERE id = $1) AS "exists!""#,+ session,+ )+ .fetch_one(&self.pool)+ .await?)+ }+async fn get_agent_session_access(&self,agent_session_id: &str,diff --git a/packages/sdk/generated/agent-harness/sdk.gen.ts b/packages/sdk/generated/agent-harness/sdk.gen.tsindex 4903221291..f1b310ba71 100644--- a/packages/sdk/generated/agent-harness/sdk.gen.ts+++ b/packages/sdk/generated/agent-harness/sdk.gen.ts@@ -221,6 +221,11 @@ export class Sdk extends HeyApiClient {/*** Get an agent session by id.+ *+ * A caller holding no grant is answered 401; an id with no session behind it+ * at all is answered 404. They used to be the same answer, which left a+ * client that read a session before its create had landed unable to tell a+ * race it should retry from a refusal it should not.*/public getAgentSession<ThrowOnError extends boolean = false>(options: Options<GetAgentSessionData, ThrowOnError>): RequestResult<GetAgentSessionResponses, GetAgentSessionErrors, ThrowOnError> {return (options.client ?? this.client).get<GetAgentSessionResponses, GetAgentSessionErrors, ThrowOnError>({ url: '/agent-sessions/{session_id}', ...options });diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.tsindex a857ecb49d..b2430ad756 100644--- a/packages/sdk/generated/agent-harness/types.gen.ts+++ b/packages/sdk/generated/agent-harness/types.gen.ts@@ -1847,8 +1847,15 @@ export type GetAgentSessionData = {};export type GetAgentSessionErrors = {+ /**+ * the session exists but is not this caller's+ */401: string;403: string;+ /**+ * no session with this id: not created yet, or deleted since+ */+ 404: string;500: string;};diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.jsonindex 44f6ce700b..735b9993b3 100644--- a/packages/sdk/specs/agent-harness.json+++ b/packages/sdk/specs/agent-harness.json@@ -588,6 +588,7 @@"get": {"tags": ["agent-sessions"],"summary": "Get an agent session by id.",+ "description": "A caller holding no grant is answered 401; an id with no session behind it\nat all is answered 404. They used to be the same answer, which left a\nclient that read a session before its create had landed unable to tell a\nrace it should retry from a refusal it should not.","operationId": "get_agent_session","parameters": [{@@ -613,7 +614,7 @@}},"401": {- "description": "",+ "description": "the session exists but is not this caller's","content": {"text/plain": {"schema": {@@ -632,6 +633,16 @@}}},+ "404": {+ "description": "no session with this id: not created yet, or deleted since",+ "content": {+ "text/plain": {+ "schema": {+ "type": "string"+ }+ }+ }+ },"500": {"description": "","content": {