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
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,16 @@ params but leaves `workflowId` and its stash. A navigation guard can hold a
newer link in the stash while the URL still shows the old one. While the URL
and the stash name different links, the loader treats the stash as a navigation
still in flight: it makes no replace and clears neither carrier, even for a
link it already opened. An empty `?workflowId=` clears the stash when the
router captures it, so an older stashed link cannot keep the empty one from
being rejected as invalid. While the stash holds a link the loader never started
and the URL does not show, the sweep makes no replace either, so that link's
navigation is not cancelled.
link it already opened. Two different malformed values are different links;
only the forms the stash records for one URL value (a repeated value joined
with `,`, a bare `?workflowId` or an empty `?workflowId=` as `,`) count as the
same link. The router records an empty `?workflowId=` as `,` in place of any
older stashed link rather than clearing the stash: an older link cannot keep
the empty one from being rejected as invalid, and while a guard holds the empty
link, an earlier lookup still sees a newer link in flight and its cleanup
cannot cancel that navigation. While the stash holds a link the loader never
started and the URL does not show, the sweep makes no replace either, so that
link's navigation is not cancelled.

The reply and the 409 body are validated with the generated
`@comfyorg/ingest-types` schemas. The spec types the 409 as `ErrorResponse` and
Expand All @@ -55,8 +60,11 @@ loader keeps its list of known reasons as a telemetry classification and
records any other value as `unknown`.

Error reports for the link carry a fixed message, the error type and the
failing error's class name. They never carry the caught error or its message:
a failed file read names the file, and a parser error quotes the reply.
failing error's class name when it is a built-in JavaScript error class, or
`other` for any other name or a name that cannot be read. They never carry the
caught error, its message or a name it chose: a failed file read names the
file, a parser error quotes the reply, and custom node code that runs while the
workflow loads can throw an error under any name.

## Alternatives considered

Expand Down
110 changes: 110 additions & 0 deletions src/composables/useWorkflowLinkUrlLoader.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -537,6 +537,49 @@ describe('workflow-id links', () => {
reported: new Error('Could not read workflow link'),
errorType: 'error_loading_workflow_link',
errorName: 'SyntaxError'
},
{
name: 'custom node code throws an error under its own name',
fail: () => {
serveFile()
const thrown = new Error('Widget size failed')
thrown.name = 'Customer Jane Doe'
vi.mocked(useWorkflowService().openWorkflow).mockRejectedValue(thrown)
},
reported: new Error('Could not open workflow link'),
errorType: 'error_opening_workflow_link',
errorName: 'other'
},
{
name: 'custom node code throws an error whose name changes between reads',
fail: () => {
serveFile()
const thrown = new Error('Widget size failed')
const names = ['Error', 'Customer Jane Doe']
Object.defineProperty(thrown, 'name', {
get: () => names.shift() ?? 'Customer Jane Doe'
})
vi.mocked(useWorkflowService().openWorkflow).mockRejectedValue(thrown)
},
reported: new Error('Could not open workflow link'),
errorType: 'error_opening_workflow_link',
errorName: 'Error'
},
{
name: 'an error name cannot be read',
fail: () => {
serveFile()
const thrown = new Error('Widget size failed')
Object.defineProperty(thrown, 'name', {
get: () => {
throw new Error('Customer Jane Doe')
}
})
vi.mocked(useWorkflowService().openWorkflow).mockRejectedValue(thrown)
},
reported: new Error('Could not open workflow link'),
errorType: 'error_opening_workflow_link',
errorName: 'other'
}
])(
'reports that $name without the file name or the error text',
Expand Down Expand Up @@ -666,6 +709,73 @@ describe('workflow-id links', () => {
expect(currentQuery()).toEqual({ workflowId: NEXT_ID })
})

it('leaves a newer malformed link a navigation guard holds while an older malformed link is rejected', async () => {
const request = vi.spyOn(api, 'fetchApi')
await navigate({ workflowId: 'bad1' })
const signIn = holdNavigation((to) => to.query.workflowId === 'bad2')
const newerLink = navigate({ workflowId: 'bad2', topup: '1' })
await signIn.arrived

expect(await loader.openWorkflowLinkFromUrl(true)).toBe('pending')

expect(request).not.toHaveBeenCalled()
expect(currentQuery()).toEqual({ workflowId: 'bad1' })
expect(getPreservedQueryParam(NAMESPACE, 'workflowId')).toBe('bad2')
signIn.release()
await newerLink
expect(currentQuery()).toEqual({ workflowId: 'bad2', topup: '1' })
})

it('leaves a newer empty link a navigation guard holds after a newer guard-held link superseded the lookup', async () => {
const respond = holdLookup()
await navigate({ workflowId: ID })
vi.mocked(useWorkflowService().openWorkflow).mockResolvedValue(true)
const newerHold = holdNavigation(isNewerLink)
const emptyHold = holdNavigation((to) => to.query.workflowId === '')

const attempt = loader.openWorkflowLinkFromUrl()
const newerLink = navigate({ workflowId: NEXT_ID })
await newerHold.arrived
const emptyLink = navigate({ workflowId: '', topup: '1' })
await emptyHold.arrived
respond()

expect(await attempt).toBe('pending')
expect(useWorkflowService().openWorkflow).not.toHaveBeenCalled()
expect(useTelemetry()?.trackWorkflowLinkOpened).not.toHaveBeenCalled()
newerHold.release()
emptyHold.release()
await Promise.all([newerLink, emptyLink])
expect(currentQuery()).toEqual({ workflowId: '', topup: '1' })

expect(await loader.openWorkflowLinkFromUrl(true)).toBe('failed')

expect(currentQuery()).toEqual({ topup: '1' })
expect(getPreservedQueryParam(NAMESPACE, 'workflowId')).toBeUndefined()
expect(loader.hasLinkInFlight()).toBe(false)
})

it('reports an empty link once when another navigation cancels its URL cleanup, and clears it later', async () => {
await navigate({ workflowId: '' })
const cleanup = holdNavigation((to) => isUrlCleanup(to) && !to.query.keep)

const attempt = loader.openWorkflowLinkFromUrl(true)
await cleanup.arrived
await navigate({ keep: 'yes' })
cleanup.release()

expect(await attempt).toBe('failed')
expect(getPreservedQueryParam(NAMESPACE, 'workflowId')).toBe(',')
expect(loader.hasLinkInFlight()).toBe(false)

expect(await loader.openWorkflowLinkFromUrl(true)).toBe('failed')

expect(currentQuery()).toEqual({ keep: 'yes' })
expect(getPreservedQueryParam(NAMESPACE, 'workflowId')).toBeUndefined()
expect(useToast().toasts).toHaveLength(1)
expect(useTelemetry()?.trackWorkflowLinkOpened).toHaveBeenCalledTimes(1)
})

it('keeps a boot link opened when another navigation cancels its URL cleanup, and clears it later without reopening', async () => {
serveFile()
await navigate({ workflowId: ID })
Expand Down
41 changes: 33 additions & 8 deletions src/composables/useWorkflowLinkUrlLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,15 +58,36 @@ function isWorkflowId(value: unknown): value is string {
return typeof value === 'string' && workflowIdSchema.safeParse(value).success
}

function linkIdentity(value: unknown): unknown {
if (value === null || value === '') return ','
if (!Array.isArray(value)) return value
if (value.length === 1) return linkIdentity(value[0])
return value.map((entry: unknown) => entry ?? '').join(',')
}

function isSameLink(carried: unknown, workflowId: unknown): boolean {
return (
carried === workflowId ||
(!isWorkflowId(carried) && !isWorkflowId(workflowId))
)
return linkIdentity(carried) === linkIdentity(workflowId)
}

const BUILT_IN_ERROR_NAMES: ReadonlySet<string> = new Set([
'Error',
'TypeError',
'RangeError',
'SyntaxError',
'ReferenceError',
'EvalError',
'URIError',
'AggregateError'
])

function failureContext(cause: unknown) {
return { error_name: cause instanceof Error ? cause.name : typeof cause }
try {
if (!(cause instanceof Error)) return { error_name: typeof cause }
const name = cause.name
return { error_name: BUILT_IN_ERROR_NAMES.has(name) ? name : 'other' }
} catch {
return { error_name: 'other' }
}
}

function isWorkflowPath(path: string): boolean {
Expand Down Expand Up @@ -299,7 +320,7 @@ function useWorkflowLinkUrlLoaderInternal() {
function completedStatus(value: unknown, workspaceId: string | null) {
if (
!completed ||
completed.value !== value ||
!isSameLink(completed.value, value) ||
completed.workspaceId !== workspaceId
)
return undefined
Expand All @@ -320,7 +341,7 @@ function useWorkflowLinkUrlLoaderInternal() {
workflowId: unknown,
workspaceId: string | null
): Promise<WorkflowLinkLoadStatus> {
startedLinks.add(workflowId)
startedLinks.add(linkIdentity(workflowId))
const ownership = attemptOwnership(workflowId, workspaceId)
const priorStatus = completedStatus(workflowId, workspaceId)
if (priorStatus) {
Expand All @@ -345,7 +366,11 @@ function useWorkflowLinkUrlLoaderInternal() {

function hasLinkInFlight(): boolean {
const { route, stash } = linkCarriers()
return stash !== undefined && stash !== route && !startedLinks.has(stash)
return (
stash !== undefined &&
!isSameLink(stash, route) &&
!startedLinks.has(linkIdentity(stash))
)
}

return { openWorkflowLinkFromUrl, isLinkSettled, hasLinkInFlight }
Expand Down
3 changes: 2 additions & 1 deletion src/platform/navigation/preservedQueryDefinitions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ export const PRESERVED_QUERY_DEFINITIONS: PreservedQueryDefinition[] = [
{
namespace: PRESERVED_QUERY_NAMESPACES.WORKFLOW_ID,
keys: ['workflowId'],
rejectRepeated: true
rejectRepeated: true,
markEmpty: true
},
{
namespace: PRESERVED_QUERY_NAMESPACES.TEMPLATE,
Expand Down
15 changes: 15 additions & 0 deletions src/platform/navigation/preservedQueryTracker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -298,6 +298,21 @@ describe('installPreservedQueryTracker', () => {
).toBeUndefined()
})

it('stashes an empty markEmpty value as a bare comma in place of a stale value', async () => {
const router = createTestRouter()
installPreservedQueryTracker(router, [
{ ...rejectRepeatedDefinition, markEmpty: true }
])

await router.push('/?workspace=ws-team')
await router.push('/?workspace=')

expect(router.currentRoute.value.fullPath).toBe('/?workspace=')
expect(getPreservedQueryParam(REJECT_REPEATED_NAMESPACE, 'workspace')).toBe(
','
)
})

it('keeps a plain namespace stash when the URL supplies an empty value', async () => {
const router = createTestRouter()
installPreservedQueryTracker(router, [plainDefinition])
Expand Down
27 changes: 16 additions & 11 deletions src/platform/navigation/preservedQueryTracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,27 +28,25 @@ export interface PreservedQueryDefinition {
* becomes a bare `,`. Both are strings outside any real id's charset, so
* they read back as invalid rather than resolving to one of several
* colliding values or to "absent" (`capturePreservedQuery` itself drops a
* null/empty value as not worth capturing). A key present with an empty
* value (`?key=`) clears the namespace's stash instead, so an older stashed
* value never stands in for the newer, empty one the URL carries.
* null/empty value as not worth capturing).
*/
rejectRepeated?: true
/** With `rejectRepeated`, an empty value (`?key=`) is captured as `,`. */
markEmpty?: true
}

/** Marks each `keys` entry present as a repeated value, or with no value at
* all, with a charset-invalid string capturePreservedQuery would otherwise
* either mis-simplify (repeated → first entry) or drop (null → nothing).
* Leaves every other key untouched. */
function withAmbiguityMarked(
query: LocationQuery,
keys: string[]
keys: string[],
markEmpty: boolean
): LocationQuery {
const result = { ...query }
for (const key of keys) {
const value = result[key]
const values = Array.isArray(value) ? value : [value]
const isRepeated = values.length > 1
const hasBareEntry = values.includes(null)
const hasBareEntry =
values.includes(null) || (markEmpty && values.includes(''))
if (!isRepeated && !hasBareEntry) continue
result[key] = values.map((entry) => entry ?? '').join(',') || ','
}
Expand All @@ -68,7 +66,14 @@ export const installPreservedQueryTracker = (
const keysToStrip = new Set<string>()

definitions.forEach(
({ namespace, keys, requiredKey, stripAfterCapture, rejectRepeated }) => {
({
namespace,
keys,
requiredKey,
stripAfterCapture,
rejectRepeated,
markEmpty
}) => {
hydratePreservedQuery(namespace)
const presentKeys = keys.filter((key) => queryKeys.has(key))
if (presentKeys.length === 0) return
Expand All @@ -77,7 +82,7 @@ export const installPreservedQueryTracker = (
return
}
const captureQuery = rejectRepeated
? withAmbiguityMarked(to.query, keys)
? withAmbiguityMarked(to.query, keys, markEmpty === true)
: to.query
if (
rejectRepeated &&
Expand Down
Loading