Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(block-agent): poll Cursor external url through a bounded query (#6023)

Wolf Mermelsteinb776b4c0f082
diff --git a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
index 6fbfba60e8..c4285bb413 100644
--- a/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
+++ b/apps/web/src/features/block-agent/context/AgentSessionContext.tsx
@@ -9,6 +9,8 @@
* so each stateful concern stays a composable unit as wiring grows.
*/
+import { isCursorBotId } from '@core/constant/cursorAgent';
+import { useAgentSessionExternalUrlQuery } from '@queries/agent-session/session';
import type {
FoldedMessage,
SessionMetadata,
@@ -22,6 +24,7 @@ import {
createContext,
createEffect,
type ParentProps,
+ Suspense,
useContext,
} from 'solid-js';
import { controlOutcome } from '../state/control-message';
@@ -143,32 +146,75 @@ export function AgentSessionProvider(
const resuming = () => isDisconnected(status.status()) && awaitingRuntime();
return (
- <AgentSessionCtx.Provider
- value={{
- sessionId,
- pending,
- session: feed.session,
- bot: feed.bot,
- metadata: feed.metadata,
- messages: feed.messages,
- // A create that failed leaves the block with nothing to load, which
- // is the same dead end for the reader as a load that failed.
- loadFailed: () => feed.loadFailed() || failed(),
- loadRetryable: feed.loadFailed,
- retryLoad: feed.retry,
- working,
- status: status.status,
- resuming,
- composer,
- quoteSelection,
- registerQuoteInsert,
- }}
- >
- {props.children}
- </AgentSessionCtx.Provider>
+ <>
+ {/* Nested so a pending poll cannot take the block orchestrator's
+ <Suspense fallback={<LoadingBlock />}> and blank the transcript.
+ The poll component gates on `isSuccess` so it should not suspend;
+ this boundary is the backstop if a read of `query.data` ever does. */}
+ <Suspense fallback={null}>
+ <CursorExternalUrlPoll
+ sessionId={sessionId}
+ session={feed.session}
+ applySnapshot={feed.applySnapshot}
+ />
+ </Suspense>
+ <AgentSessionCtx.Provider
+ value={{
+ sessionId,
+ pending,
+ session: feed.session,
+ bot: feed.bot,
+ metadata: feed.metadata,
+ messages: feed.messages,
+ // A create that failed leaves the block with nothing to load, which
+ // is the same dead end for the reader as a load that failed.
+ loadFailed: () => feed.loadFailed() || failed(),
+ loadRetryable: feed.loadFailed,
+ retryLoad: feed.retry,
+ working,
+ status: status.status,
+ resuming,
+ composer,
+ quoteSelection,
+ registerQuoteInsert,
+ }}
+ >
+ {props.children}
+ </AgentSessionCtx.Provider>
+ </>
);
}
+/**
+ * Compensating read for a Cursor session whose provider url arrived after
+ * the feed's snapshot. Lives in its own Suspense so the rest of the block
+ * stays mounted while this query's first fetch is in flight.
+ */
+function CursorExternalUrlPoll(props: {
+ sessionId: Accessor<string | undefined>;
+ session: Accessor<AgentSessionResponse | undefined>;
+ applySnapshot: (session: AgentSessionResponse) => void;
+}) {
+ // Only a loaded Cursor session whose provider url is still missing polls;
+ // everything else passes `undefined`, which disables the query.
+ const query = useAgentSessionExternalUrlQuery(() => {
+ const id = props.sessionId();
+ const session = props.session();
+ if (!id || !session || session.external?.url) return undefined;
+ return isCursorBotId(session.botId) ? id : undefined;
+ });
+ createEffect(() => {
+ // `query.data` suspends while pending and throws once it errors
+ // (`useFavoritesData`). Gate on success so neither reaches the
+ // orchestrator Suspense / an error boundary.
+ if (!query.isSuccess) return;
+ const snapshot = query.data;
+ if (!snapshot?.external?.url) return;
+ props.applySnapshot(snapshot);
+ });
+ return null;
+}
+
export function useAgentSession(): AgentSessionState {
const ctx = useContext(AgentSessionCtx);
if (!ctx) {
diff --git a/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts b/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts
index d2634da64f..6877867708 100644
--- a/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts
+++ b/apps/web/src/features/block-agent/context/create-agent-session-feed.test.ts
@@ -6,7 +6,6 @@
* ordered store without a refetch.
*/
-import { CURSOR_BOT_ID } from '@core/constant/cursorAgent';
import type { FoldedMessage } from '@service-agent-fold/generated/types';
import type { AgentSessionResponse } from '@service-agent-harness/generated/schemas';
import { createRoot } from 'solid-js';
@@ -234,54 +233,6 @@ describe('createAgentSessionFeed live updates', () => {
expect(feed.session()?.name).toBe('New Name');
});
- /**
- * The link out to the provider is minted inside the first prompt, so the
- * snapshot the block loaded predates it. Nothing announces it, so a settled
- * turn is the cue to look again.
- */
- it('picks up the external agent link once the first turn settles', async () => {
- let calls = 0;
- worker.getSession = async () => {
- calls += 1;
- return {
- isErr: () => false,
- value: {
- id: 'session',
- name: 'Agent Session',
- modifiedAt: '2026-08-24T12:00:00Z',
- harness: 'claude-code',
- botId: CURSOR_BOT_ID,
- // The agent exists only from the second read onwards.
- external:
- calls > 1
- ? {
- provider: 'cursor',
- name: 'Add a health check',
- url: 'https://cursor.com/agents/bc-1',
- }
- : undefined,
- },
- };
- };
- const { createAgentSessionFeed } = await import(
- './create-agent-session-feed'
- );
-
- worker.messages = [
- message(0, 'user', 'add a health check'),
- message(0, 'agent', 'done', { kind: 'end_turn' }),
- ];
- const feed = createRoot(() => createAgentSessionFeed(() => 'session'));
- await flush();
- await flush();
- await flush();
-
- expect(feed.working()).toBe(false);
- expect(feed.session()?.external?.url).toBe(
- 'https://cursor.com/agents/bc-1'
- );
- });
-
it('does not re-read the snapshot for a session with no provider', async () => {
let calls = 0;
worker.getSession = async () => {
diff --git a/apps/web/src/features/block-agent/context/create-agent-session-feed.ts b/apps/web/src/features/block-agent/context/create-agent-session-feed.ts
index e226d113d5..046458fb1b 100644
--- a/apps/web/src/features/block-agent/context/create-agent-session-feed.ts
+++ b/apps/web/src/features/block-agent/context/create-agent-session-feed.ts
@@ -10,7 +10,6 @@
* and keeps rows reconciled so a streaming turn updates in place.
*/
-import { isCursorBotId } from '@core/constant/cursorAgent';
import type { AgentSessionRenamedEvent } from '@queries/agent-session/realtime-protocol';
import { acquireAgentSessionFold } from '@queries/agent-session/session-fold';
import { subscribeAgentSessionRenamed } from '@queries/agent-session/session-metadata-sync';
@@ -26,7 +25,6 @@ import type {
import {
type Accessor,
batch,
- createEffect,
createResource,
createSignal,
onCleanup,
@@ -48,6 +46,11 @@ export type AgentSessionFeed = {
retry: () => void;
/** The newest turn has no stop reason yet — the agent is working. */
working: Accessor<boolean>;
+ /**
+ * Adopt a newer snapshot of this session (the bounded external-url poll).
+ * No-op when the payload is for a different session or the feed has closed.
+ */
+ applySnapshot: (session: AgentSessionResponse) => void;
};
/** Prompt sorts before reply within a turn. */
@@ -195,30 +198,10 @@ export function createAgentSessionFeed(
return last.author.kind === 'user' || last.stop == null;
};
- // The external identity — the Cursor agent's id, name, and the link out to
- // it — is minted inside the session's *first prompt*, so the snapshot
- // fetched at load never carries it: `create` returns those columns NULL by
- // construction. Nothing announces it on the wire either, so re-read the
- // snapshot once a turn has settled, and keep the whole payload this time.
- //
- // Bounded by construction: the only session kind that gets one is Cursor's,
- // and the moment it lands this stops matching. A turn that settles without
- // minting one (a prompt that failed outright) is retried on the next.
- createEffect(() => {
- const id = sessionId();
- const session = resource.latest;
- if (!id || !session || session.external) return;
- if (!isCursorBotId(session.botId) || working() || messages().length === 0) {
- return;
- }
- const run = generation;
- void agentHarnessServiceClient.get(id).then((refreshed) => {
- // A superseded run has already replaced the value this would land on.
- if (refreshed.isErr() || closed || generation !== run) return;
- if (sessionId() !== id || !refreshed.value.external) return;
- mutate(refreshed.value);
- });
- });
+ const applySnapshot = (session: AgentSessionResponse) => {
+ if (closed || sessionId() !== session.id) return;
+ mutate(session);
+ };
return {
session: () => resource.latest,
@@ -228,5 +211,6 @@ export function createAgentSessionFeed(
loadFailed: () => resource.error !== undefined,
retry: () => void refetch(),
working,
+ applySnapshot,
};
}
diff --git a/apps/web/src/lib/queries/agent-session/session.ts b/apps/web/src/lib/queries/agent-session/session.ts
new file mode 100644
index 0000000000..0c30e0146e
--- /dev/null
+++ b/apps/web/src/lib/queries/agent-session/session.ts
@@ -0,0 +1,61 @@
+/**
+ * Bounded snapshot poll for a Cursor session whose `external.url` is still
+ * missing.
+ *
+ * Cursor mints that url inside the session's first prompt, and nothing
+ * announces it on the wire, so a block opened from the magic chip mid-run
+ * loads a snapshot without the "Open in Cursor" link. This query re-reads
+ * the same GET the feed already used, on a short budget (~30s) that covers
+ * a slow mint. A url-less row past the budget is a failed harness
+ * follow-up, which no amount of polling can repair.
+ */
+
+import { throwOnErr } from '@core/util/result';
+import { agentHarnessServiceClient } from '@service-agent-harness/client';
+import { useQuery } from '@tanstack/solid-query';
+import type { Accessor } from 'solid-js';
+
+/**
+ * How often, and how many times, to re-read a Cursor session's snapshot
+ * while its cursor.com url is still missing. Together they span ~30s, which
+ * comfortably covers Cursor's agent creation inside the first prompt.
+ */
+export const EXTERNAL_URL_POLL_INTERVAL_MS = 2_000;
+export const EXTERNAL_URL_POLL_ATTEMPTS = 15;
+
+/**
+ * Re-read an agent session snapshot while `sessionId` is set. Callers pass
+ * `undefined` when the session is not a Cursor bot, already has a url, or
+ * has not loaded yet — the query disables rather than fetching.
+ *
+ * `gcTime: 0` drops the observer when the call site unmounts so reopening
+ * the block gets a fresh budget. `retry: false` keeps one GET per attempt,
+ * matching that budget. The default 5-minute `staleTime` would not stop
+ * `refetchInterval`, but it would hide a remount fetch; zero keeps each
+ * observer honest.
+ */
+export function useAgentSessionExternalUrlQuery(
+ sessionId: Accessor<string | undefined>
+) {
+ return useQuery(() => {
+ const id = sessionId();
+ return {
+ queryKey: ['agentSession', 'externalUrl', id ?? ''] as const,
+ queryFn: async () =>
+ await throwOnErr(() => agentHarnessServiceClient.get(id!)),
+ enabled: Boolean(id),
+ // Stop once the url lands or the attempt budget is spent. Failed
+ // fetches count too, so a streak of errors cannot poll forever.
+ refetchInterval: (query) => {
+ if (query.state.data?.external?.url) return false;
+ const attempts =
+ query.state.dataUpdateCount + query.state.errorUpdateCount;
+ if (attempts >= EXTERNAL_URL_POLL_ATTEMPTS) return false;
+ return EXTERNAL_URL_POLL_INTERVAL_MS;
+ },
+ retry: false,
+ staleTime: 0,
+ gcTime: 0,
+ };
+ });
+}