diff --git a/src/workbench/extensions/agent/AgentPanelRoot.vue b/src/workbench/extensions/agent/AgentPanelRoot.vue index c5a76a49598..67d9e4a5905 100644 --- a/src/workbench/extensions/agent/AgentPanelRoot.vue +++ b/src/workbench/extensions/agent/AgentPanelRoot.vue @@ -179,6 +179,7 @@ const workflowResolver = useAgentWorkflowResolver({ }) const { refreshCloudWorkflowIds, + forgetCloudWorkflowId, cloudIdFor, boundOrOpenWorkflowFor, storedWorkflowFor, @@ -571,6 +572,7 @@ const { prepare: async () => { await refreshCloudWorkflowIds() }, + disowned: forgetCloudWorkflowId, tabs: openTabsSnapshot, activeTab: enqueueActiveTab, draft: targetWorkflowDraft diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts index ea3302ca1a2..da32c82e7a2 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.test.ts @@ -1488,6 +1488,121 @@ describe('useAgentSession (v1 composition root)', () => { expect(session.boundWorkflowId.value).toBeNull() }) + // FE-2501: the tab -> workflow binding is persisted, so a workflow the + // backend refuses to serve poisons its tab for good - every later turn from + // that tab re-posts the same dead id, and a reload re-affirms the binding + // from the thread's own workflow pointer. Only the workflow-scoped refusal + // releases the binding; the thread-scoped one names a different resource. + it.for([ + { refusal: 'workflow not found or access denied', released: true }, + { refusal: 'thread not found or access denied', released: false } + ])('(k2) 403 $refusal releases the binding: $released', async (scenario) => { + const tabPath = 'workflows/portrait.json' + useAgentWorkflowTabBindingStore().bind('wf-dead', tabPath) + const postMessage = vi + .fn() + .mockRejectedValue( + new AgentApiError(scenario.refusal, 403, { error: scenario.refusal }) + ) + const session = useAgentSession({ + rest: fakeRest({ postMessage }), + events: fakeEvents().source, + workflow: { + current: () => ({ id: 'wf-dead', tabPath }), + adopted: vi.fn() + } + }) + session.start() + session.bindWorkflow('wf-dead') + + expect(await session.sendMessage('run it')).toBe(false) + + expect(useAgentWorkflowTabBindingStore().tabPathFor('wf-dead')).toBe( + scenario.released ? undefined : tabPath + ) + expect(session.boundWorkflowId.value).toBe( + scenario.released ? null : 'wf-dead' + ) + expect(session.entries.value.at(-1)).toMatchObject({ + role: 'assistant', + parts: [ + { + type: 'notice', + level: 'error', + text: `Message failed to send: ${scenario.refusal}` + } + ] + }) + }) + + // The refusal names a workflow, so the release must be keyed by that id. + // `agent_active_tab`, reference navigation and commitWorkflowTarget all + // rebind the same tab path mid-flight without bumping the send generation, + // and a path-keyed release would delete whichever binding won that race. + it('(k3) a late refusal does not disturb a binding the tab was rebound to', async () => { + const tabPath = 'workflows/portrait.json' + const bindings = useAgentWorkflowTabBindingStore() + bindings.bind('wf-dead', tabPath) + const postMessage = vi.fn(async () => { + bindings.bind('wf-live', tabPath) + throw new AgentApiError('workflow not found or access denied', 403, { + error: 'workflow not found or access denied' + }) + }) + const session = useAgentSession({ + rest: fakeRest({ postMessage }), + events: fakeEvents().source, + workflow: { + current: () => ({ id: 'wf-dead', tabPath }), + adopted: vi.fn() + } + }) + session.start() + session.bindWorkflow('wf-dead') + + expect(await session.sendMessage('run it')).toBe(false) + + expect(bindings.tabPathFor('wf-dead')).toBeUndefined() + expect(bindings.tabPathFor('wf-live')).toBe(tabPath) + expect(bindings.workflowIdFor(tabPath)).toBe('wf-live') + }) + + // The binding store is page-global and persisted, so it outlives the send + // generation. A refusal that lands after newChat()/loadThread() has moved on + // must still release, or the dead id survives exactly as before the fix. + it('(k4) releases the binding even when the send generation moved on', async () => { + const tabPath = 'workflows/portrait.json' + const bindings = useAgentWorkflowTabBindingStore() + bindings.bind('wf-dead', tabPath) + const disowned = vi.fn() + let abandon: () => void = () => {} + const postMessage = vi.fn(async () => { + abandon() + throw new AgentApiError('workflow not found or access denied', 403, { + error: 'workflow not found or access denied' + }) + }) + const session = useAgentSession({ + rest: fakeRest({ postMessage }), + events: fakeEvents().source, + workflow: { + current: () => ({ id: 'wf-dead', tabPath }), + adopted: vi.fn(), + disowned + } + }) + session.start() + session.bindWorkflow('wf-dead') + abandon = () => void session.newChat() + + expect(await session.sendMessage('run it')).toBe(false) + + expect(bindings.tabPathFor('wf-dead')).toBeUndefined() + // The resolver prefers its name-derived cloud index over the binding + // store, so the refused id has to leave that index too. + expect(disowned).toHaveBeenCalledWith('wf-dead') + }) + it('(k) a failed POST records the user text plus a settled error reply and returns false', async () => { const postMessage = vi .fn< diff --git a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts index ee0d2a806bb..3f2d8764156 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentSession.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentSession.ts @@ -12,7 +12,8 @@ import { isAgentEvent, parseAgentWsEvent, toTurnId, - zAgentAdmissionError + zAgentAdmissionError, + zDisownedWorkflowError } from '../../schemas/agentApiSchema' import { AgentApiError } from '../../services/agent/agentRestClient' import type { @@ -81,6 +82,8 @@ export interface AgentSessionDeps { isCurrent: () => boolean ): Promise | void prepare?(): Promise + /** The server refused this workflow id; forget every cached trace of it. */ + disowned?(workflowId: string): void tabs?(origin?: TurnOrigin): OpenTabsSnapshot | undefined activeTab?(data: AgentActiveTabData): void draft?(origin?: TurnOrigin): DraftSnapshot | undefined @@ -109,6 +112,14 @@ function parseAdmissionError(error: unknown) { return { ...parsed.data.error, retryAfterSeconds: error.retryAfterSeconds } } +function disownsWorkflow(error: unknown): boolean { + return ( + error instanceof AgentApiError && + error.status === 403 && + zDisownedWorkflowError.safeParse(error.body).success + ) +} + export function useAgentSession(deps: AgentSessionDeps) { const { rest, events, workflow } = deps @@ -388,6 +399,28 @@ export function useAgentSession(deps: AgentSessionDeps) { ) } + /** + * The server will not serve the id this turn was posted under, and the + * binding that produced it outlives the page. Left in place it poisons the + * tab: every later turn re-posts the same dead id, and a reload re-affirms + * the binding through the thread's own workflow pointer. + * + * Everything here is keyed by the refused id, never by its tab path: the tab + * may already have been rebound to a healthy workflow while the POST was in + * flight. `disowned` evicts the id from the resolver's cloud index, which + * `cloudIdFor` consults ahead of the binding store. + */ + function releaseDisownedWorkflow( + sent: WorkflowTurnContext | undefined, + error: unknown + ): void { + if (sent?.id === undefined || !disownsWorkflow(error)) return + bindingStore.unbindWorkflow(sent.id) + workflow?.disowned?.(sent.id) + if (boundWorkflowId.value === sent.id) boundWorkflowId.value = null + if (rememberedWorkflowId === sent.id) rememberedWorkflowId = null + } + async function performSend( text: string, attachments?: SentAttachment[], @@ -399,6 +432,7 @@ export function useAgentSession(deps: AgentSessionDeps) { const originContext = workflow?.current() const origin: TurnOrigin = originContext === undefined ? null : { tabPath: originContext.tabPath } + let sentContext: WorkflowTurnContext | undefined try { await prepareWorkflow() if (generation !== loadGeneration) return false @@ -407,6 +441,7 @@ export function useAgentSession(deps: AgentSessionDeps) { recordUnavailableTarget(text) return false } + sentContext = wfContext const ack = await postTurn( threadAtSend, text, @@ -420,6 +455,10 @@ export function useAgentSession(deps: AgentSessionDeps) { acceptTurn(ack, text, wfContext, attachments, tags, workflowReferences) return true } catch (error) { + // Before the generation guard: the binding store is page-global and + // persisted, so a refusal that lands after newChat()/loadThread() has + // moved on still has to release, or the dead id survives the reload. + releaseDisownedWorkflow(sentContext, error) if (generation !== loadGeneration) return false recordSendError(error, text) return false diff --git a/src/workbench/extensions/agent/composables/agent/useAgentWorkflowResolver.test.ts b/src/workbench/extensions/agent/composables/agent/useAgentWorkflowResolver.test.ts index 2c62b0461d3..26257f3f7a6 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentWorkflowResolver.test.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentWorkflowResolver.test.ts @@ -292,6 +292,34 @@ describe('Agent workflow resolution', () => { ]) }) + // cloudIdFor reads the name-derived index ahead of the binding store, so + // releasing the binding alone still leaves a refused id resolvable here - + // and refreshCloudWorkflowIds cannot be relied on to drop it, since it + // swallows its errors and the caller races it against a timeout. + it('stops resolving a refused cloud id once it is forgotten', async () => { + const portrait = workflow('workflows/portrait.json', 'Portrait') + const { resolver, bindings } = setup( + [portrait], + [ + { id: 'cloud-portrait', name: 'Portrait' }, + { id: 'cloud-other', name: 'Other' } + ] + ) + await resolver.refreshCloudWorkflowIds() + expect(resolver.cloudIdFor(portrait)).toBe('cloud-portrait') + + bindings.unbindWorkflow('cloud-portrait') + expect(resolver.cloudIdFor(portrait)).toBe('cloud-portrait') + + resolver.forgetCloudWorkflowId('cloud-portrait') + + expect(resolver.cloudIdFor(portrait)).toBeUndefined() + expect(resolver.openTabsSnapshot()).toBeUndefined() + expect(resolver.availableWorkflowReferences.value).toEqual([ + { id: 'cloud-other', name: 'Other' } + ]) + }) + it('rejects a stale binding that points a cloud id at a differently named saved tab', async () => { const portrait = workflow('workflows/portrait.json', 'Portrait') const { resolver, bindings, workflows } = setup( diff --git a/src/workbench/extensions/agent/composables/agent/useAgentWorkflowResolver.ts b/src/workbench/extensions/agent/composables/agent/useAgentWorkflowResolver.ts index fe499222eba..5fd59b2bca0 100644 --- a/src/workbench/extensions/agent/composables/agent/useAgentWorkflowResolver.ts +++ b/src/workbench/extensions/agent/composables/agent/useAgentWorkflowResolver.ts @@ -62,6 +62,16 @@ export function useAgentWorkflowResolver({ } } + /** + * Drops a workflow the server has refused. `cloudIdFor` reads this index + * ahead of the binding store, and `refreshCloudWorkflowIds` both swallows + * its errors and races a timeout, so a stale entry would keep handing the + * refused id back to the next turn however often the binding is released. + */ + function forgetCloudWorkflowId(workflowId: string): void { + cloudIndex.value = cloudIndex.value.filter(({ id }) => id !== workflowId) + } + function cloudWorkflowName(workflow: ComfyWorkflow): string { return workflow.suffix === 'app.json' ? `${workflow.filename}.app` @@ -203,6 +213,7 @@ export function useAgentWorkflowResolver({ return { refreshCloudWorkflowIds, + forgetCloudWorkflowId, cloudIdFor, cloudWorkflowName, boundOrOpenWorkflowFor, diff --git a/src/workbench/extensions/agent/schemas/agentApiSchema.ts b/src/workbench/extensions/agent/schemas/agentApiSchema.ts index b414dcd438e..5cbd8db6f42 100644 --- a/src/workbench/extensions/agent/schemas/agentApiSchema.ts +++ b/src/workbench/extensions/agent/schemas/agentApiSchema.ts @@ -118,6 +118,16 @@ export type CloudWorkflowEntry = z.infer< export const zAgentError = z.union([zGeneratedAgentError, zAgentAdmissionError]) +/** + * The 403 body the agent service returns when it will not serve the turn's + * `workflow_id` to the caller's workspace, whether the row is gone or belongs + * elsewhere. The message is the only discriminator on the wire: a 403 refusing + * the thread or the message carries the same shape with a different subject. + */ +export const zDisownedWorkflowError = z.object({ + error: z.literal('workflow not found or access denied') +}) + export const zUploadImageResult = z.object({ name: z.string(), subfolder: z.string(), diff --git a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.test.ts b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.test.ts index b50c61c9761..d3858e1b0eb 100644 --- a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.test.ts +++ b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.test.ts @@ -392,6 +392,23 @@ describe('agentWorkflowTabBindingStore', () => { }) }) + it('unbindWorkflow drops only the named workflow, wherever it now sits', () => { + const store = useAgentWorkflowTabBindingStore() + store.bind('wf-1', 'workflows/a.json') + store.bind('wf-2', 'workflows/b.json') + + store.bind('wf-3', 'workflows/a.json') + store.unbindWorkflow('wf-1') + + expect(store.tabPathFor('wf-3')).toBe('workflows/a.json') + expect(store.workflowIdFor('workflows/a.json')).toBe('wf-3') + expect(store.tabPathFor('wf-2')).toBe('workflows/b.json') + expect(store.tabPathFor('wf-1')).toBeUndefined() + + store.unbindWorkflow('wf-unknown') + expect(store.tabPathFor('wf-3')).toBe('workflows/a.json') + }) + it('resolves both directions after a bind', () => { const store = useAgentWorkflowTabBindingStore() store.bind('wf-1', 'workflows/a.json') diff --git a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.ts b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.ts index df8da4a0684..9834b23dda6 100644 --- a/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.ts +++ b/src/workbench/extensions/agent/stores/agent/agentWorkflowTabBindingStore.ts @@ -152,6 +152,18 @@ export const useAgentWorkflowTabBindingStore = defineStore( } } + /** + * Drops one workflow's record wherever it sits. Path-keyed `unbind` would + * take whichever workflow occupies the path now, which is the wrong one + * once the tab has been rebound. + */ + function unbindWorkflow(workflowId: string): void { + if (!Object.hasOwn(tabByWorkflow.value, workflowId)) return + delete tabByWorkflow.value[workflowId] + boundInstances.delete(workflowId) + refusedInstances.delete(workflowId) + } + function releaseClosedTab({ tab, path }: OpenTab): void { const workflowId = recordIdFor(path) if (workflowId === undefined) return @@ -222,6 +234,13 @@ export const useAgentWorkflowTabBindingStore = defineStore( : undefined } - return { bind, unbind, matchesWorkflow, tabPathFor, workflowIdFor } + return { + bind, + unbind, + unbindWorkflow, + matchesWorkflow, + tabPathFor, + workflowIdFor + } } )