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): preserve sessions through navigation handoff (#7584)
Wolf Mermelstein11af88745b7e
diff --git a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx b/apps/web/src/features/agents-view/components/AgentSessionPane.tsxindex 699c910e34..9b18130995 100644--- a/apps/web/src/features/agents-view/components/AgentSessionPane.tsx+++ b/apps/web/src/features/agents-view/components/AgentSessionPane.tsx@@ -11,10 +11,6 @@ import { ArchivedSessionFooter } from '@app/features/block-agent/component/Archiimport { AgentSidePanelSections } from '@app/features/block-agent/component/sidepanel/AgentSidePanelSections';import { Transcript } from '@app/features/block-agent/component/Transcript';import { useAgentSession } from '@app/features/block-agent/context/AgentSessionContext';-import {- forgetPendingSession,- pendingSession,-} from '@app/features/block-agent/context/pending-session';import { createAgentRouteTarget } from '@app/features/block-agent/primitives/create-agent-route-target';import { AgentChangesProvider } from '@app/features/changes/agent-session-changes';import {@@ -47,7 +43,7 @@ import ShareIcon from '@icon/share.svg';import type { NotificationSource } from '@notifications/notification-source';import ArrowSquareOut from '@phosphor/arrow-square-out.svg';import { EmptyStatePanel } from '@ui';-import { onCleanup, Show } from 'solid-js';+import { Show } from 'solid-js';import { changeSessionArchiveState } from '../../block-agent/queries/change-session-archive-state';import { ChatSessionInput } from './ChatComposer';import { SessionModelSelector } from './ModelSelector';@@ -309,13 +305,6 @@ export function AgentSessionPane(props: {onSessionId: (sessionId: string) => void;onDeleted: () => void;}) {- const pending = pendingSession(props.id);- onCleanup(() => {- if (pending?.sessionId() || pending?.failed()) {- forgetPendingSession(props.id);- }- });-return (<AgentSessionProvider blockId={props.id} onSessionId={props.onSessionId}><AgentChangesProvider>diff --git a/apps/web/src/features/block-agent/agent-session-provider.tsx b/apps/web/src/features/block-agent/agent-session-provider.tsxindex 744b793c37..557203bbb7 100644--- a/apps/web/src/features/block-agent/agent-session-provider.tsx+++ b/apps/web/src/features/block-agent/agent-session-provider.tsx@@ -40,8 +40,15 @@ export function AgentSessionProvider(onSessionId?: (sessionId: string) => void;}) {- const { sessionId, pending, failed, error, pendingPrompt, initialInput } =- resolveSessionId(() => props.blockId);+ const {+ sessionId,+ pending,+ failed,+ error,+ pendingPrompt,+ initialInput,+ acquired,+ } = resolveSessionId(() => props.blockId);createEffect(() => {const id = sessionId();@@ -49,7 +56,7 @@ export function AgentSessionProvider(});const userId = useUserId();- const live = createAgentSession(sessionId, { userId });+ const live = createAgentSession(sessionId, { userId, onAcquire: acquired });// A block opened by sending a first prompt shows that prompt, and the// working line under it, from its very first paint. Nothing else can: the// session does not exist until `POST /agent-sessions` answers, and thediff --git a/apps/web/src/features/block-agent/component/Block.tsx b/apps/web/src/features/block-agent/component/Block.tsxindex 811300ef4e..606e0c0eef 100644--- a/apps/web/src/features/block-agent/component/Block.tsx+++ b/apps/web/src/features/block-agent/component/Block.tsx@@ -30,7 +30,6 @@ import {} from 'solid-js';import { AgentSessionProvider } from '../agent-session-provider';import { useAgentSession } from '../context/AgentSessionContext';-import { forgetPendingSession } from '../context/pending-session';import { parseAgentMessageTarget } from '../core/search-location';import { createAgentRouteTarget } from '../primitives/create-agent-route-target';import { AgentComposer } from './AgentComposer';@@ -211,7 +210,6 @@ export default function BlockAgent() {// nowhere.const adoptSessionId = (sessionId: string) => {split?.handle.adoptContentId({ type: 'agent', nextId: sessionId });- forgetPendingSession(blockId);};return (diff --git a/apps/web/src/features/block-agent/context/create-agent-session.ts b/apps/web/src/features/block-agent/context/create-agent-session.tsindex 634d7a18ed..0b3d94d751 100644--- a/apps/web/src/features/block-agent/context/create-agent-session.ts+++ b/apps/web/src/features/block-agent/context/create-agent-session.ts@@ -112,6 +112,8 @@ export function createAgentSession(options: {/** The viewer, so a speculated prompt is attributed as the log will. */userId: Accessor<string | undefined>;+ /** This view now owns a reference; a pending navigation may release its own. */+ onAcquire?: () => void;}): AgentSessionHandle {// Whether this block went on screen before it had a session to load.@@ -205,6 +207,7 @@ export function createAgentSession(unsubscribe();session.release();});+ options.onAcquire?.();return session;});diff --git a/apps/web/src/features/block-agent/context/pending-session.test.tsx b/apps/web/src/features/block-agent/context/pending-session.test.tsxnew file mode 100644index 0000000000..8c810790e6--- /dev/null+++ b/apps/web/src/features/block-agent/context/pending-session.test.tsx@@ -0,0 +1,307 @@+/** @vitest-environment jsdom */++import type { FoldInput } from '@core/agent-fold/client';+import type { FoldedStreamEvent } from '@service-agent-fold/generated/types';+import type {+ AgentSessionLogEntryDto,+ ControlRequest,+} from '@service-agent-harness/generated/schemas';+import { err, ok } from 'neverthrow';+import { Suspense } from 'solid-js';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const fold = vi.hoisted(() => ({+ pushSession: vi.fn(),+ readSession: vi.fn(),+ closeSession: vi.fn(),+}));+const harness = vi.hoisted(() => ({+ create: vi.fn(),+ get: vi.fn(),+ control: vi.fn(),+}));++vi.mock('@core/agent-fold/client', () => fold);+vi.mock('@service-agent-harness/client', () => ({+ agentHarnessServiceClient: harness,+}));+vi.mock('@queries/soup/normalized-cache', () => ({+ refetchSoupEntity: vi.fn(async () => {}),+}));+vi.mock('@queries/agent-session/queue-sync', () => ({+ subscribeSocketSessionStarted: () => () => {},+}));+vi.mock('@queries/agent-session/log', () => ({+ AgentSessionLogUnavailable: class extends Error {},+ watchAgentSessionLog: () => ({+ cached: Promise.resolve(undefined),+ fetched: Promise.resolve({ bot: { id: 'bot' }, rows: [] }),+ stop: () => {},+ }),+ canFollowAgentSessionLog: () => false,+ forgetAgentSessionLog: vi.fn(async () => {}),+}));+vi.mock('@queries/agent-session/session-metadata-sync', () => ({+ subscribeAgentSessionRenamed: () => () => {},+ subscribeAgentSessionUpdated: () => () => {},+}));+vi.mock('@service-storage/graphql-soup', () => ({+ subscribeGraphqlSoupReconnected: () => () => {},+}));++const { cleanup, render } = await import('@solidjs/testing-library');+const { AgentSession } = await import('@core/agent-session/AgentSession');+const { PromptTrace } = await import('@core/agent-session/prompt-telemetry');+const { createAgentSession } = await import('./create-agent-session');+const { forgetPendingSession, pendingSession, startPendingSession } =+ await import('./pending-session');+const { resolveSessionId } = await import('./resolve-session-id');++const issue = vi.spyOn(AgentSession.prototype, 'issue');+const stage = vi.spyOn(PromptTrace.prototype, 'stage');++/** Use the same resolver/acquisition boundary as both destination providers. */+function Destination(props: { id: string }) {+ const resolved = resolveSessionId(() => props.id);+ const live = createAgentSession(resolved.sessionId, {+ userId: () => 'me',+ onAcquire: resolved.acquired,+ });+ return <p>{resolved.error() ?? live.session()?.name}</p>;+}++const mount = (id: string) =>+ render(() => (+ <Suspense>+ <Destination id={id} />+ </Suspense>+ ));++function deferred<T>() {+ let resolve!: (value: T) => void;+ const promise = new Promise<T>((r) => {+ resolve = r;+ });+ return { promise, resolve };+}++const created = (id: string) => ok({ session: { id, ownerId: 'me' } });+const accepted = (request: ControlRequest) =>+ ok({ actionId: request.actionId, status: 'sent' });+const settle = () => vi.advanceTimersByTimeAsync(0);+const promptTrace = () => issue.mock.calls[0]?.[1]?.trace;+const snapshots = () =>+ fold.pushSession.mock.calls+ .flatMap((call) => call[1] as FoldInput[])+ .filter((input) => input.kind === 'snapshot');++beforeEach(() => {+ vi.useFakeTimers();+ vi.clearAllMocks();+ fold.pushSession.mockResolvedValue([]);+ fold.readSession.mockResolvedValue({+ messages: [],+ metadata: { turn: 'idle' },+ });+ harness.create.mockImplementation(async ({ id }: { id: string }) =>+ created(id)+ );+ harness.get.mockImplementation(async (id: string) =>+ ok({ id, name: 'New session' })+ );+ harness.control.mockImplementation(async (_id, request: ControlRequest) =>+ accepted(request)+ );+});++afterEach(() => {+ cleanup();+ for (const [request] of harness.create.mock.calls) {+ forgetPendingSession(request.id);+ }+ vi.clearAllTimers();+ vi.useRealTimers();+});++describe('pending navigation ownership', () => {+ it('keeps one fold and the prompt trace when the POST finishes before mount', async () => {+ const id = startPendingSession({ prompt: 'Hello' });+ await settle();+ const beforeMount = AgentSession.get(id);+ const trace = promptTrace();+ expect(beforeMount).toBeDefined();+ expect(trace).toBeInstanceOf(PromptTrace);+ expect(trace?.ended).toBe(false);+ expect(fold.closeSession).not.toHaveBeenCalled();++ const destination = mount(id);+ await settle();+ expect(AgentSession.get(id)).toBe(beforeMount);+ expect(pendingSession(id)).toBeUndefined();+ expect(harness.get).toHaveBeenCalledOnce();+ expect(snapshots()).toHaveLength(1);+ expect(fold.closeSession).not.toHaveBeenCalled();++ const request = harness.control.mock.calls[0][1] as ControlRequest;+ fold.pushSession.mockResolvedValueOnce([+ {+ kind: 'update',+ message: {+ agentSessionId: id,+ turn: 1,+ author: { kind: 'user', userId: 'me' },+ requestId: request.actionId ?? null,+ parts: [{ kind: 'text', text: 'Hello' }],+ stop: null,+ pending: false,+ },+ },+ {+ kind: 'new',+ message: {+ agentSessionId: id,+ turn: 1,+ author: { kind: 'agent' },+ requestId: null,+ parts: [{ kind: 'text', text: 'Ready' }],+ stop: null,+ pending: false,+ },+ },+ ] satisfies FoldedStreamEvent[]);+ AgentSession.ingest({+ agentSessionId: id,+ entries: [+ {+ id: 'confirmed-row',+ createdAt: new Date().toISOString(),+ direction: 'to_server',+ content: { type: 'acp', jsonrpc: '2.0' },+ } satisfies AgentSessionLogEntryDto,+ ],+ });+ await settle();+ const firstText = stage.mock.calls.findIndex(+ ([name]) => name === 'first_text'+ );+ expect(firstText).toBeGreaterThanOrEqual(0);+ expect(stage.mock.contexts[firstText]).toBe(trace);+ expect(fold.closeSession).not.toHaveBeenCalled();++ destination.unmount();+ expect(AgentSession.get(id)).toBeUndefined();+ expect(fold.closeSession).toHaveBeenCalledExactlyOnceWith(id);+ });++ it('hands off before the POST answers and releases each owner once', async () => {+ const creation = deferred<ReturnType<typeof created>>();+ const delivery = deferred<ReturnType<typeof accepted>>();+ harness.create.mockReturnValue(creation.promise);+ harness.control.mockReturnValue(delivery.promise);+ const id = startPendingSession({ prompt: 'Hello' });+ const destination = mount(id);+ creation.resolve(created(id));+ await settle();+ const beforeAccepted = AgentSession.get(id);+ expect(beforeAccepted).toBeDefined();+ expect(pendingSession(id)).toBeUndefined();++ delivery.resolve(accepted(harness.control.mock.calls[0][1]));+ await settle();+ expect(AgentSession.get(id)).toBe(beforeAccepted);+ expect(promptTrace()?.ended).toBe(false);+ expect(harness.get).toHaveBeenCalledOnce();+ expect(snapshots()).toHaveLength(1);+ expect(fold.closeSession).not.toHaveBeenCalled();++ destination.unmount();+ expect(AgentSession.get(id)).toBeUndefined();+ expect(fold.closeSession).toHaveBeenCalledExactlyOnceWith(id);+ });++ it('retains the POST owner when the destination unmounts during delivery', async () => {+ const delivery = deferred<ReturnType<typeof accepted>>();+ harness.control.mockReturnValue(delivery.promise);+ const id = startPendingSession({ prompt: 'Hello' });+ await settle();+ const destination = mount(id);+ await settle();+ destination.unmount();+ expect(AgentSession.get(id)).toBeDefined();+ expect(fold.closeSession).not.toHaveBeenCalled();++ delivery.resolve(accepted(harness.control.mock.calls[0][1]));+ await settle();+ expect(AgentSession.get(id)).toBeUndefined();+ expect(fold.closeSession).toHaveBeenCalledExactlyOnceWith(id);+ });++ it('expires a ready session whose navigation never mounts', async () => {+ const id = startPendingSession({ prompt: 'Hello' });+ await settle();+ expect(AgentSession.get(id)).toBeDefined();+ await vi.advanceTimersByTimeAsync(5 * 60_000);+ expect(pendingSession(id)).toBeUndefined();+ expect(AgentSession.get(id)).toBeUndefined();+ expect(fold.closeSession).toHaveBeenCalledExactlyOnceWith(id);+ expect(promptTrace()?.ended).toBe(true);+ });++ it('bounds an abandoned create and does not retain a late result', async () => {+ const creation = deferred<ReturnType<typeof created>>();+ harness.create.mockReturnValue(creation.promise);+ const id = startPendingSession({ prompt: 'Hello' });+ await vi.advanceTimersByTimeAsync(5 * 60_000);+ expect(pendingSession(id)).toBeUndefined();+ creation.resolve(created(id));+ await settle();+ expect(harness.control).toHaveBeenCalledOnce();+ expect(AgentSession.get(id)).toBeUndefined();+ expect(fold.closeSession).toHaveBeenCalledExactlyOnceWith(id);+ });++ it('still delivers a slow create to its mounted destination after registry expiry', async () => {+ const creation = deferred<ReturnType<typeof created>>();+ harness.create.mockReturnValue(creation.promise);+ const id = startPendingSession({ prompt: 'Hello' });+ const destination = mount(id);+ await vi.advanceTimersByTimeAsync(5 * 60_000);+ expect(pendingSession(id)).toBeUndefined();+ creation.resolve(created(id));+ await settle();+ expect(AgentSession.get(id)).toBeDefined();+ expect(harness.control).toHaveBeenCalledOnce();+ expect(fold.closeSession).not.toHaveBeenCalled();+ destination.unmount();+ expect(fold.closeSession).toHaveBeenCalledExactlyOnceWith(id);+ });++ it('releases a failed prompt immediately while preserving its startup error', async () => {+ harness.control.mockResolvedValue(+ err([{ code: 'HTTP_ERROR', message: 'Runtime is disconnected.' }])+ );+ const id = startPendingSession({ prompt: 'Hello' });+ await settle();+ expect(pendingSession(id)?.error()).toBe('Runtime is disconnected.');+ expect(AgentSession.get(id)).toBeUndefined();+ expect(fold.closeSession).toHaveBeenCalledExactlyOnceWith(id);+ expect(promptTrace()?.ended).toBe(true);+ await vi.advanceTimersByTimeAsync(5 * 60_000);+ expect(pendingSession(id)).toBeUndefined();+ expect(fold.closeSession).toHaveBeenCalledOnce();+ });++ it('forgets a failed create when its error view unmounts', async () => {+ harness.create.mockResolvedValue(+ err([{ code: 'HTTP_ERROR', message: 'Could not create session.' }])+ );+ const id = startPendingSession({ prompt: 'Hello' });+ await settle();+ const destination = mount(id);+ expect(pendingSession(id)?.error()).toBe('Could not create session.');+ destination.unmount();+ expect(pendingSession(id)).toBeUndefined();+ expect(harness.get).not.toHaveBeenCalled();+ expect(fold.closeSession).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/features/block-agent/context/pending-session.ts b/apps/web/src/features/block-agent/context/pending-session.tsindex d6c36e603f..e82e4ab698 100644--- a/apps/web/src/features/block-agent/context/pending-session.ts+++ b/apps/web/src/features/block-agent/context/pending-session.ts@@ -14,6 +14,8 @@* before the block is on screen is normal, not a race. It is what tells a* block "not created yet" apart from "a session to load": an id in here is* waiting on its create; any other id is loaded as it is.+ * It also holds the live session across navigation until the destination+ * owns a reference, even when creation and the prompt POST finish first.** Everything downstream of the block reads its session id as* `Accessor<string | undefined>`, so "not created yet" is the same absence@@ -54,7 +56,14 @@ export type PendingSession = {initialInput?: string;};-const pending = new Map<string, PendingSession>();+type PendingSessionEntry = PendingSession & { dispose: () => void };++const pending = new Map<string, PendingSessionEntry>();++// A destination normally adopts the session immediately. Bound abandoned+// navigation and failed creates without making a timer part of the handoff.+// Cold sandbox provisioning can take minutes, like the prompt trace's stall bound.+const PENDING_SESSION_TTL_MS = 5 * 60_000;/*** Options captured by the preflight composer before a session exists.@@ -108,16 +117,32 @@ export function startPendingSession(: undefined;const [sessionId, setSessionId] = createSignal<string>();const [error, setError] = createSignal<string>();+ let navigation: AgentSession | undefined;+ let disposed = false;+ const releaseNavigation = () => {+ navigation?.release();+ navigation = undefined;+ };const fail = (message: string, cause?: unknown) => {trace?.end('failed', cause ?? new Error(message));+ releaseNavigation();setError(message);};+ const expiry = setTimeout(+ () => forgetPendingSession(id),+ PENDING_SESSION_TTL_MS+ );pending.set(id, {sessionId,failed: () => error() !== undefined,error,prompt: options.prompt?.trim() || undefined,initialInput: options.initialInput,+ dispose: () => {+ disposed = true;+ clearTimeout(expiry);+ releaseNavigation();+ },});const traced = <T>(operation: () => T): T =>@@ -178,6 +203,10 @@ export function startPendingSession();trace?.stage('configured');}+ // The prompt's reference ends when its POST answers. Navigation+ // owns a separate reference until the destination acquires, so a+ // fast POST cannot destroy the fold before that view mounts.+ if (!disposed) navigation = AgentSession.acquire(created);setSessionId(created);if (prompt || options.attachments?.length) {const delivered = await issueSessionAction(@@ -195,6 +224,7 @@ export function startPendingSession(});if (delivered.isErr()) {+ releaseNavigation();setError(delivered.error.map((error) => error.message).join(' ') ||'The first message could not be sent.'@@ -236,9 +266,11 @@ export function pendingSession(id: string): PendingSession | undefined {}/**- * Drop a settled create. Called once the block has seen it land or fail, so- * the map does not grow for the life of the tab.+ * Release the navigation reference once the destination owns its acquisition,+ * or when a failed/abandoned create no longer needs a placeholder.*/export function forgetPendingSession(id: string): void {+ const entry = pending.get(id);pending.delete(id);+ entry?.dispose();}diff --git a/apps/web/src/features/block-agent/context/resolve-session-id.test.ts b/apps/web/src/features/block-agent/context/resolve-session-id.test.tsindex 3da640b50e..fabfb1533c 100644--- a/apps/web/src/features/block-agent/context/resolve-session-id.test.ts+++ b/apps/web/src/features/block-agent/context/resolve-session-id.test.ts@@ -7,7 +7,7 @@import type { AgentAction } from '@service-agent-harness/generated/schemas';import { createRoot } from 'solid-js';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const takeWarm = vi.hoisted(() => vi.fn<() => string | undefined>());const replenishWarm = vi.hoisted(() => vi.fn<(userId: string) => void>());@@ -120,7 +120,9 @@ vi.mock('@core/agent-session/AgentSession', () => ({},}));-const { startPendingSession } = await import('./pending-session');+const { forgetPendingSession, startPendingSession } = await import(+ './pending-session'+);const { PromptTrace } = await import('@core/agent-session/prompt-telemetry');const { agentHarnessServiceClient } = await import('@service-agent-harness/client'@@ -141,6 +143,13 @@ beforeEach(() => {create.confirmedModel = undefined;});+afterEach(() => {+ for (const [request] of vi.mocked(agentHarnessServiceClient.create).mock+ .calls) {+ if (request.id) forgetPendingSession(request.id);+ }+});+describe('a block id that is already a session', () => {it('resolves to itself, never pending', () => {createRoot((dispose) => {diff --git a/apps/web/src/features/block-agent/context/resolve-session-id.ts b/apps/web/src/features/block-agent/context/resolve-session-id.tsindex 340faa0c56..f52bf75155 100644--- a/apps/web/src/features/block-agent/context/resolve-session-id.ts+++ b/apps/web/src/features/block-agent/context/resolve-session-id.ts@@ -8,8 +8,8 @@* plus the facts the block chrome needs to explain the wait.*/-import { type Accessor, createMemo } from 'solid-js';-import { pendingSession } from './pending-session';+import { type Accessor, createMemo, onCleanup } from 'solid-js';+import { forgetPendingSession, pendingSession } from './pending-session';export type ResolvedSessionId = {/** The session id; absent while its create is still in flight. */@@ -23,13 +23,22 @@ export type ResolvedSessionId = {* the create is still on the wire. */pendingPrompt: Accessor<string | undefined>;initialInput: Accessor<string | undefined>;+ /** Called only after the destination owns its AgentSession reference. */+ acquired: () => void;};export function resolveSessionId(blockId: Accessor<string>): ResolvedSessionId {// The create in flight for this id, or undefined for an id that is simply// a session to load. Read once per id: a create that settles is forgotten// by the surface that opened it, and by then `sessionId` is the id itself.- const entry = createMemo(() => pendingSession(blockId()));+ const entry = createMemo(() => {+ const id = blockId();+ const session = pendingSession(id);+ onCleanup(() => {+ if (session?.sessionId() || session?.failed()) forgetPendingSession(id);+ });+ return session;+ });const sessionId = () => {const session = entry();@@ -47,5 +56,6 @@ export function resolveSessionId(blockId: Accessor<string>): ResolvedSessionId {error: () => entry()?.error(),pendingPrompt: () => entry()?.prompt,initialInput: () => entry()?.initialInput,+ acquired: () => forgetPendingSession(blockId()),};}diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.mdindex f9b395e721..4682eab7c7 100644--- a/docs/AGENT_GUIDE/ai-chat.md+++ b/docs/AGENT_GUIDE/ai-chat.md@@ -15,6 +15,12 @@ first prose. Verify a second prompt and a reload preserve the complete answer.Selected model and effort must be confirmed before the first prompt; settingsalready confirmed by the runtime do not need another control request.+Repeat from Home, Agents, and the create menu with an already-ready session.+The first prompt can be accepted before its destination mounts; navigating into+the session must keep the same streamed turn without restarting its load. Also+leave a pending destination, then reopen the session and confirm the sent prompt+and complete answer remain available.+## Working with projectsProject tools can list, read, create, update, delete, and share projects, and