Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions packages/assistant-ui-runtime/src/collectPending.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,41 @@ export function derivePendingMcpAuth(
return { mcpServers: servers };
}

const UPDATE_CURRENT_SESSION_TOOL_NAME = 'update_current_session';
/** Mirrors `TRUEFORGE_MCP_ID` in trueforge-core. This package does not depend on it. */
const TRUEFORGE_MCP_SERVER_ID = 'built-in:trueforge-mcp';

function isUpdateCurrentSessionCall(part: ToolCallPart): boolean {
// The TrueForge server is deferred, so its tools arrive as `call_tool` and the
// target server is the `mcp_server` argument. A same-named tool on another server
// must not refresh this session's spec.
return (
part.toolName === 'call_tool' &&
part.args['tool_name'] === UPDATE_CURRENT_SESSION_TOOL_NAME &&
part.args['mcp_server'] === TRUEFORGE_MCP_SERVER_ID
);
}

/** Tool call id of the latest finished `update_current_session` call, which rewrites the session's spec. */
export function findLatestSessionSpecUpdate(messages: readonly ThreadMessage[]): string | undefined {
let latest: string | undefined;
for (const message of messages) {
if (message.role !== 'assistant') {
continue;
}
walkToolCallParts(
message.content,
part => {
if (part.result !== undefined && isUpdateCurrentSessionCall(part)) {
latest = part.toolCallId;
}
},
ROOT_THREAD_ID,
);
}
return latest;
}

/**
* Most recent `sandboxId` observed anywhere in the conversation, scanning backward.
* Unlike `derivePendingMcpAuth`, this isn't gated on message status: once a sandbox
Expand Down
19 changes: 19 additions & 0 deletions packages/assistant-ui-runtime/src/draft/useDraftAgentSpec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ export interface UseDraftAgentSpecResult {
updateAgentSpec: (update: AgentSpecUpdate) => void;
flushAgentSpec: () => Promise<void>;
adoptAgentSpec: (request: { agentSpec: AgentSpec; updatedAt?: string }) => void;
/** Re-read the stored spec after the backend changed it (e.g. the agent edited its own session). */
reloadAgentSpec: () => Promise<void>;
takeTurnHeaderTimestamp: () => Promise<string | undefined>;
}

Expand Down Expand Up @@ -223,6 +225,21 @@ export function useDraftAgentSpec({
[],
);

const reloadAgentSpec = useCallback(async () => {
if (draftBridge == null || draftSessionId == null) {
return;
}
try {
const loaded = await draftBridge.getDraftAgentSpec(draftSessionId);
if (loaded == null || activeDraftIdRef.current !== draftSessionId) {
return;
}
adoptAgentSpec({ agentSpec: loaded });
} catch (error) {
onError?.(error);
}
}, [adoptAgentSpec, draftBridge, draftSessionId, onError]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overlapping reloads can apply a stale spec

Medium Severity

reloadAgentSpec does not ignore stale in-flight fetches. Each finished update_current_session starts a new GET, and adoptAgentSpec always applies whichever response returns last. A slower first fetch can overwrite a later spec, so the draft UI can miss the most recent agent edit.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 81d66c2. Configure here.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In-flight spec sync can clobber agent updates

Medium Severity

reloadAgentSpec adopts the GET result without stopping a PATCH that is already in flight. Clearing inFlightFlushRef only drops the local promise; a debounced user syncAgentSpec can still complete afterward and overwrite the spec update_current_session just wrote, leaving the UI and server disagreeing.

Additional Locations (1)
Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 81d66c2. Configure here.


const takeTurnHeaderTimestamp = useCallback(async () => {
await flushPendingSpecSyncNow();
const updatedAt = lastUpdatedAtRef.current;
Expand Down Expand Up @@ -265,6 +282,7 @@ export function useDraftAgentSpec({
updateAgentSpec,
flushAgentSpec: flushPendingSpecSyncNow,
adoptAgentSpec,
reloadAgentSpec,
takeTurnHeaderTimestamp,
}),
[
Expand All @@ -276,6 +294,7 @@ export function useDraftAgentSpec({
specError,
flushPendingSpecSyncNow,
adoptAgentSpec,
reloadAgentSpec,
takeTurnHeaderTimestamp,
updateAgentSpec,
],
Expand Down
35 changes: 35 additions & 0 deletions packages/assistant-ui-runtime/src/useTrueForgeAgentRuntime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
collectPendingToolResponses,
derivePendingMcpAuth,
deriveSandboxId,
findLatestSessionSpecUpdate,
} from './collectPending.js';
import {
buildUserMessageContent,
Expand Down Expand Up @@ -156,6 +157,40 @@ function useTrueForgeAgentRuntimeImpl(
const pendingMcpAuth = useMemo(() => derivePendingMcpAuth(messages), [messages]);
const sandboxId = useMemo(() => deriveSandboxId(messages), [messages]);

const sessionSpecUpdateId = useMemo(() => findLatestSessionSpecUpdate(messages), [messages]);
const handledSessionSpecUpdateIdRef = useRef<string | undefined>(undefined);
// Gate reloads on "has this session run in this mount", not on the current
// isRunning flag. Stream teardown often applies the tool result and clears
// isRunning in the same batch; marking the id handled while skipping reload
// would drop that update permanently.
const sawRunningInSessionRef = useRef(false);
const trackedSessionIdRef = useRef(sessionId);
if (trackedSessionIdRef.current !== sessionId) {
trackedSessionIdRef.current = sessionId;
sawRunningInSessionRef.current = false;
handledSessionSpecUpdateIdRef.current = undefined;
}
const reloadAgentSpec = draftSpec.reloadAgentSpec;
useEffect(() => {
if (isRunning) {
sawRunningInSessionRef.current = true;
}
}, [isRunning]);
useEffect(() => {
if (sessionSpecUpdateId === undefined || sessionSpecUpdateId === handledSessionSpecUpdateIdRef.current) {
return;
}
// Calls already in loaded history are reflected in the spec loaded with the session.
if (!sawRunningInSessionRef.current) {
handledSessionSpecUpdateIdRef.current = sessionSpecUpdateId;
return;
}
handledSessionSpecUpdateIdRef.current = sessionSpecUpdateId;
if (agent.mode === 'draft') {
void reloadAgentSpec();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Paused turns skip the spec reload

Medium Severity

The reload effect treats any update_current_session seen before isRunning as historical and never fetches again. A session opened while paused (for example waiting on approval) never sets that flag, so when the tool later finishes the new spec is marked handled and the draft UI stays on the old spec.

Fix in Cursor Fix in Web

Reviewed by Cursor Bugbot for commit 81d66c2. Configure here.

}, [agent.mode, reloadAgentSpec, sessionSpecUpdateId]);

const downloadSandboxFile = useCallback(
async ({ turnId, path }: { turnId: string; path: string }) => {
if (server.downloadSandboxFile == null) {
Expand Down
63 changes: 63 additions & 0 deletions packages/assistant-ui-runtime/test/collectPending.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
collectPendingToolResponses,
derivePendingMcpAuth,
deriveSandboxId,
findLatestSessionSpecUpdate,
} from '../src/collectPending.js';
import { ROOT_THREAD_ID } from '../src/constants.js';
import { MESSAGE_CUSTOM_KEY } from '../src/messageCustomMetadata.js';
Expand Down Expand Up @@ -135,3 +136,65 @@ describe('current pause collection', () => {
expect(collectPendingApprovals([pausedApproval])).toEqual([expect.objectContaining({ approvalId: 'approval-1' })]);
});
});

describe('findLatestSessionSpecUpdate', () => {
function toolCall(toolCallId: string, toolName: string, args: Record<string, string>, result?: string) {
return {
type: 'tool-call' as const,
toolCallId,
toolName,
args,
argsText: JSON.stringify(args),
...(result === undefined ? {} : { result }),
};
}

it('returns the latest finished update_current_session call on the TrueForge server', () => {
const messages = [
assistantMessage('a1', {
content: [
toolCall(
'first',
'call_tool',
{ mcp_server: 'built-in:trueforge-mcp', tool_name: 'update_current_session' },
'{}',
),
],
}),
userMessage('u2'),
assistantMessage('a2', {
content: [
toolCall(
'second',
'call_tool',
{ mcp_server: 'built-in:trueforge-mcp', tool_name: 'update_current_session' },
'{}',
),
],
}),
];
expect(findLatestSessionSpecUpdate(messages)).toBe('second');
});

it('ignores the same tool name on another server, direct calls, and calls still running', () => {
const messages = [
assistantMessage('a1', {
content: [
toolCall('other-server', 'call_tool', { mcp_server: 'github', tool_name: 'update_current_session' }, '{}'),
toolCall('direct', 'update_current_session', {}, '{}'),
toolCall('running', 'call_tool', {
mcp_server: 'built-in:trueforge-mcp',
tool_name: 'update_current_session',
}),
toolCall(
'done',
'call_tool',
{ mcp_server: 'built-in:trueforge-mcp', tool_name: 'update_current_session' },
'{}',
),
],
}),
];
expect(findLatestSessionSpecUpdate(messages)).toBe('done');
});
});
Loading