Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
improvement(mothership): read a detached run's call as flat columns, …
…and name the paused case

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
  • Loading branch information
waleedlatif1 and claude committed Oct 31, 2026
commit b5d6485654138026ca7a3fc261cbbc3c266b4383
37 changes: 20 additions & 17 deletions apps/sim/lib/mothership/async-runs/repository.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -461,10 +461,25 @@ describe('async tool repository single-row semantics', () => {
})

describe('the workflow run a settled call left running', () => {
const stored = {
argv: null,
exitCode: null,
stdout: null,
status: null,
executionId: null,
}
const cli = (argv: string[], exitCode: number, record: Record<string, unknown>) => ({
...stored,
executableName: 'sim_cli',
args: { request: { invocation: { kind: 'cli', argv } } },
result: { exitCode, stdout: JSON.stringify(record), stderr: '' },
argv,
exitCode: String(exitCode),
stdout: JSON.stringify(record),
})
const tool = (executableName: string, status: string | null, executionId: string) => ({
...stored,
executableName,
status,
executionId,
})
const running = { runId: 'run-1', workflowId: 'wf-1', status: 'running' }

Expand All @@ -485,13 +500,7 @@ describe('the workflow run a settled call left running', () => {
})

it('is a workflow tool answered still running', () => {
expect(
detachedWorkflowExecutionId({
executableName: 'run_workflow',
args: { workflowId: 'wf-1' },
result: { status: 'running', executionId: 'exec-1', workflowId: 'wf-1' },
})
).toBe('exec-1')
expect(detachedWorkflowExecutionId(tool('run_workflow', 'running', 'exec-1'))).toBe('exec-1')
})

it.each([
Expand All @@ -503,15 +512,9 @@ describe('the workflow run a settled call left running', () => {
['a wait on a run', cli(['workflows', 'runs', 'wait', 'run-1'], 4, running)],
[
'an unreadable answer',
{
...cli(['workflows', 'run', 'wf-1'], 4, running),
result: { exitCode: 4, stdout: 'not json' },
},
],
[
'a workflow tool that settled',
{ executableName: 'run_block', args: {}, result: { success: true, executionId: 'exec-1' } },
{ ...cli(['workflows', 'run', 'wf-1'], 4, running), stdout: 'not json' },
],
['a workflow tool that settled', tool('run_block', null, 'exec-1')],
])('is not %s', (_label, call) => {
expect(detachedWorkflowExecutionId(call)).toBeUndefined()
})
Expand Down
46 changes: 24 additions & 22 deletions apps/sim/lib/mothership/async-runs/repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1826,10 +1826,7 @@ export async function prepareWorkbenchAccess(
if (processes.some((process) => process.sessionKey !== input.sessionKey))
throw new Error('Recorded workbench ownership does not match this chat')
return {
/**
* A workflow tool's handler runs a workflow, which never touches the workbench. One answered
* still running holds its run past its turn, so it must not hold the workbench too.
*/
// A workflow tool's run never touches the workbench, and one answered running outlives its turn.
handlersPending: previous.some(
(row) =>
!row.settledAt &&
Expand Down Expand Up @@ -1940,40 +1937,42 @@ export async function getUnsettledClientWorkflowExecutions(
)
}

/** The fields of a stored call that say whether it left a workflow run going, read as text. */
interface DetachedRunCall {
executableName: string | null
/** `args.request.invocation.argv` of a `sim_cli` call. */
argv: unknown
exitCode: string | null
stdout: string | null
status: string | null
executionId: string | null
}

/**
* The workflow execution a settled call started and left running: a `workflows run` the CLI
* answered still running (exit 4 and its run record), or a workflow tool answered still running
* (`WorkflowToolRunningResult`). A run the call only waited on (`workflows runs wait`) is not
* one: another run started it.
*/
export function detachedWorkflowExecutionId(call: {
executableName: string | null
args: unknown
result: unknown
}): string | undefined {
const result = toRecordOrNull(call.result)
if (!result) return undefined
export function detachedWorkflowExecutionId(call: DetachedRunCall): string | undefined {
if (call.executableName === 'sim_cli') {
const request = toRecordOrNull(toRecordOrNull(call.args)?.request)
const argv = toRecordOrNull(request?.invocation)?.argv
const argv = call.argv
// The command path, wherever global flags (`--output json`) put it, never `workflows runs`.
const end = Array.isArray(argv) && argv.includes('--') ? argv.indexOf('--') : undefined
const tokens = Array.isArray(argv) ? argv.slice(0, end) : []
if (!tokens.some((token, index) => token === 'workflows' && tokens[index + 1] === 'run'))
return undefined
if (result.exitCode !== 4 || typeof result.stdout !== 'string') return undefined
if (call.exitCode !== '4' || call.stdout === null) return undefined
try {
const record = toRecordOrNull(JSON.parse(result.stdout))
const record = toRecordOrNull(JSON.parse(call.stdout))
return record?.status === 'running' && typeof record.runId === 'string'
? record.runId
: undefined
} catch {
return undefined
}
}
return result.status === 'running' && typeof result.executionId === 'string'
? result.executionId
: undefined
return call.status === 'running' && call.executionId !== null ? call.executionId : undefined
}

/**
Expand All @@ -1995,12 +1994,15 @@ export async function getDetachedWorkflowExecutions(
{ [TraceAttr.StreamId]: streamId, [TraceAttr.UserId]: userId },
async () => {
const { args, result } = copilotAsyncToolCalls
/** Only the fields `detachedWorkflowExecutionId` reads, so no call's payload is loaded. */
const rows = await executor
// Only what `detachedWorkflowExecutionId` reads; an exit-4 `sim_cli` stdout is its run record.
const rows: DetachedRunCall[] = await executor
.select({
executableName: copilotAsyncToolCalls.executableName,
args: sql<unknown>`jsonb_build_object('request', jsonb_build_object('invocation', jsonb_build_object('argv', ${args} #> '{request,invocation,argv}')))`,
result: sql<unknown>`jsonb_build_object('exitCode', ${result} -> 'exitCode', 'stdout', ${result} -> 'stdout', 'status', ${result} -> 'status', 'executionId', ${result} -> 'executionId')`,
argv: sql<unknown>`${args} #> '{request,invocation,argv}'`,
exitCode: sql<string | null>`${result} ->> 'exitCode'`,
stdout: sql<string | null>`${result} ->> 'stdout'`,
status: sql<string | null>`${result} ->> 'status'`,
executionId: sql<string | null>`${result} ->> 'executionId'`,
})
.from(copilotAsyncToolCalls)
.innerJoin(copilotRuns, eq(copilotRuns.id, copilotAsyncToolCalls.runId))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -591,9 +591,14 @@ describe.runIf(Boolean(redisUrl))('settled client-claimed workflow tools', () =>
)
})

it.each(['pending', 'completed', 'failed', 'cancelled'] as const)(
it.each([
['pending (paused at a human approval)', 'pending'],
['completed', 'completed'],
['failed', 'failed'],
['cancelled', 'cancelled'],
] as const)(
'leaves a detached run whose log is %s for a Stop to skip',
async (logStatus) => {
async (_label, logStatus) => {
const detachedCli = generateId()
const detachedTool = generateId()
const cliCall = generateId()
Expand Down