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
98 changes: 98 additions & 0 deletions browser_tests/tests/agent/agentRunModePopover.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,4 +196,102 @@ test.describe('Agent run permissions popover', { tag: '@cloud' }, () => {
expect(savedModes).toEqual(['auto', 'auto'])
})
})

// PM-1660/PM-1661, reproduced from the reporter's recording: the POST that
// carries the message waits on the cloud-workflow refresh first. The server
// pins a turn's run mode when that POST arrives, so a mode written inside
// that window re-authorized a turn sent under the previous mode.
test('a mode picked while a message is still in flight is saved after it', async ({
agentPanel,
comfyPage
}) => {
const page = comfyPage.page
const reachedServer: string[] = []
let holdTheSend = false
let releaseTheSend: () => void = () => {}
const sendHeld = new Promise<void>((resolve) => {
releaseTheSend = resolve
})

// Both halves of the send are held. Holding the workflow refresh alone
// would not be enough: prepareWorkflow() abandons it after
// PREPARE_TIMEOUT_MS and issues the POST anyway, which then waits here.
await page.route('**/api/workflows?*', async (route) => {
if (holdTheSend) await sendHeld
await route.fallback()
})
await page.route('**/api/agent/threads/*/messages', async (route) => {
if (route.request().method() !== 'POST') return route.fallback()
// Recorded where the POST is FORWARDED, not where it is intercepted.
// Recording on interception would let a PUT that overtook a still-held
// POST still read back as ['message', 'run-mode'] and pass.
if (holdTheSend) await sendHeld
await route.fallback()
reachedServer.push('message')
})
await page.route('**/api/agent/run-mode', async (route) => {
const request = route.request()
// ask_approval, which is also agentRunModeStore's own default, so the
// starting mode does not depend on this route winning a race.
// DockedAgentPanel fires load() on setup, and asserting a mode only this
// mock can produce was right about one attempt in four: it failed the
// initial run and two retries in CI and was reported 'flaky' only
// because a fourth attempt passed.
if (request.method() !== 'PUT')
return route.fulfill(
jsonRoute({
mode: 'ask_approval',
credit_limit: null
} satisfies AgentRunModePreference)
)
reachedServer.push('run-mode')
return route.fulfill(
jsonRoute(zAgentRunMode.parse(request.postDataJSON()))
)
})

await agentPanel.open()
await agentPanel.selectWorkflow()
const panel = agentPanel.root
const askTrigger = panel.getByRole('button', {
name: enMessages.agent.runModeTriggerAsk,
exact: true
})
const autoTrigger = panel.getByRole('button', {
name: enMessages.agent.runModeTriggerAuto,
exact: true
})
await expect(askTrigger).toBeVisible()

holdTheSend = true
await agentPanel.sendMessage('run the wf')

// Picked in the ESCALATING direction: the turn was sent under
// ask_approval, so a PUT that overtook it would let an already-sent turn
// run without a consent card.
await test.step('switching mode now does not overtake the message', async () => {
await askTrigger.click()
await page
.getByRole('menuitemradio', {
name: new RegExp(enMessages.agent.runModeAuto)
})
.click()

// A cheap sanity guard, not the regression detector: reachedServer is
// pushed from a Node-side route handler, which the DOM assertion above
// it does not order against. The detector is the final assertion.
// Nothing at all should have been forwarded while the send is held.
await expect(
page.getByRole('menuitemradio', {
name: new RegExp(enMessages.agent.runModeAuto)
})
).toHaveAttribute('aria-busy', 'true')
expect(reachedServer).toEqual([])

releaseTheSend()
await expect(autoTrigger).toBeVisible()
// The load-bearing assertion: the write landed, and it landed second.
await expect.poll(() => reachedServer).toEqual(['message', 'run-mode'])
})
})
})
14 changes: 9 additions & 5 deletions src/scripts/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ import {
fetchWithUnifiedRemint,
shouldRemintCloudRequest
} from '@/platform/auth/unified/remintRetry'
import {
AUTH_INIT_TIMEOUT_MS,
FETCH_RESPONSE_HEADERS_TIMEOUT_MS
} from '@/scripts/apiTimeouts'
import { getDevOverride } from '@/utils/devFeatureFlagOverride'
import { getSessionOverride } from '@/utils/sessionFeatureFlagOverride'
import type {
Expand Down Expand Up @@ -143,8 +147,6 @@ interface QueuePromptRequestBody {
number?: number
}

const FETCH_RESPONSE_HEADERS_TIMEOUT_MS = 60_000

/**
* Which cloud auth path a request actually took, for error diagnostics (PM-1802).
*
Expand Down Expand Up @@ -636,7 +638,7 @@ export class ComfyApi extends EventTarget {

/**
* Waits for Firebase auth to be initialized before proceeding.
* Includes 10-second timeout to prevent infinite hanging.
* Bounded by AUTH_INIT_TIMEOUT_MS to prevent infinite hanging.
*/
private async waitForAuthInitialization(): Promise<void> {
if (isCloud) {
Expand All @@ -649,10 +651,12 @@ export class ComfyApi extends EventTarget {
try {
await Promise.race([
until(isInitialized).toBe(true),
promiseTimeout(10000)
promiseTimeout(AUTH_INIT_TIMEOUT_MS)
])
} catch {
console.warn('Firebase auth initialization timeout after 10 seconds')
console.warn(
`Firebase auth initialization timeout after ${AUTH_INIT_TIMEOUT_MS / 1000} seconds`
)
}
}
}
Expand Down
22 changes: 22 additions & 0 deletions src/scripts/apiTimeouts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* The request bounds `api.fetchApi` enforces, in their own leaf module so that
* a caller which must OUTLAST a request can derive its bound from the same
* numbers instead of restating them.
*
* Deliberately not exported from `api.ts`: `src/scripts/__mocks__/api.ts` is
* the manual mock every `vi.mock('@/scripts/api')` resolves to, and it exports
* only `api` — so a constant read through that path arrives `undefined` and any
* arithmetic on it silently becomes `NaN`. A `setTimeout` armed with `NaN`
* fires immediately, which is exactly the failure a derived timeout must not
* have. Importing from here keeps the real values under a mocked `api`.
*/

/** Ceiling on `ComfyApi.waitForAuthInitialization`, spent before the response timer below is armed. */
export const AUTH_INIT_TIMEOUT_MS = 10_000

/**
* Response-HEADERS timeout for one `fetchApi` attempt — not the body. A 401
* remint clears this timer and arms a fresh one for the retry, so a single
* cloud request can spend it twice (`fetchWithUnifiedRemint`).
*/
export const FETCH_RESPONSE_HEADERS_TIMEOUT_MS = 60_000
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ import type {
PostMessageInput
} from '../../services/agent/agentRestClient'
import { useAgentConversationStore } from '../../stores/agent/agentConversationStore'
import { useAgentSendGateStore } from '../../stores/agent/agentSendGateStore'
import { useAgentWorkflowTabBindingStore } from '../../stores/agent/agentWorkflowTabBindingStore'

import type { SelectedNode } from './useCanvasSelection'
Expand Down Expand Up @@ -5367,6 +5368,50 @@ describe('useAgentSession (v1 composition root)', () => {
])
expect(session.notices.value).toHaveLength(0)
})

// PM-1660: the gate has to be taken in sendMessage, before performSend
// awaits prepareWorkflow(), and released however the POST settles. Without
// these two cases the wiring can be removed or moved into the success branch
// with every agent unit suite still green — only the @cloud spec notices,
// and only on the success path.
it.for([
['resolves', (resolve: () => void) => resolve()],
['rejects', (_resolve: () => void, reject: () => void) => reject()]
] as const)(
'holds the send gate from send until the POST %s, across New Chat',
async ([, settlePost]) => {
let settle: () => void = () => {}
const postMessage = vi.fn(
() =>
new Promise<AgentTurnAccepted>((resolve, reject) => {
settle = () =>
settlePost(
() =>
resolve({
thread_id: 'th-1',
message_id: 'msg-1',
workflow_id: 'wf-1'
}),
() => reject(new Error('post failed'))
)
})
)
const rest = fakeRest({ postMessage })
const session = useAgentSession({ rest, events: fakeEvents().source })
session.start()
const gate = useAgentSendGateStore()

const sent = session.sendMessage('go')
await vi.waitFor(() => expect(postMessage).toHaveBeenCalled())
session.newChat('new_chat_button')

expect(gate.isSending).toBe(true)
settle()
await sent

expect(gate.isSending).toBe(false)
}
)
})

describe('thread resume (B17)', () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ import type { AssistantMessage } from '../../services/agent/agentMessageParts'
import { normalizeAgentTranscript } from '../../services/agent/agentTranscript'
import type { LiveTurn } from '../../stores/agent/agentConversationStore'
import { useAgentConversationStore } from '../../stores/agent/agentConversationStore'
import { useAgentSendGateStore } from '../../stores/agent/agentSendGateStore'
import { useAgentWorkflowTabBindingStore } from '../../stores/agent/agentWorkflowTabBindingStore'
import type { WorkflowReference } from '../../types/workflowReference'
import { serializeWorkflowReferences } from '../../utils/workflowReferenceText'
Expand Down Expand Up @@ -374,6 +375,7 @@ export function useAgentSession(deps: AgentSessionDeps) {
clearLegacyAgentStorage()

const conversationStore = useAgentConversationStore()
const sendGateStore = useAgentSendGateStore()
const bindingStore = useAgentWorkflowTabBindingStore()
/**
* The workflow the session is bound to (set on turn ack or an active-tab
Expand Down Expand Up @@ -1152,6 +1154,7 @@ export function useAgentSession(deps: AgentSessionDeps) {
}
promptEditState.value = { phase: 'idle' }
sending.value = true
const releaseSendGate = sendGateStore.begin()
sendInFlight = true
stopPendingAck = null
try {
Expand All @@ -1165,6 +1168,7 @@ export function useAgentSession(deps: AgentSessionDeps) {
)
} finally {
sending.value = false
releaseSendGate()
sendInFlight = false
}
}
Expand Down
Loading
Loading