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
4 changes: 2 additions & 2 deletions .github/workflows/desktop-e2e.yml
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,7 @@ jobs:
working-directory: apps/desktop
run: bunx playwright install chromium

# The terminal-cancel suite drives a real tmux server; without tmux its tmux scenarios skip.
# The terminal-cancel suite drives a real tmux server and fails when tmux is missing.
- name: Install tmux
run: brew install tmux
env:
Expand Down Expand Up @@ -241,7 +241,7 @@ jobs:
working-directory: apps/desktop
run: bunx playwright install chromium

# The terminal-cancel suite drives a real tmux server; without tmux its tmux scenarios skip.
# The terminal-cancel suite drives a real tmux server and fails when tmux is missing.
- name: Install tmux
run: brew install tmux
env:
Expand Down
57 changes: 57 additions & 0 deletions apps/desktop/src/main/browser-agent/driver.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,35 @@ describe('executeTool', () => {
expect(result.error).toContain('the user started working in this page')
})

it('sends no input once the action budget is spent, even before the watchdog timer fires', async () => {
await driver.executeTool('chat-test', 'browser_open_tab', {})
const contents = session.requireTab().view.webContents
const watchdogMs = driver.browserToolWatchdogMs('browser_press_key', { key: 'Enter' })
if (watchdogMs === null) throw new Error('browser_press_key must have a watchdog')
vi.useFakeTimers()
try {
// The clock passes the deadline while the action reads the page, with no timer run yet.
const probe = vi.mocked(contents.executeJavaScript).getMockImplementation()
vi.mocked(contents.executeJavaScript).mockImplementation(async (...args) => {
vi.setSystemTime(Date.now() + watchdogMs + 1)
return probe ? probe(...args) : undefined
})
vi.mocked(contents.debugger.sendCommand).mockClear()

const pending = driver.executeTool('chat-test', 'browser_press_key', { key: 'Enter' })
await vi.advanceTimersByTimeAsync(watchdogMs)
const result = await pending

expect(result.ok).toBe(false)
expect(contents.debugger.sendCommand).not.toHaveBeenCalledWith(
'Input.dispatchKeyEvent',
expect.anything()
)
} finally {
vi.useRealTimers()
}
})

it('never makes a background read wait for the user', async () => {
await driver.executeTool('chat-test', 'browser_open_tab', {})
typeInAgentPage(session.requireTab().view.webContents)
Expand Down Expand Up @@ -1127,6 +1156,34 @@ describe('executeTool', () => {
vi.useRealTimers()
}
})

it('charges the first-page wait to the watchdog so the call ends within its budget', async () => {
const { contents, listeners, registered } = await openLoadingTab()
const watchdogMs = driver.browserToolWatchdogMs('browser_snapshot', {})
if (watchdogMs === null) throw new Error('browser_snapshot must have a watchdog')
const loadAfterMs = Math.floor(watchdogMs / 2) - 1
vi.mocked(contents.executeJavaScript).mockReturnValue(new Promise(() => {}))
vi.useFakeTimers()
try {
let outcome: unknown
void driver.executeTool('chat-test', 'browser_snapshot', {}).then((result) => {
outcome = result
})
await vi.advanceTimersByTimeAsync(loadAfterMs)
vi.mocked(contents.getURL).mockReturnValue('http://127.0.0.1/popup')
vi.mocked(contents.isLoading).mockReturnValue(false)
for (const onLoaded of listeners('did-stop-loading').slice(registered)) onLoaded()

// The page hangs once loaded; the call must still end at the watchdog measured from the start.
await vi.advanceTimersByTimeAsync(watchdogMs - loadAfterMs + 1)
expect(outcome).toMatchObject({
ok: false,
error: expect.stringContaining('did not finish this action in time'),
})
} finally {
vi.useRealTimers()
}
})
})

it('leaves no watchdog timer pending once a tool finishes', async () => {
Expand Down
39 changes: 25 additions & 14 deletions apps/desktop/src/main/browser-agent/driver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5501,6 +5501,9 @@ export async function executeTool(
tool !== 'browser_request_takeover' &&
!BROWSER_TOOL_OBSERVES_ONLY[tool]
const watchdogMs = browserToolWatchdogMs(tool, params)
// The waits for the user and for a first page spend the action's own budget: the client
// times the call as queue plus watchdog, so time spent before acting cannot be extra.
const executionDeadline = watchdogMs === null ? undefined : Date.now() + watchdogMs
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
if (yieldsToUser && isUserWorkingInPage()) {
await yieldToUser(
toolCallId,
Expand Down Expand Up @@ -5531,11 +5534,15 @@ export async function executeTool(
? { contents: session.requireAutomationTab().view.webContents, response }
: null
const executionEpoch = ++state.toolExecutionEpoch
const executionDeadline = watchdogMs === null ? undefined : Date.now() + watchdogMs
// Checked right before each input the action sends: a user who starts working in the
// page mid-action (between a batch's steps, during a click's target probes) wins it.
// The pre-action waits can spend the whole budget; the watchdog's timer only fires once
// the action yields, so an input dispatched before then must check the deadline itself.
const assertCurrentExecution = () => {
if (state.toolExecutionEpoch !== executionEpoch) {
if (
state.toolExecutionEpoch !== executionEpoch ||
(executionDeadline !== undefined && Date.now() >= executionDeadline)
) {
throw new ToolError('This browser action expired before it could dispatch input.')
}
if (yieldsToUser && isUserWorkingInPage()) {
Expand Down Expand Up @@ -5588,20 +5595,24 @@ export async function executeTool(
)
const cancellableExecution = Promise.race([execution, cancellation])
const guardedExecution =
watchdogMs === null
executionDeadline === undefined
? cancellableExecution
: raceAgainstWatchdog(cancellableExecution, watchdogMs, () => {
executionController.abort()
if (state.toolExecutionEpoch === executionEpoch) state.toolExecutionEpoch++
if (
tool === 'browser_snapshot' ||
tool === 'browser_open_url' ||
tool === 'browser_find' ||
observeRequest(tool, params) !== undefined
) {
invalidateSnapshot(state)
: raceAgainstWatchdog(
cancellableExecution,
Math.max(0, executionDeadline - Date.now()),
() => {
executionController.abort()
if (state.toolExecutionEpoch === executionEpoch) state.toolExecutionEpoch++
if (
tool === 'browser_snapshot' ||
tool === 'browser_open_url' ||
tool === 'browser_find' ||
observeRequest(tool, params) !== undefined
) {
invalidateSnapshot(state)
}
}
})
)
let observedResult: unknown
try {
observedResult = await guardedExecution
Expand Down
5 changes: 3 additions & 2 deletions apps/desktop/src/main/observability.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,8 +82,9 @@ const FAILURE_DEDUPE_MS = 5_000
*
* The recovery prompt never outlives a quit: a failure once a quit is committed
* (`will-quit`) exits without asking, since a dialog opened during shutdown can
* only fall back to a blocking native alert, and any quit request while the
* prompt is open answers it as Quit. A `before-quit` that another listener
* only fall back to a blocking native alert, and a quit request while the
* bundled prompt is open answers it as Quit (the native fallback, used only when
* that page fails to load, cannot be answered by a quit). A `before-quit` that another listener
* cancels leaves later failures their prompt.
*/
export function installMainProcessFailureObservers({
Expand Down
14 changes: 13 additions & 1 deletion apps/sim/lib/function-execution/execute-request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3929,12 +3929,24 @@ describe('Function execution request', () => {
const data = await failRemote(
'javascript',
'import "node:path"\nreturn 1',
'SyntaxError: /home/user/index.js: Unexpected token (9:8)'
'SyntaxError: /home/user/.sim-function-a1B2c3_d4.mjs: Unexpected token (9:8)'
)
expect(data.error).toBe('SyntaxError: Unexpected token')
expect(data.errorMessage).toBe('Unexpected token')
})

it.each(['/v1/users/42: not found', '/static/app.js: not found'])(
'keeps a thrown message that starts with a path other than the sandbox code file: %s',
async (message) => {
const data = await failRemote(
'javascript',
`import "node:path"\nthrow new TypeError(${JSON.stringify(message)})`,
`TypeError: ${message}`
)
expect(data.errorMessage).toBe(message)
}
)

it('drops the line, code and exception name from a Python error', async () => {
const data = await failRemote(
'python',
Expand Down
9 changes: 6 additions & 3 deletions apps/sim/lib/function-execution/execute-request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -570,10 +570,13 @@ function extractEnhancedError(
}

/**
* A leading absolute file path a sandbox puts before a JavaScript error's message
* (`/home/user/index.js: Unexpected token`).
* The path of the code file a remote sandbox runs (`.sim-function-<id>.mjs`, under its working
* directory), which a JavaScript error puts before its message
* (`/home/user/.sim-function-abc.mjs: Unexpected token`). Matched by that name alone, so a thrown
* message that starts with any other path (`/static/app.js: not found`) stays intact.
*/
const SANDBOX_FILE_PATH_PREFIX = /^(?:file:\/\/)?\/\S*:\s*/
const SANDBOX_FILE_PATH_PREFIX =
/^(?:file:\/\/)?(?:\S*\/)?\.sim-function-[\w-]+\.(?:mjs|cjs|py):\s*/

/**
* The type label a sandbox error leads with, when a message follows: `ValueError: invalid phone`,
Expand Down
9 changes: 4 additions & 5 deletions apps/sim/lib/internal/confluence/operations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ import { docNotReadyMessage, isDocNotReadyError } from '@/lib/uploads/utils/doc-
import { processSingleFileToUserFile, type RawFileInput } from '@/lib/uploads/utils/file'
import { downloadServableFileFromStorage } from '@/lib/uploads/utils/file.server'
import { assertToolFileAccess } from '@/app/api/files/authorization'
import { cleanHtmlContent } from '@/tools/confluence/utils'
import { cleanHtmlContent, isNumericConfluenceSpaceId } from '@/tools/confluence/utils'
import { parseAtlassianErrorMessage } from '@/tools/jira/utils'

const logger = createLogger('ConfluenceOperations')
Expand Down Expand Up @@ -130,7 +130,6 @@ function mappedLabels(value: unknown): JsonObject[] {
})
}

const NUMERIC_SPACE_ID_PATTERN = /^[1-9][0-9]{0,19}$/
const SPACE_STATUSES = ['current', 'archived'] as const

function normalizedConfluenceSpaceKey(value: string): string {
Expand Down Expand Up @@ -163,14 +162,14 @@ async function resolveConfluenceSpaceId(
signal?: AbortSignal
): Promise<string> {
const spaceIdentifier = value.trim()
if (NUMERIC_SPACE_ID_PATTERN.test(spaceIdentifier)) return spaceIdentifier
if (isNumericConfluenceSpaceId(spaceIdentifier)) return spaceIdentifier

const spaceKey = normalizedConfluenceSpaceKey(spaceIdentifier)
const space = await findConfluenceSpaceByKey(client, spaceKey, signal)
const resolvedId = space?.id
if (
(typeof resolvedId !== 'string' && typeof resolvedId !== 'number') ||
!NUMERIC_SPACE_ID_PATTERN.test(String(resolvedId))
!isNumericConfluenceSpaceId(String(resolvedId))
) {
throw new ConfluenceOperationError(`Confluence space key "${spaceKey}" was not found`, 404)
}
Expand All @@ -183,7 +182,7 @@ async function resolveConfluenceSpaceKey(
signal?: AbortSignal
): Promise<string> {
const spaceIdentifier = normalizedConfluenceSpaceKey(value)
if (!NUMERIC_SPACE_ID_PATTERN.test(spaceIdentifier)) return spaceIdentifier
if (!isNumericConfluenceSpaceId(spaceIdentifier)) return spaceIdentifier

const space = await client.json(client.apiV2(`/spaces/${spaceIdentifier}`), {}, signal)
if (typeof space.key !== 'string' || !space.key) {
Expand Down
2 changes: 1 addition & 1 deletion apps/sim/scripts/test-markdown-viewer-e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -624,7 +624,7 @@ async function provePastePersistence(page: Page, browserName: string) {
try {
// Leave the file before deleting it, or the open editor refetches it and the next check on
// this page records that 404 as its own. A failed proof keeps the page for its screenshot.
if (proved) await page.goto('about:blank')
if (proved) await page.goto('about:blank').catch(() => undefined)
await request(`/api/workspaces/${workspaceId}/files/${pastedFileId}`, undefined, 'DELETE')
} finally {
await sql`delete from public_share where id=${pastedShareId}`
Expand Down
3 changes: 2 additions & 1 deletion apps/sim/tools/confluence/create_page.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { CONTENT_BODY_OUTPUT_PROPERTIES, VERSION_OUTPUT_PROPERTIES } from '@/tools/confluence/types'
import { isNumericConfluenceSpaceId } from '@/tools/confluence/utils'
import { dryRunId } from '@/tools/dry-run'
import type { InternalToolConfig } from '@/tools/types'

Expand Down Expand Up @@ -113,7 +114,7 @@ export const confluenceCreatePageTool: InternalToolConfig<
pageId: dryRunId('page'),
title: params.title,
status: 'current',
...(/^\d+$/.test(spaceId) ? { spaceId } : {}),
...(isNumericConfluenceSpaceId(spaceId) ? { spaceId } : {}),
...(params.parentId ? { parentId: params.parentId } : {}),
}
},
Expand Down
7 changes: 7 additions & 0 deletions apps/sim/tools/confluence/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,3 +98,10 @@ export function transformPageData(data: any) {
},
}
}

const NUMERIC_SPACE_ID_PATTERN = /^[1-9][0-9]{0,19}$/

/** Whether a space identifier is a Confluence numeric space id rather than a space key. */
export function isNumericConfluenceSpaceId(spaceIdentifier: string): boolean {
return NUMERIC_SPACE_ID_PATTERN.test(spaceIdentifier)
}
54 changes: 47 additions & 7 deletions apps/sim/tools/dry-run.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { knowledgeUpsertDocumentTool } from '@/tools/knowledge/upsert_document'
import { resendSendTool } from '@/tools/resend/send'
import { answerUnsentCall, describeToolRequest, unsentWriteFor } from '@/tools/side-effects'
import { slackMessageTool } from '@/tools/slack/message'
import { telegramMessageTool } from '@/tools/telegram/message'
import type { ExecutableToolConfig } from '@/tools/types'

vi.unmock('@/tools/metadata-outputs')
Expand All @@ -28,6 +29,7 @@ const TOOLS = new Map<string, ExecutableToolConfig>(
knowledgeUpsertDocumentTool,
resendSendTool,
slackMessageTool,
telegramMessageTool,
].map((tool) => [tool.id, tool])
)

Expand Down Expand Up @@ -137,28 +139,24 @@ describe('a dry run’s placeholder for an unsent write', () => {
toolId: 'hubspot_update_deal',
params: { accessToken: SECRET, dealId: 'deal-key', idProperty: 'deal_key', properties: {} },
read: (returned: Record<string, unknown>) => returned.dealId,
not: 'deal-key',
},
{
case: 'an upsert names the document it replaces as previous, never as its own',
toolId: 'knowledge_upsert_document',
params: { knowledgeBaseId: 'kb1', name: 'Runbook', content: 'steps', documentId: 'doc-old' },
read: (returned: Record<string, unknown>) => toRecord(returned.data).documentId,
not: 'doc-old',
},
{
case: 'a Slack DM reports the channel Slack opens, not the user it names',
toolId: 'slack_message',
params: { accessToken: SECRET, destinationType: 'dm', dmUserId: 'U123', text: 'hi' },
read: (returned: Record<string, unknown>) => returned.channel,
not: 'U123',
},
{
case: 'Slack text that Slack returns escaped is not echoed as sent',
toolId: 'slack_message',
params: { accessToken: SECRET, channel: 'C1', text: 'Q&A <today>' },
read: (returned: Record<string, unknown>) => toRecord(returned.message).text,
not: 'Q&A <today>',
},
{
case: 'a Confluence page created in a space named by key reports the id Confluence resolves',
Expand All @@ -171,12 +169,54 @@ describe('a dry run’s placeholder for an unsent write', () => {
content: '<p>x</p>',
},
read: (returned: Record<string, unknown>) => returned.spaceId,
not: 'ENG',
},
])('$case', async ({ toolId, params, read, not }) => {
{
case: 'a zero-padded Confluence space id is a key Confluence resolves, not an id it echoes',
toolId: 'confluence_create_page',
params: {
accessToken: SECRET,
domain: 'acme.atlassian.net',
spaceId: '007',
title: 'Notes',
content: '<p>x</p>',
},
read: (returned: Record<string, unknown>) => returned.spaceId,
},
])('$case', async ({ toolId, params, read }) => {
const returned = await placeholderFor(toolId, params)

expect(read(returned)).not.toBe(not)
expect(read(returned)).toEqual(expect.stringMatching(/^dry_run_/))
})

it.each([
{
toolId: 'knowledge_upsert_document',
params: { knowledgeBaseId: 'kb1', name: 'Runbook', content: 'steps' },
repeats: (r: Record<string, unknown>) => ({ data: { documentId: r.documentId } }),
},
{
toolId: 'slack_message',
params: { accessToken: SECRET, channel: 'C1', text: 'hi' },
repeats: (r: Record<string, unknown>) => ({ message: { ts: r.ts, channel: r.channel } }),
},
])(
'$toolId reports one placeholder id wherever its output repeats it',
async ({ toolId, params, repeats }) => {
const returned = await placeholderFor(toolId, params)

expect(JSON.stringify(repeats(returned))).toMatch(/dry_run_/)
expect(returned).toMatchObject(repeats(returned))
}
)

it('echoes the chat a Telegram message names by a numeric id given as a number', async () => {
const returned = await placeholderFor('telegram_message', {
botToken: SECRET,
chatId: -1001234,
text: 'hi',
})

expect(returned).toMatchObject({ data: { chat: { id: -1001234 } } })
})

it('samples a file list a placeholder cannot hold as empty', async () => {
Expand Down
Loading
Loading