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
2 changes: 2 additions & 0 deletions src/workbench/extensions/agent/AgentPanelRoot.vue
Original file line number Diff line number Diff line change
Expand Up @@ -179,6 +179,7 @@ const workflowResolver = useAgentWorkflowResolver({
})
const {
refreshCloudWorkflowIds,
forgetCloudWorkflowId,
cloudIdFor,
boundOrOpenWorkflowFor,
storedWorkflowFor,
Expand Down Expand Up @@ -571,6 +572,7 @@ const {
prepare: async () => {
await refreshCloudWorkflowIds()
},
disowned: forgetCloudWorkflowId,
tabs: openTabsSnapshot,
activeTab: enqueueActiveTab,
draft: targetWorkflowDraft
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<AgentRestClient['postMessage']>()
.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(
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
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<AgentRestClient['postMessage']>(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<AgentRestClient['postMessage']>(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<
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import {
isAgentEvent,
parseAgentWsEvent,
toTurnId,
zAgentAdmissionError
zAgentAdmissionError,
zDisownedWorkflowError
} from '../../schemas/agentApiSchema'
import { AgentApiError } from '../../services/agent/agentRestClient'
import type {
Expand Down Expand Up @@ -81,6 +82,8 @@ export interface AgentSessionDeps {
isCurrent: () => boolean
): Promise<void> | void
prepare?(): Promise<void>
/** 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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
bindingStore.unbindWorkflow(sent.id)
workflow?.disowned?.(sent.id)
if (boundWorkflowId.value === sent.id) boundWorkflowId.value = null
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
if (rememberedWorkflowId === sent.id) rememberedWorkflowId = null
}

async function performSend(
text: string,
attachments?: SentAttachment[],
Expand All @@ -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
Expand All @@ -407,6 +441,7 @@ export function useAgentSession(deps: AgentSessionDeps) {
recordUnavailableTarget(text)
return false
}
sentContext = wfContext
const ack = await postTurn(
threadAtSend,
text,
Expand All @@ -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)
Comment thread
claude[bot] marked this conversation as resolved.
Resolved
if (generation !== loadGeneration) return false
recordSendError(error, text)
return false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down Expand Up @@ -203,6 +213,7 @@ export function useAgentWorkflowResolver({

return {
refreshCloudWorkflowIds,
forgetCloudWorkflowId,
cloudIdFor,
cloudWorkflowName,
boundOrOpenWorkflowFor,
Expand Down
10 changes: 10 additions & 0 deletions src/workbench/extensions/agent/schemas/agentApiSchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -222,6 +234,13 @@ export const useAgentWorkflowTabBindingStore = defineStore(
: undefined
}

return { bind, unbind, matchesWorkflow, tabPathFor, workflowIdFor }
return {
bind,
unbind,
unbindWorkflow,
matchesWorkflow,
tabPathFor,
workflowIdFor
}
}
)
Loading