mirror of
https://github.com/simstudioai/sim.git
synced 2026-11-24 22:49:06 +08:00
fix(copilot): recover tool arguments lost when a call is checkpointed mid-generation
Tool arguments reach Sim two ways: whole on a frame's `arguments`, or in pieces
as `args_delta` chunks that accumulate into `streamingArgs`. Only the first
populated `params`, so a call checkpointed before any frame carried `arguments`
executed with `{}` and failed its own schema on every required property. The
file subagent's `workspace_file` calls arrive exactly that way, which left the
agent retrying and then routing around the tool entirely.
- executor: hydrate `params` from the streamed deltas before dispatch, covering
both normal dispatch and the never-dispatched resume path.
- handlers: record the subagent channel at registration rather than only on a
finalized frame, so the workspace_file -> edit_content intent handoff can find
its intent instead of reporting "No workspace_file context found".
- preview adapter: pass the frame's tool call id into file delegation, which
derives its audit id from it. Without it every preview threw and no file
content streamed at all.
- run: a checkpointed call with no recorded result now reports a failed result
instead of throwing, which ended the whole turn and cost the user the entire
response.
Each fix has a regression test verified to fail without it.
This commit is contained in:
1 parent
c0ef569b56
commit
b25e7ba0c3
7 files changed
+234
-5
No files matched your search
@@ -376,7 +376,11 @@ export async function processFilePreviewStreamEvent(input: {
|
||||
if (toolCallId && parsedArgs) {
|
||||
const { operation, title, contentType, edit } = parsedArgs
|
||||
const target = await resolvePreviewTarget({
|
||||
context: execContext,
|
||||
/* File delegation derives its audit id from the tool call
|
||||
(`copilot-tool:<toolCallId>`), and that id lives on the frame rather
|
||||
than the turn-scoped context. Passing the turn context alone made
|
||||
every preview throw, so the file stopped streaming entirely. */
|
||||
context: { ...execContext, toolCallId },
|
||||
workspaceId: execContext.workspaceId,
|
||||
target: parsedArgs.target,
|
||||
})
|
||||
@@ -405,7 +409,7 @@ export async function processFilePreviewStreamEvent(input: {
|
||||
(operation === 'append' || operation === 'patch')
|
||||
) {
|
||||
previewBase = await loadWorkspaceFileTextForPreview(
|
||||
execContext,
|
||||
{ ...execContext, toolCallId },
|
||||
execContext.workspaceId,
|
||||
fileId
|
||||
)
|
||||
@@ -480,7 +484,7 @@ export async function processFilePreviewStreamEvent(input: {
|
||||
(intent.operation === 'append' || intent.operation === 'patch')
|
||||
) {
|
||||
previewBase = await loadWorkspaceFileTextForPreview(
|
||||
execContext,
|
||||
{ ...execContext, toolCallId: streamEvent.payload.toolCallId },
|
||||
execContext.workspaceId,
|
||||
result.fileId
|
||||
)
|
||||
|
||||
@@ -38,7 +38,13 @@ vi.mock('@/lib/uploads/contexts/workspace/workspace-file-manager', () => ({
|
||||
}) ?? null,
|
||||
}))
|
||||
vi.mock('@/lib/workspace-files/application/list-workspace-files', () => ({
|
||||
listAllWorkspaceFiles: { execute: listAllWorkspaceFilesMock },
|
||||
/* `executeCopilotFileUseCase` reads `useCase.operation.id` to check the
|
||||
operation is registered before running it, so a use-case mock without an
|
||||
`operation` throws before `execute` is ever reached. */
|
||||
listAllWorkspaceFiles: {
|
||||
execute: listAllWorkspaceFilesMock,
|
||||
operation: { id: 'files.list' },
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/copilot/tools/server/files/file-preview', async () => {
|
||||
|
||||
@@ -886,6 +886,109 @@ describe('sse-handlers tool lifecycle', () => {
|
||||
)
|
||||
})
|
||||
|
||||
/**
|
||||
* A call can be checkpointed while every frame it received is still
|
||||
* `generating`. The subagent channel must already be on the tool call by
|
||||
* then: the workspace_file -> edit_content intent handoff scopes on it, and
|
||||
* recording it only on a finalized frame left edit_content reporting
|
||||
* "No workspace_file context found" for a write that had in fact succeeded.
|
||||
*/
|
||||
/**
|
||||
* Arguments reach Sim either whole on a frame or in `args_delta` pieces. A
|
||||
* call checkpointed before any frame carries `arguments` used to execute with
|
||||
* `{}` — its own schema then rejected every required property — even though
|
||||
* the full argument JSON had already arrived as deltas.
|
||||
*/
|
||||
it('executes with arguments recovered from args_delta frames', async () => {
|
||||
executeTool.mockResolvedValueOnce({ success: true, output: { ok: true } })
|
||||
context.toolCalls.set('parent-1', {
|
||||
id: 'parent-1',
|
||||
name: 'file',
|
||||
status: 'pending',
|
||||
startTime: Date.now(),
|
||||
})
|
||||
|
||||
const call = {
|
||||
toolCallId: 'sub-tool-delta',
|
||||
toolName: 'workspace_file',
|
||||
executor: MothershipStreamV1ToolExecutor.sim,
|
||||
mode: MothershipStreamV1ToolMode.async,
|
||||
phase: MothershipStreamV1ToolPhase.call,
|
||||
}
|
||||
const scope = { lane: 'subagent', parentToolCallId: 'parent-1', agentId: 'file' } as const
|
||||
|
||||
// Registered while still generating, with no arguments on the frame.
|
||||
await subAgentHandlers.tool(
|
||||
{
|
||||
type: MothershipStreamV1EventType.tool,
|
||||
scope,
|
||||
payload: { ...call, status: 'generating' },
|
||||
} as StreamEvent,
|
||||
context,
|
||||
execContext,
|
||||
{ interactive: false, timeout: 1000 }
|
||||
)
|
||||
|
||||
for (const argumentsDelta of ['{"operation":"update",', '"title":"Set contents"}']) {
|
||||
await subAgentHandlers.tool(
|
||||
{
|
||||
type: MothershipStreamV1EventType.tool,
|
||||
scope,
|
||||
payload: {
|
||||
toolCallId: 'sub-tool-delta',
|
||||
toolName: 'workspace_file',
|
||||
phase: 'args_delta',
|
||||
argumentsDelta,
|
||||
},
|
||||
} as unknown as StreamEvent,
|
||||
context,
|
||||
execContext,
|
||||
{ interactive: false, timeout: 1000 }
|
||||
)
|
||||
}
|
||||
|
||||
await executeToolAndReport('sub-tool-delta', context, execContext, {
|
||||
interactive: false,
|
||||
timeout: 1000,
|
||||
})
|
||||
|
||||
expect(executeTool).toHaveBeenCalledWith(
|
||||
'workspace_file',
|
||||
{ operation: 'update', title: 'Set contents' },
|
||||
expect.any(Object)
|
||||
)
|
||||
})
|
||||
|
||||
it('records the subagent channel from a generating frame, before any final frame', async () => {
|
||||
context.toolCalls.set('parent-1', {
|
||||
id: 'parent-1',
|
||||
name: 'file',
|
||||
status: 'pending',
|
||||
startTime: Date.now(),
|
||||
})
|
||||
|
||||
await subAgentHandlers.tool(
|
||||
{
|
||||
type: MothershipStreamV1EventType.tool,
|
||||
scope: { lane: 'subagent', parentToolCallId: 'parent-1', agentId: 'file' },
|
||||
payload: {
|
||||
toolCallId: 'sub-tool-partial',
|
||||
toolName: 'workspace_file',
|
||||
executor: MothershipStreamV1ToolExecutor.sim,
|
||||
mode: MothershipStreamV1ToolMode.async,
|
||||
phase: MothershipStreamV1ToolPhase.call,
|
||||
status: 'generating',
|
||||
arguments: { operation: 'update' },
|
||||
},
|
||||
} satisfies StreamEvent,
|
||||
context,
|
||||
execContext,
|
||||
{ interactive: false, timeout: 1000 }
|
||||
)
|
||||
|
||||
expect(context.toolCalls.get('sub-tool-partial')?.parentToolCallId).toBe('parent-1')
|
||||
})
|
||||
|
||||
it('updates stored params when a subagent generating event is followed by the final tool call', async () => {
|
||||
executeTool.mockResolvedValueOnce({ success: true, output: { ok: true } })
|
||||
context.toolCalls.set('parent-1', {
|
||||
|
||||
@@ -583,6 +583,11 @@ function registerSubagentToolCall(
|
||||
status: 'pending',
|
||||
agentId,
|
||||
params: args,
|
||||
/* The invoking subagent's channel, recorded here rather than only on a
|
||||
finalized frame: a call checkpointed while every frame is still partial
|
||||
would otherwise execute with no channel, and the workspace_file ->
|
||||
edit_content intent handoff scopes on exactly this id. */
|
||||
parentToolCallId,
|
||||
startTime: Date.now(),
|
||||
}
|
||||
applyToolDisplay(toolCall)
|
||||
|
||||
@@ -1634,6 +1634,68 @@ describe('runCopilotLifecycle', () => {
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* Go blocks on a result for every checkpointed call. Throwing here used to end
|
||||
* the whole turn, so one unrecorded result cost the user the entire response —
|
||||
* and the only thing preventing it was a partial frame happening to register
|
||||
* the call. Report the failure as that tool's result instead, so the model
|
||||
* sees one failed call and can route around it.
|
||||
*/
|
||||
it('reports a failed result instead of ending the turn when a checkpointed tool has none', async () => {
|
||||
const billingAttribution = {
|
||||
actorUserId: 'user-1',
|
||||
workspaceId: 'ws-1',
|
||||
billedAccountUserId: 'owner-1',
|
||||
organizationId: 'org-1',
|
||||
billingEntity: { type: 'organization' as const, id: 'org-1' },
|
||||
billingPeriod: {
|
||||
start: '2026-07-01T00:00:00.000Z',
|
||||
end: '2026-08-01T00:00:00.000Z',
|
||||
},
|
||||
payerSubscription: null,
|
||||
}
|
||||
mockRunStreamLoop.mockImplementationOnce(
|
||||
async (
|
||||
_fetchUrl: string,
|
||||
_fetchOptions: RequestInit,
|
||||
context: StreamingContext
|
||||
): Promise<void> => {
|
||||
// Registered but never resolved — no `result` ever recorded.
|
||||
context.toolCalls.set('tool-1', {
|
||||
id: 'tool-1',
|
||||
name: 'workspace_file',
|
||||
status: MothershipStreamV1ToolOutcome.error,
|
||||
})
|
||||
context.awaitingAsyncContinuation = {
|
||||
checkpointId: 'ckpt-1',
|
||||
pendingToolCallIds: ['tool-1'],
|
||||
}
|
||||
}
|
||||
)
|
||||
mockRunStreamLoop.mockResolvedValueOnce(undefined)
|
||||
|
||||
await expect(
|
||||
runCopilotLifecycle(
|
||||
{ message: 'hello', messageId: 'message-1' },
|
||||
{
|
||||
userId: 'user-1',
|
||||
workspaceId: 'ws-1',
|
||||
chatId: 'chat-1',
|
||||
executionId: 'execution-1',
|
||||
runId: 'run-1',
|
||||
simRequestId: 'request-1',
|
||||
billingAttribution,
|
||||
}
|
||||
)
|
||||
).resolves.toBeDefined()
|
||||
|
||||
// The turn continued: a second leg ran, carrying the failed result back.
|
||||
expect(mockRunStreamLoop).toHaveBeenCalledTimes(2)
|
||||
const resumeBody = JSON.parse((mockRunStreamLoop.mock.calls[1]?.[1].body as string) ?? '{}')
|
||||
const sent = JSON.stringify(resumeBody)
|
||||
expect(sent).toContain('tool-1')
|
||||
})
|
||||
|
||||
it('fails closed instead of sending a secret-bearing tool name on resume', async () => {
|
||||
const registry = new ResolvedSecretTraceRegistry([
|
||||
{ name: 'TOKEN', plaintext: 'unsafe-tool', encryptedValue: 'ciphertext' },
|
||||
|
||||
@@ -1780,7 +1780,27 @@ async function runCheckpointLoop(
|
||||
toolStatus: tool?.status,
|
||||
hasPendingPromise: context.pendingToolPromises.has(toolCallId),
|
||||
})
|
||||
throw new Error(`Cannot resume: missing result for pending tool call ${toolCallId}`)
|
||||
/**
|
||||
* Go is blocked on a result for every checkpointed call, so throwing
|
||||
* here ends the turn outright and the user loses the whole response.
|
||||
* Report the failure as that tool's result instead: the model sees one
|
||||
* failed call and can retry or route around it, which is how every
|
||||
* other tool failure already behaves. Reached only when a call was
|
||||
* checkpointed without Sim ever recording a result for it.
|
||||
*/
|
||||
const failedName = tool?.name ?? ''
|
||||
results.push({
|
||||
callId: toolCallId,
|
||||
name: failedName,
|
||||
data: getToolCallTerminalData({
|
||||
id: toolCallId,
|
||||
name: failedName,
|
||||
status: MothershipStreamV1ToolOutcome.error,
|
||||
error: `Tool call ${toolCallId} produced no result before resume`,
|
||||
}),
|
||||
success: false,
|
||||
})
|
||||
continue
|
||||
}
|
||||
const name = tool.name || ''
|
||||
if (!isResolvedSecretModelContentUnchanged(name, execContext.resolvedSecretTraceRegistry)) {
|
||||
|
||||
@@ -499,6 +499,33 @@ function terminalCompletionFromToolCall(toolCall: ToolCallState): AsyncToolCompl
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Recovers a tool call's arguments from the raw argument stream.
|
||||
*
|
||||
* Arguments reach Sim two ways: whole, on a tool frame's `arguments`, or in
|
||||
* pieces, as `argumentsDelta` chunks that `handleToolArgsDelta` concatenates
|
||||
* into `streamingArgs`. Only the first populates `params`. When a call is
|
||||
* checkpointed before any frame carries `arguments` — which is how the file
|
||||
* subagent's `workspace_file` calls arrive — `params` stays undefined and the
|
||||
* tool executes with `{}`, failing its own schema on every required property.
|
||||
* The arguments were never lost, only unparsed, so recover them here rather
|
||||
* than dispatching a call known to be incomplete.
|
||||
*/
|
||||
function hydrateParamsFromStreamedArgs(toolCall: ToolCallState): void {
|
||||
if (toolCall.params !== undefined) return
|
||||
const streamed = toolCall.streamingArgs?.trim()
|
||||
if (!streamed) return
|
||||
try {
|
||||
const parsed = JSON.parse(streamed)
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
toolCall.params = parsed as Record<string, unknown>
|
||||
}
|
||||
} catch {
|
||||
// A truncated stream is not recoverable; leave params undefined so the
|
||||
// tool's own validation reports the failure.
|
||||
}
|
||||
}
|
||||
|
||||
export async function executeToolAndReport(
|
||||
toolCallId: string,
|
||||
context: StreamingContext,
|
||||
@@ -512,6 +539,8 @@ export async function executeToolAndReport(
|
||||
message: 'Tool call not found',
|
||||
})
|
||||
|
||||
hydrateParamsFromStreamedArgs(toolCall)
|
||||
|
||||
const argsPayload = toolCall.params
|
||||
? (() => {
|
||||
try {
|
||||
|
||||
Reference in new issue
Block a user