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.

feat(agents): open a new session on its final id, prompt shown instantly (#6868)

Wolf Mermelstein9b40749e9078
diff --git a/apps/web/src/features/agents-view/views/AgentsView.tsx b/apps/web/src/features/agents-view/views/AgentsView.tsx
index d2d868cee8..5a5628ff55 100644
--- a/apps/web/src/features/agents-view/views/AgentsView.tsx
+++ b/apps/web/src/features/agents-view/views/AgentsView.tsx
@@ -239,6 +239,7 @@ function AgentsWorkspace(props: { initialRoute?: AgentsRoute }) {
const startConversation = (start: StartConversation) => {
const id = startPendingSession({
botId: start.botId,
+ userId: userId(),
prompt: start.prompt,
attachments: start.attachments,
modelOverride: start.modelOverride,
diff --git a/apps/web/src/features/block-agent/agent-session-provider.tsx b/apps/web/src/features/block-agent/agent-session-provider.tsx
index e9953ec85a..ed3cc84d1f 100644
--- a/apps/web/src/features/block-agent/agent-session-provider.tsx
+++ b/apps/web/src/features/block-agent/agent-session-provider.tsx
@@ -6,6 +6,10 @@ import { isCursorBotId } from '@core/constant/cursorAgent';
import { useUserId } from '@core/context/user';
import { idToDisplayName } from '@core/user/util';
import { useAgentSessionExternalUrlQuery } from '@queries/agent-session/session';
+import type {
+ FoldedMessage,
+ TurnState,
+} from '@service-agent-fold/generated/types';
import type { AgentSessionResponse } from '@service-agent-harness/generated/schemas';
import {
type Accessor,
@@ -32,7 +36,7 @@ export function AgentSessionProvider(
onSessionId?: (sessionId: string) => void;
}
) {
- const { sessionId, pending, failed, error } = resolveSessionId(
+ const { sessionId, pending, failed, error, pendingPrompt } = resolveSessionId(
() => props.blockId
);
@@ -43,7 +47,36 @@ export function AgentSessionProvider(
const userId = useUserId();
const live = createAgentSession(sessionId, { userId });
- const turn = () => live.metadata()?.turn ?? 'idle';
+ // 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 the
+ // shared session's own speculation starts only once it does. This stands
+ // in until the fold reports anything at all - the speculated bubble
+ // arrives under the same key and takes over without a gap.
+ const firstPrompt = () => {
+ const prompt = pendingPrompt();
+ if (!prompt || failed() || live.messages().length > 0) return undefined;
+ return prompt;
+ };
+ const messages = (): FoldedMessage[] => {
+ const prompt = firstPrompt();
+ if (prompt === undefined) return live.messages();
+ return [
+ {
+ agentSessionId: sessionId() ?? props.blockId,
+ turn: 0,
+ author: { kind: 'user', userId: userId() ?? null },
+ requestId: null,
+ parts: [{ kind: 'text', text: prompt }],
+ stop: null,
+ pending: true,
+ },
+ ];
+ };
+ const turn = (): TurnState =>
+ firstPrompt() !== undefined
+ ? 'starting'
+ : (live.metadata()?.turn ?? 'idle');
const served = createQueueController({
// Public viewers can read the transcript without signing in, while the
// live action queue requires an authenticated caller.
@@ -106,7 +139,7 @@ export function AgentSessionProvider(
session: live.session,
bot: live.bot,
metadata: live.metadata,
- messages: live.messages,
+ 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: () => live.loadFailed() || failed(),
diff --git a/apps/web/src/features/block-agent/context/pending-session.ts b/apps/web/src/features/block-agent/context/pending-session.ts
index 1dcaeea1d9..d1f26e369a 100644
--- a/apps/web/src/features/block-agent/context/pending-session.ts
+++ b/apps/web/src/features/block-agent/context/pending-session.ts
@@ -4,48 +4,47 @@
* `POST /agent-sessions` does not answer until its Daytona sandbox is booted,
* cloned and answering — minutes, not milliseconds. Waiting on that before
* opening anything means staring at a spinner for the whole provision, so the
- * block opens immediately against a placeholder id minted here, and adopts
- * the real one when the create lands.
+ * session's id is minted here and the block opens against it immediately;
+ * the create carries the same id, so the URL, the sidebar row and every
+ * reference are final from the first frame and nothing has to be adopted
+ * or rewritten when the server answers.
*
* The registry is module-level on purpose: the create is in flight before any
* block mounts, and must survive the mount either way round — resolving
- * before the block is on screen is normal, not a race.
+ * 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.
*
* Everything downstream of the block reads its session id as
* `Accessor<string | undefined>`, so "not created yet" is the same absence
* they already handle while the GET is in flight.
*/
-import { markMessageSent } from '@core/util/message-send-motion';
+import { AgentSession } from '@core/agent-session/AgentSession';
import { agentHarnessServiceClient } from '@service-agent-harness/client';
import type {
CreateAgentSessionRequest,
PromptAttachment,
} from '@service-agent-harness/generated/schemas';
import { type Accessor, createSignal } from 'solid-js';
-
-/**
- * Placeholder ids are prefixed so a session id can never be mistaken for one:
- * real ids are UUIDs.
- */
-const PLACEHOLDER_PREFIX = 'pending-';
+import { v7 as uuidv7 } from 'uuid';
export type PendingSession = {
- /** The real session id, once the create resolves. */
+ /** The session's id, once the create has made it real. */
sessionId: Accessor<string | undefined>;
/** The create failed — this block has nothing to become. */
failed: Accessor<boolean>;
/** The startup error returned by the service. */
error: Accessor<string | undefined>;
+ /**
+ * The first prompt, so the block can show it as sent from the moment it
+ * opens rather than once the create has answered.
+ */
+ prompt: string | undefined;
};
const pending = new Map<string, PendingSession>();
-/** Whether `id` is a placeholder this module minted rather than a session. */
-export function isPlaceholderSessionId(id: string): boolean {
- return id.startsWith(PLACEHOLDER_PREFIX);
-}
-
/**
* Options captured by the preflight composer before a session exists.
*/
@@ -56,6 +55,8 @@ export type StartPendingSessionOptions = {
prompt?: string;
/** Uploaded SFS files delivered with the first prompt. */
attachments?: PromptAttachment[];
+ /** The sender, so the first prompt is attributed as the log will. */
+ userId?: string;
/** Model to run on instead of the persona's, set as the session is created. */
modelOverride?: string;
/**
@@ -67,23 +68,28 @@ export type StartPendingSessionOptions = {
};
/**
- * Start creating a managed session and return the placeholder to open a block
+ * Start creating a managed session and return its id, to open a block
* against right now. The POST runs unattended; nothing awaits it.
+ *
+ * The id is minted here and sent with the create - a v7 UUID like the ones
+ * the harness mints for actions, so it sorts by time with the server's own.
*/
export function startPendingSession(
options: StartPendingSessionOptions = {}
): string {
- const placeholder = `${PLACEHOLDER_PREFIX}${crypto.randomUUID()}`;
+ const id = uuidv7();
const [sessionId, setSessionId] = createSignal<string>();
const [error, setError] = createSignal<string>();
- pending.set(placeholder, {
+ pending.set(id, {
sessionId,
failed: () => error() !== undefined,
error,
+ prompt: options.prompt?.trim() || undefined,
});
void agentHarnessServiceClient
.create({
+ id,
...(options.botId ? { botId: options.botId } : {}),
...(options.modelOverride ? { model: options.modelOverride } : {}),
...(options.repoUrl
@@ -98,26 +104,39 @@ export function startPendingSession(
);
return;
}
- const id = result.value.session.id;
+ // Normally the id this tab minted; a service that predates the field
+ // mints its own, and the block adopts that one the way it always did.
+ const created = result.value.session.id;
+ // The block adopts the session the moment it exists. The first prompt
+ // then goes through the shared session like any other, so it is folded
+ // speculatively - bubble and working line on screen at once - while
+ // the control POST waits out the runtime handshake. Delivering it
+ // first and adopting after left the transcript empty for that wait.
+ setSessionId(created);
const prompt = options.prompt?.trim() ?? '';
if (prompt || options.attachments?.length) {
- const delivered = await agentHarnessServiceClient.control(id, {
- type: 'prompt',
- prompt,
- ...(options.attachments?.length
- ? { attachments: options.attachments }
- : {}),
- });
- if (delivered.isErr()) {
- setError(
- delivered.error.map((error) => error.message).join(' ') ||
- 'The first message could not be sent.'
+ const session = AgentSession.acquire(created);
+ try {
+ const delivered = await session.issue(
+ {
+ type: 'prompt',
+ prompt,
+ ...(options.attachments?.length
+ ? { attachments: options.attachments }
+ : {}),
+ },
+ { userId: options.userId }
);
- return;
+ if (delivered.isErr()) {
+ setError(
+ delivered.error.map((error) => error.message).join(' ') ||
+ 'The first message could not be sent.'
+ );
+ }
+ } finally {
+ session.release();
}
- markMessageSent(`agent:${id}:${delivered.value.actionId}`);
}
- setSessionId(id);
})
.catch(() =>
setError(
@@ -125,24 +144,22 @@ export function startPendingSession(
)
);
- return placeholder;
+ return id;
}
/**
- * The pending session behind a placeholder, or undefined when there is none —
- * a placeholder URL reloaded in a new tab, whose create belonged to the tab
- * that is gone.
+ * The create in flight for `id`, or undefined when there is none: the id is
+ * a session to load as it is - including one whose create belonged to a tab
+ * that is gone, which then loads (or fails to) like any other.
*/
-export function pendingSession(
- placeholder: string
-): PendingSession | undefined {
- return pending.get(placeholder);
+export function pendingSession(id: string): PendingSession | undefined {
+ return pending.get(id);
}
/**
- * Drop a resolved placeholder. Called once the block has adopted the real id,
- * so the map does not grow for the life of the tab.
+ * 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.
*/
-export function forgetPendingSession(placeholder: string): void {
- pending.delete(placeholder);
+export function forgetPendingSession(id: string): void {
+ pending.delete(id);
}
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.ts
index 90405c892a..569fad3bd7 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
@@ -9,7 +9,7 @@ import { createRoot } from 'solid-js';
import { beforeEach, describe, expect, it, vi } from 'vitest';
const create = vi.hoisted(() => ({
- resolve: undefined as ((id: string) => void) | undefined,
+ resolve: undefined as ((id?: string) => void) | undefined,
reject: undefined as (() => void) | undefined,
control: vi.fn(),
}));
@@ -17,9 +17,9 @@ const create = vi.hoisted(() => ({
vi.mock('@service-agent-harness/client', () => ({
agentHarnessServiceClient: {
create: vi.fn(
- () =>
+ (request: { id: string }) =>
new Promise((resolve) => {
- create.resolve = (id: string) =>
+ create.resolve = (id: string = request.id) =>
resolve({ isErr: () => false, value: { session: { id } } });
create.reject = () =>
resolve({
@@ -37,6 +37,17 @@ vi.mock('@service-agent-harness/client', () => ({
},
}));
+// The first prompt goes through the shared session so it is folded
+// speculatively; here that is just the control POST under the session's id.
+vi.mock('@core/agent-session/AgentSession', () => ({
+ AgentSession: {
+ acquire: (id: string) => ({
+ issue: (action: unknown) => create.control(id, action),
+ release: () => {},
+ }),
+ },
+}));
+
const { startPendingSession } = await import('./pending-session');
const { agentHarnessServiceClient } = await import(
'@service-agent-harness/client'
@@ -60,8 +71,8 @@ describe('a block id that is already a session', () => {
});
});
-describe('a placeholder', () => {
- it('has no session until the create lands, then has that one', async () => {
+describe('an id whose create is in flight', () => {
+ it('has no session until the create lands, then is that session', async () => {
const placeholder = startPendingSession();
await createRoot(async (dispose) => {
const resolved = resolveSessionId(() => placeholder);
@@ -69,10 +80,24 @@ describe('a placeholder', () => {
expect(resolved.pending()).toBe(true);
expect(resolved.failed()).toBe(false);
- create.resolve?.('session-9');
+ create.resolve?.();
await flush();
- expect(resolved.sessionId()).toBe('session-9');
+ expect(resolved.sessionId()).toBe(placeholder);
+ expect(resolved.pending()).toBe(false);
+ dispose();
+ });
+ });
+
+ // A service that predates client-minted ids answers with its own; the
+ // block adopts that one exactly as it adopted a placeholder's before.
+ it('adopts the id the service answers with when it differs', async () => {
+ const minted = startPendingSession();
+ await createRoot(async (dispose) => {
+ const resolved = resolveSessionId(() => minted);
+ create.resolve?.('server-minted');
+ await flush();
+ expect(resolved.sessionId()).toBe('server-minted');
expect(resolved.pending()).toBe(false);
dispose();
});
@@ -109,6 +134,7 @@ describe('a placeholder', () => {
repoBranch: 'feature/home',
});
expect(agentHarnessServiceClient.create).toHaveBeenLastCalledWith({
+ id: placeholder,
botId: 'persona-1',
model: 'model-2',
repoUrl: 'https://github.com/macro-inc/macro',
@@ -116,14 +142,42 @@ describe('a placeholder', () => {
});
await createRoot(async (dispose) => {
const resolved = resolveSessionId(() => placeholder);
- create.resolve?.('session-10');
+ create.resolve?.();
await flush();
await flush();
expect(create.control.mock.calls).toEqual([
- ['session-10', { type: 'prompt', prompt: 'Fix the tests' }],
+ [placeholder, { type: 'prompt', prompt: 'Fix the tests' }],
]);
- expect(resolved.sessionId()).toBe('session-10');
+ expect(resolved.sessionId()).toBe(placeholder);
+ dispose();
+ });
+ });
+
+ // The prompt shows as sent from the block's own speculation the moment the
+ // session exists; the block must not wait for the harness to accept it.
+ it('has the session as soon as the create lands, prompt still on the wire', async () => {
+ let deliver: ((result: unknown) => void) | undefined;
+ create.control.mockReturnValue(
+ new Promise((resolve) => {
+ deliver = resolve;
+ })
+ );
+ const placeholder = startPendingSession({ prompt: 'Hello' });
+ await createRoot(async (dispose) => {
+ const resolved = resolveSessionId(() => placeholder);
+ expect(resolved.pendingPrompt()).toBe('Hello');
+ create.resolve?.();
+ await flush();
+ expect(resolved.sessionId()).toBe(placeholder);
+ expect(resolved.pending()).toBe(false);
+ expect(create.control).toHaveBeenCalledTimes(1);
+ deliver?.({
+ isErr: () => false,
+ value: { actionId: 'action-11', status: 'accepted' },
+ });
+ await flush();
+ expect(resolved.failed()).toBe(false);
dispose();
});
});
@@ -136,7 +190,7 @@ describe('a placeholder', () => {
const placeholder = startPendingSession({ prompt: 'Hello' });
await createRoot(async (dispose) => {
const resolved = resolveSessionId(() => placeholder);
- create.resolve?.('session-prompt-error');
+ create.resolve?.();
await flush();
expect(resolved.error()).toBe('Runtime is disconnected.');
expect(resolved.pending()).toBe(false);
@@ -144,13 +198,14 @@ describe('a placeholder', () => {
});
});
- // A placeholder URL reloaded in a new tab: the create it named belonged to
- // the tab that is gone, so there is nothing to wait for.
- it('with no create behind it is a failure, not a wait', () => {
+ // The id is final from the start, so a URL reloaded in another tab names a
+ // real session: it loads (or fails to) like any other, never a dead end.
+ it('with no create behind it in this tab is a session to load', () => {
createRoot((dispose) => {
- const resolved = resolveSessionId(() => 'pending-nothing');
+ const resolved = resolveSessionId(() => 'reloaded-elsewhere');
+ expect(resolved.sessionId()).toBe('reloaded-elsewhere');
expect(resolved.pending()).toBe(false);
- expect(resolved.failed()).toBe(true);
+ expect(resolved.failed()).toBe(false);
dispose();
});
});
@@ -170,10 +225,10 @@ it.each(['Describe this', ''])(
mimeType: 'image/png',
},
];
- startPendingSession({ prompt, attachments });
- create.resolve?.('session-image');
+ const id = startPendingSession({ prompt, attachments });
+ create.resolve?.();
await flush();
- expect(create.control).toHaveBeenCalledWith('session-image', {
+ expect(create.control).toHaveBeenCalledWith(id, {
type: 'prompt',
prompt,
attachments,
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.ts
index 7e713f37ea..61738ffaad 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
@@ -1,53 +1,49 @@
/**
* A block's session id, which may not exist yet.
*
- * The block mounts with whatever id the split gave it. Usually that is a real
- * session; for a just-created one it is a placeholder standing in for a create
- * still on the wire (`pending-session.ts`). This resolves the two into the one
- * shape the block consumes: an id that is absent until there is one, plus the
- * two facts the block chrome needs to explain the wait.
+ * The block mounts with whatever id the split gave it. Usually that is a
+ * session to load; for a just-created one it is an id whose create is still
+ * on the wire (`pending-session.ts`). This resolves the two into the one
+ * shape the block consumes: an id that is absent until the session exists,
+ * plus the facts the block chrome needs to explain the wait.
*/
import { type Accessor, createMemo } from 'solid-js';
-import { isPlaceholderSessionId, pendingSession } from './pending-session';
+import { pendingSession } from './pending-session';
export type ResolvedSessionId = {
- /** The real session id; absent while a create is still in flight. */
+ /** The session id; absent while its create is still in flight. */
sessionId: Accessor<string | undefined>;
/** This block is waiting on a create it started. */
pending: Accessor<boolean>;
- /** The create failed, or the placeholder has no create behind it. */
+ /** The create failed. */
failed: Accessor<boolean>;
error: Accessor<string | undefined>;
+ /** The first prompt of a create this block started, to show as sent while
+ * the create is still on the wire. */
+ pendingPrompt: Accessor<string | undefined>;
};
export function resolveSessionId(blockId: Accessor<string>): ResolvedSessionId {
- const entry = createMemo(() => {
- const id = blockId();
- return isPlaceholderSessionId(id)
- ? (pendingSession(id) ?? null)
- : undefined;
- });
+ // 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()));
- // `undefined` entry: the block id is already a session. `null`: a
- // placeholder nothing is creating — a reloaded placeholder URL, which can
- // only be an error, never a wait.
const sessionId = () => {
const session = entry();
if (session === undefined) return blockId();
- return session?.sessionId();
+ return session.sessionId();
};
return {
sessionId,
pending: () =>
- entry() != null &&
+ entry() !== undefined &&
!entry()?.failed() &&
entry()?.sessionId() === undefined,
- failed: () => entry() === null || (entry()?.failed() ?? false),
- error: () =>
- entry() === null
- ? 'This conversation was not created. Return to the composer to start a new one.'
- : entry()?.error(),
+ failed: () => entry()?.failed() ?? false,
+ error: () => entry()?.error(),
+ pendingPrompt: () => entry()?.prompt,
};
}
diff --git a/apps/web/src/features/block-agent/definition.ts b/apps/web/src/features/block-agent/definition.ts
index ce4ca7e00e..a0e001a012 100644
--- a/apps/web/src/features/block-agent/definition.ts
+++ b/apps/web/src/features/block-agent/definition.ts
@@ -1,10 +1,6 @@
import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';
import { ok } from 'neverthrow';
import { lazy } from 'solid-js';
-import {
- isPlaceholderSessionId,
- pendingSession,
-} from './context/pending-session';
export const definition = defineBlock({
name: 'agent',
@@ -12,16 +8,10 @@ export const definition = defineBlock({
component: lazy(() => import('./component/Block')),
liveTrackingEnabled: false,
async load(source, _intent) {
- if (source.type === 'dss') {
- // A placeholder is only meaningful to the tab that minted it (see
- // `context/pending-session.ts`). One arriving from anywhere else — a
- // reloaded URL, a restored layout — names a session this tab cannot
- // find, so it is missing rather than merely slow.
- if (isPlaceholderSessionId(source.id) && !pendingSession(source.id)) {
- return LoadErrors.MISSING;
- }
- return ok({ id: source.id });
- }
+ // A just-created session's id is the real one from the first frame
+ // (`context/pending-session.ts`), so a reloaded or restored URL loads it
+ // like any other; a create that never landed fails as a load, not here.
+ if (source.type === 'dss') return ok({ id: source.id });
return LoadErrors.MISSING;
},
accepted: {},
diff --git a/apps/web/src/features/home/home-agent-composer.test.tsx b/apps/web/src/features/home/home-agent-composer.test.tsx
index aae5f7254c..b589de6834 100644
--- a/apps/web/src/features/home/home-agent-composer.test.tsx
+++ b/apps/web/src/features/home/home-agent-composer.test.tsx
@@ -22,6 +22,9 @@ const mocks = vi.hoisted(() => ({
vi.mock('@app/features/block-agent/context/pending-session', () => ({
startPendingSession: mocks.start,
}));
+vi.mock('@core/context/user', () => ({
+ useUserId: () => () => 'viewer-1',
+}));
vi.mock('@components/app/split-layout/layoutUtils', () => ({
useSplitPanelOrThrow: () => ({ handle: { replace: mocks.replace } }),
}));
@@ -80,7 +83,8 @@ it('forwards the shared composer selection into the common session flow', () =>
repoBranch: 'feature/home',
};
mocks.onStart?.(start);
- expect(mocks.start).toHaveBeenCalledWith(start);
+ // The viewer rides along so the first prompt is attributed as the log will.
+ expect(mocks.start).toHaveBeenCalledWith({ ...start, userId: 'viewer-1' });
expect(mocks.replace).toHaveBeenCalledWith({
next: { type: 'component', id: 'agents-session~agents~pending-session' },
});
diff --git a/apps/web/src/features/home/home-agent-composer.tsx b/apps/web/src/features/home/home-agent-composer.tsx
index 3191ec4402..2745491668 100644
--- a/apps/web/src/features/home/home-agent-composer.tsx
+++ b/apps/web/src/features/home/home-agent-composer.tsx
@@ -3,6 +3,7 @@ import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';
import { useChatInputContext } from '@core/component/AI/context';
import { toast } from '@core/component/Toast/Toast';
import { useSettingsState } from '@core/constant/SettingsState';
+import { useUserId } from '@core/context/user';
import { registerHotkey } from '@core/hotkey/hotkeys';
import { TOKENS } from '@core/hotkey/tokens';
import { createEffect, createSignal } from 'solid-js';
@@ -23,6 +24,7 @@ export function HomeAgentComposer(props: { autoFocus?: boolean }) {
const input = useChatInputContext();
const roster = createAgentRosterSource();
const settings = useSettingsState();
+ const userId = useUserId();
const [draft, setDraft] = createSignal('');
let focus: (() => void) | undefined;
let draftVersion = 0;
@@ -65,7 +67,7 @@ export function HomeAgentComposer(props: { autoFocus?: boolean }) {
},
});
const start = (conversation: StartConversation) => {
- const id = startPendingSession(conversation);
+ const id = startPendingSession({ ...conversation, userId: userId() });
panel.handle.replace({
next: {
type: 'component',
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
index ce5a3d7ab3..66580b50cc 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequest.ts
@@ -5,6 +5,7 @@
* OpenAPI spec version: 0.1.0
*/
import type { CreateAgentSessionRequestBotId } from './createAgentSessionRequestBotId';
+import type { CreateAgentSessionRequestId } from './createAgentSessionRequestId';
import type { CreateAgentSessionRequestInstructions } from './createAgentSessionRequestInstructions';
import type { CreateAgentSessionRequestModel } from './createAgentSessionRequestModel';
import type { CreateAgentSessionRequestOwner } from './createAgentSessionRequestOwner';
@@ -36,6 +37,13 @@ default coding persona. On an external request, bot callers may omit it
(their own identity is used) and must not name another bot; user callers
must supply a bot they own. */
botId?: CreateAgentSessionRequestBotId;
+ /** Id to create the session under, minted by the caller. Lets a surface
+open on the session's final id - URL, history row, references - the
+moment the user acts, rather than after this request answers (which
+for a managed sandbox can take a while). Omitted, the service mints
+one. Managed sessions only. Answers 409 if a session already holds
+the id. */
+ id?: CreateAgentSessionRequestId;
/** Instructions the session's runtime works under, for its whole life.
Recorded on the session whichever runtime serves it. Only the
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestId.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestId.ts
new file mode 100644
index 0000000000..43b91abf91
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/createAgentSessionRequestId.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * agent_harness_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * Id to create the session under, minted by the caller. Lets a surface
+open on the session's final id - URL, history row, references - the
+moment the user acts, rather than after this request answers (which
+for a managed sandbox can take a while). Omitted, the service mints
+one. Managed sessions only. Answers 409 if a session already holds
+the id.
+ */
+export type CreateAgentSessionRequestId = string | null;
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
index 6b219e48b7..7998769823 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/generated/schemas/index.ts
@@ -88,6 +88,7 @@ export * from './controlResponse';
export * from './controlStatusDto';
export * from './createAgentSessionRequest';
export * from './createAgentSessionRequestBotId';
+export * from './createAgentSessionRequestId';
export * from './createAgentSessionRequestInstructions';
export * from './createAgentSessionRequestModel';
export * from './createAgentSessionRequestOwner';
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.json
index 194a9da901..cca82e9347 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
@@ -2296,6 +2296,11 @@
"format": "uuid",
"description": "Bot the session runs for. On a managed request this optionally selects\na persisted persona the user owns, may use through team membership, or\ncan `@` mention in a shared channel; omitting it uses the deployment's\ndefault coding persona. On an external request, bot callers may omit it\n(their own identity is used) and must not name another bot; user callers\nmust supply a bot they own."
},
+ "id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "Id to create the session under, minted by the caller. Lets a surface\nopen on the session's final id - URL, history row, references - the\nmoment the user acts, rather than after this request answers (which\nfor a managed sandbox can take a while). Omitted, the service mints\none. Managed sessions only. Answers 409 if a session already holds\nthe id."
+ },
"instructions": {
"type": ["string", "null"],
"description": "Instructions the session's runtime works under, for its whole life.\n\nRecorded on the session whichever runtime serves it. Only the\nin-process one acts on them today; `agent_harness`'s `AgentKind`\nrecords what each of the others will need to."
diff --git a/crates/agent_harness/src/domain/service/open.rs b/crates/agent_harness/src/domain/service/open.rs
index a84d6e9766..bc52731830 100644
--- a/crates/agent_harness/src/domain/service/open.rs
+++ b/crates/agent_harness/src/domain/service/open.rs
@@ -254,7 +254,7 @@ where
};
let defaults = self.inner.defaults.for_bot(bot_id);
let sandbox_size = self.inner.sessions.user_sandbox_size(&owner_user).await?;
- let session_id = AgentSessionId::new();
+ let session_id = request.id.unwrap_or_else(AgentSessionId::new);
// Same ordering as the trigger path's open: the token has to be minted
// before the row, because the row is what carries the hash that makes
// it mean anything.
diff --git a/crates/agent_harness/src/domain/service/test.rs b/crates/agent_harness/src/domain/service/test.rs
index 2c9103087a..10f1a11300 100644
--- a/crates/agent_harness/src/domain/service/test.rs
+++ b/crates/agent_harness/src/domain/service/test.rs
@@ -2723,6 +2723,7 @@ async fn a_managed_session_opens_as_the_managed_default_bot() {
let session = service
.open_managed_session(agent_session::domain::ports::OpenManagedSession {
+ id: None,
repo_url: None,
repo_branch: None,
instructions: None,
@@ -2961,6 +2962,7 @@ async fn managed_open_composes_its_prompt_without_channel_context() {
let result = service
.open_managed_session(OpenManagedSession {
+ id: None,
repo_url: None,
repo_branch: None,
instructions: None,
@@ -2989,6 +2991,7 @@ async fn open_managed_session_spawns_at_the_users_default_size() {
.expect("the user default should persist");
let open = service.open_managed_session(OpenManagedSession {
+ id: None,
repo_url: None,
repo_branch: None,
instructions: None,
@@ -3714,6 +3717,7 @@ mod lifecycle_events {
async fn codex_named_session_provisions_egress_without_advertising_mcp() {
let (service, repo, containers, _, _) = harness();
let open = service.open_managed_session(OpenManagedSession {
+ id: None,
repo_url: None,
repo_branch: None,
owner: model_owner::Owner::User(sender()),
@@ -3847,6 +3851,7 @@ impl crate::domain::ports::ReachableRepositories for SelectedRepositories {
async fn a_chosen_model_is_the_session_model_from_creation() {
let (service, repo, containers, _, _) = harness();
let open = service.open_managed_session(OpenManagedSession {
+ id: None,
repo_url: None,
repo_branch: None,
owner: model_owner::Owner::User(sender()),
@@ -3875,6 +3880,7 @@ async fn a_chosen_model_is_the_session_model_from_creation() {
async fn a_cursor_managed_session_is_always_stamped_cursor() {
let (service, repo, containers, _, _) = harness();
let open = service.open_managed_session(OpenManagedSession {
+ id: None,
repo_url: None,
repo_branch: None,
owner: model_owner::Owner::User(sender()),
@@ -3901,6 +3907,7 @@ async fn a_cursor_managed_session_is_always_stamped_cursor() {
fn explicit_cursor_request() -> OpenManagedSession {
OpenManagedSession {
+ id: None,
owner: model_owner::Owner::User(sender()),
instructions: None,
model: None,
diff --git a/crates/agent_session/src/domain/error.rs b/crates/agent_session/src/domain/error.rs
index 5fab862bdd..54c02036bf 100644
--- a/crates/agent_session/src/domain/error.rs
+++ b/crates/agent_session/src/domain/error.rs
@@ -31,6 +31,11 @@ pub enum AgentSessionError {
Disconnected(AgentSessionId),
#[error("this bot already has a session for this thread")]
ThreadSessionExists,
+ /// A create named an id a session already holds. Ids are minted by the
+ /// client so a surface can open on the final id before the create
+ /// answers; two creates under one id is a client bug, not a retry.
+ #[error("agent session {0} already exists")]
+ SessionIdTaken(AgentSessionId),
#[error("the session owner is not a known user")]
UnknownOwner,
/// A path that runs as the session's owner - spending their credentials,
diff --git a/crates/agent_session/src/domain/ports.rs b/crates/agent_session/src/domain/ports.rs
index d3014bad2d..dea3748416 100644
--- a/crates/agent_session/src/domain/ports.rs
+++ b/crates/agent_session/src/domain/ports.rs
@@ -219,6 +219,10 @@ pub struct OpenExternalAgentSession {
/// paths remain runtime-owned. There is no originating mention to announce.
#[derive(Debug, Clone)]
pub struct OpenManagedSession {
+ /// The id the session is created under, when the caller minted one so it
+ /// could open a surface on the final id before this answers. `None`
+ /// mints one here.
+ pub id: Option<AgentSessionId>,
/// Repository explicitly selected by the caller for a supported runtime.
pub repo_url: Option<String>,
/// Starting branch for the selected repository.
diff --git a/crates/agent_session/src/inbound/axum_router.rs b/crates/agent_session/src/inbound/axum_router.rs
index 0f5a5d3aff..bdf852a10d 100644
--- a/crates/agent_session/src/inbound/axum_router.rs
+++ b/crates/agent_session/src/inbound/axum_router.rs
@@ -1460,6 +1460,14 @@ where
#[derive(Debug, Clone, Default, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreateAgentSessionRequest {
+ /// Id to create the session under, minted by the caller. Lets a surface
+ /// open on the session's final id - URL, history row, references - the
+ /// moment the user acts, rather than after this request answers (which
+ /// for a managed sandbox can take a while). Omitted, the service mints
+ /// one. Managed sessions only. Answers 409 if a session already holds
+ /// the id.
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub id: Option<Uuid>,
/// Bot the session runs for. On a managed request this optionally selects
/// a persisted persona the user owns, may use through team membership, or
/// can `@` mention in a shared channel; omitting it uses the deployment's
@@ -1639,7 +1647,7 @@ impl IntoResponse for CreateSessionApiError {
Self::InvalidWorkspace(reason) => (StatusCode::UNPROCESSABLE_ENTITY, reason.to_owned()),
Self::MixedSessionShape => (
StatusCode::UNPROCESSABLE_ENTITY,
- "a managed session may take a prompt, persona and instructions; naming a \
+ "a managed session may take an id, prompt, persona and instructions; naming a \
workspace, owner or thread asks for an external one"
.to_owned(),
),
@@ -1658,6 +1666,10 @@ impl IntoResponse for CreateSessionApiError {
StatusCode::CONFLICT,
"this bot already has a session for this thread".to_owned(),
),
+ Self::Domain(AgentSessionError::SessionIdTaken(_)) => (
+ StatusCode::CONFLICT,
+ "a session with this id already exists".to_owned(),
+ ),
Self::Domain(AgentSessionError::InvalidRepositorySelection(reason)) => {
(StatusCode::UNPROCESSABLE_ENTITY, reason.to_owned())
}
@@ -1823,6 +1835,7 @@ pub async fn create_agent_session_handler<
let session = state
.opener
.open_managed_session(OpenManagedSession {
+ id: request.id.map(AgentSessionId::new_from_uuid),
repo_url: request.repo_url,
repo_branch: request
.repo_branch
@@ -1851,7 +1864,11 @@ pub async fn create_agent_session_handler<
// An external runtime sends its own first prompt through the control
// endpoint, so accepting one here would silently drop it, and it runs on
// whatever model its operator configured, which is not ours to set.
- if request.prompt.is_some() || request.repo_branch.is_some() || request.model.is_some() {
+ if request.prompt.is_some()
+ || request.repo_branch.is_some()
+ || request.model.is_some()
+ || request.id.is_some()
+ {
return Err(CreateSessionApiError::MixedSessionShape);
}
let bot_id = resolve_bot(&caller.authorization, request.bot_id)?;
diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rs
index c2cb949311..ea5ca331e1 100644
--- a/crates/agent_session/src/outbound/postgres.rs
+++ b/crates/agent_session/src/outbound/postgres.rs
@@ -326,6 +326,7 @@ impl AgentSessionRepo for PgAgentSessionRepo {
.await
.map_err(
|error| match error.as_database_error().and_then(|e| e.constraint()) {
+ Some("agent_session_pkey") => AgentSessionError::SessionIdTaken(id),
Some("agent_session_thread_bot_unique") => AgentSessionError::ThreadSessionExists,
Some("agent_session_owner_id_fkey") => AgentSessionError::UnknownOwner,
_ => AgentSessionError::Unknown(
diff --git a/crates/coding_agent_worker/src/dispatch.rs b/crates/coding_agent_worker/src/dispatch.rs
index e755aef630..0ad2be2381 100644
--- a/crates/coding_agent_worker/src/dispatch.rs
+++ b/crates/coding_agent_worker/src/dispatch.rs
@@ -49,6 +49,9 @@ impl WorkExecutor for Dispatcher {
content,
} => {
let request = CreateAgentSessionRequest {
+ // The service mints the id: nothing here opens a surface
+ // on it before the create answers.
+ id: None,
// A harness serves many agents, so the token implies no
// bot: name the mentioned agent, and the service verifies
// it is bound to this harness.
diff --git a/packages/sdk/generated/agent-harness/types.gen.ts b/packages/sdk/generated/agent-harness/types.gen.ts
index 8ca9f087a7..49d7c8d086 100644
--- a/packages/sdk/generated/agent-harness/types.gen.ts
+++ b/packages/sdk/generated/agent-harness/types.gen.ts
@@ -622,6 +622,15 @@ export type CreateAgentSessionRequest = {
* must supply a bot they own.
*/
botId?: string | null;
+ /**
+ * Id to create the session under, minted by the caller. Lets a surface
+ * open on the session's final id - URL, history row, references - the
+ * moment the user acts, rather than after this request answers (which
+ * for a managed sandbox can take a while). Omitted, the service mints
+ * one. Managed sessions only. Answers 409 if a session already holds
+ * the id.
+ */
+ id?: string | null;
/**
* Instructions the session's runtime works under, for its whole life.
*
diff --git a/packages/sdk/specs/agent-harness.json b/packages/sdk/specs/agent-harness.json
index 194a9da901..cca82e9347 100644
--- a/packages/sdk/specs/agent-harness.json
+++ b/packages/sdk/specs/agent-harness.json
@@ -2296,6 +2296,11 @@
"format": "uuid",
"description": "Bot the session runs for. On a managed request this optionally selects\na persisted persona the user owns, may use through team membership, or\ncan `@` mention in a shared channel; omitting it uses the deployment's\ndefault coding persona. On an external request, bot callers may omit it\n(their own identity is used) and must not name another bot; user callers\nmust supply a bot they own."
},
+ "id": {
+ "type": ["string", "null"],
+ "format": "uuid",
+ "description": "Id to create the session under, minted by the caller. Lets a surface\nopen on the session's final id - URL, history row, references - the\nmoment the user acts, rather than after this request answers (which\nfor a managed sandbox can take a while). Omitted, the service mints\none. Managed sessions only. Answers 409 if a session already holds\nthe id."
+ },
"instructions": {
"type": ["string", "null"],
"description": "Instructions the session's runtime works under, for its whole life.\n\nRecorded on the session whichever runtime serves it. Only the\nin-process one acts on them today; `agent_harness`'s `AgentKind`\nrecords what each of the others will need to."