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
19 changes: 17 additions & 2 deletions src/components/graph/GraphCanvas.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -219,7 +219,10 @@ function setRootGraph(graph: LGraph | undefined) {
;(app as unknown as { rootGraph: LGraph | undefined }).rootGraph = graph
}

async function mountGraphCanvas(stubs: Record<string, unknown> = {}) {
async function mountGraphCanvas(
stubs: Record<string, unknown> = {},
errorHandler?: (error: unknown) => void
) {
// Handed to the component rather than left to the active-Pinia fallback, so
// the readiness gates below are set on the instance startup actually reads.
const pinia = getActivePinia()!
Expand All @@ -241,7 +244,8 @@ async function mountGraphCanvas(stubs: Record<string, unknown> = {}) {
pinia,
createI18n({ legacy: false, locale: 'en', missingWarn: false })
],
stubs
stubs,
config: errorHandler ? { errorHandler } : {}
}
} as RenderOptions<typeof GraphCanvas>)

Expand Down Expand Up @@ -273,6 +277,17 @@ describe('GraphCanvas first-run tour wiring', () => {
).toBeGreaterThan(mocks.handleStartupOutcome.mock.invocationCallOrder[0])
})

it('settles tab restoration when startup fails before restoring tabs', async () => {
const failure = new Error('init failed')
mocks.initializeWorkflow.mockRejectedValue(failure)
const errors: unknown[] = []

await mountGraphCanvas({}, (error) => errors.push(error))

expect(errors).toEqual([failure])
expect(useWorkflowStore().tabsRestored).toBe(true)
})

it('offers the tour over a workflow that arrived from the URL', async () => {
await mountGraphCanvas()

Expand Down
1 change: 1 addition & 0 deletions src/components/graph/GraphCanvas.vue
Original file line number Diff line number Diff line change
Expand Up @@ -636,6 +636,7 @@ onMounted(async () => {
bootstrapOutcome = 'completed'
} finally {
if (!disposed) {
workflowStore.markTabsRestored()
finishStartup(bootstrapOutcome)
}
}
Expand Down
7 changes: 7 additions & 0 deletions src/platform/workflow/management/stores/workflowStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -563,6 +563,11 @@ export const useWorkflowStore = defineStore('workflow', () => {
}
}

const tabsRestored = ref(false)
const markTabsRestored = () => {
tabsRestored.value = true
}

/** @see WorkflowStore.isSubgraphActive */
const isSubgraphActive = ref(false)

Expand Down Expand Up @@ -757,6 +762,8 @@ export const useWorkflowStore = defineStore('workflow', () => {
isSyncLoading,
loadWorkflows,

tabsRestored: computed(() => tabsRestored.value),
markTabsRestored,
isSubgraphActive,
activeSubgraph,
updateActiveGraph,
Expand Down
9 changes: 9 additions & 0 deletions src/platform/workflow/management/stores/workflowStoreTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,15 @@ export interface WorkflowStore {
loadWorkflows: () => Promise<void>
reorderWorkflows: (from: number, to: number) => void

/**
* `true` once startup has finished restoring the previous session's open
* tabs, including unsaved drafts recreated from local storage. Until then,
* a workflow with no open tab may simply not have been restored yet.
*/
tabsRestored: boolean
/** Called once startup tab restoration settles, including when startup fails first. */
markTabsRestored: () => void

/** `true` if any subgraph is currently being viewed. */
isSubgraphActive: boolean
activeSubgraph: Subgraph | undefined
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -398,10 +398,13 @@ describe('useWorkflowPersistenceV2', () => {
expect(loadWorkflowsSpy).toHaveBeenCalledOnce()
expect(openWorkflowMock).not.toHaveBeenCalled()

expect(workflowStore.tabsRestored).toBe(false)

gate.resolve()
await pending

expect(openWorkflowMock).toHaveBeenCalledWith(workflowB)
expect(workflowStore.tabsRestored).toBe(true)
})

it('falls back to the default workflow when metadata loading fails', async () => {
Expand All @@ -416,6 +419,7 @@ describe('useWorkflowPersistenceV2', () => {

expect(loadBlankWorkflowMock).toHaveBeenCalled()
expect(openWorkflowMock).not.toHaveBeenCalled()
expect(workflowStore.tabsRestored).toBe(true)
})

it('activates the correct workflow at storedActiveIndex', async () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,14 @@ export function useWorkflowPersistenceV2() {
* GraphCanvas must call this during startup when workflow persistence is enabled.
*/
const restoreWorkflowTabsState = async () => {
try {
await restoreSavedTabs()
} finally {
workflowStore.markTabsRestored()
}
}

const restoreSavedTabs = async () => {
if (!workflowPersistenceEnabled.value) {
tabStateRestored = true
return
Expand Down
1 change: 1 addition & 0 deletions src/workbench/extensions/agent/AgentPanelRoot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -305,6 +305,7 @@ function syncFakeSelection() {
}

beforeEach(() => {
useWorkflowStore().markTabsRestored()
let clientMessageIds = 0
nextClientMessageId.mockImplementation(
() => `client-message-${++clientMessageIds}`
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { render, waitFor } from '@testing-library/vue'
import type { WorkflowResponse } from '@comfyorg/ingest-types'
import { getActivePinia } from 'pinia'
import { assert, beforeEach, describe, expect, it, vi } from 'vitest'
import { defineComponent } from 'vue'
import { defineComponent, nextTick } from 'vue'

import { i18n } from '@/i18n'
import { useWorkflowService } from '@/platform/workflow/core/services/workflowService'
import { useWorkflowStore } from '@/platform/workflow/management/stores/workflowStore'
import { blankGraph } from '@/scripts/defaultGraph'
import { createMockLoadedWorkflow } from '@/utils/__tests__/litegraphTestUtils'

import type { CloudWorkflowEntry } from '../../schemas/agentApiSchema'
Expand All @@ -18,8 +20,9 @@ import { useAgentWorkflowSelection } from './useAgentWorkflowSelection'

vi.mock(import('@/platform/workflow/core/services/workflowService'))

function setup() {
function setup({ tabsRestored = true }: { tabsRestored?: boolean } = {}) {
const workflows = useWorkflowStore()
if (tabsRestored) workflows.markTabsRestored()
const bindings = useAgentWorkflowTabBindingStore()
const panel = useAgentPanelStore()
panel.beginWorkflowRestoration()
Expand Down Expand Up @@ -654,6 +657,138 @@ describe('historical workflow restoration', () => {
expect(warnRestoreFailed).not.toHaveBeenCalled()
})

const draftPath = 'workflows/Agent draft.json'
const draftGraphId = '3d4d7f1e-3c8b-4a0a-9a3c-1d2e3f4a5b6c'

async function bindDraftThenReload(): Promise<void> {
const beforeReload = useWorkflowStore()
const draft = beforeReload.createTemporary('Agent draft.json', {
...blankGraph,
id: draftGraphId
})
beforeReload.openWorkflowsInBackground({ right: [draft.path] })
const bindingsBeforeReload = useAgentWorkflowTabBindingStore()
bindingsBeforeReload.bind('wf-draft', draft.path)
await nextTick()
bindingsBeforeReload.$dispose()
delete getActivePinia()?.state.value[bindingsBeforeReload.$id]
await beforeReload.closeWorkflow(draft)
}

function restoreDraftTab(workflows: ReturnType<typeof useWorkflowStore>) {
const restored = workflows.createTemporary('Agent draft.json', {
...blankGraph,
id: draftGraphId
})
workflows.openWorkflowsInBackground({ right: [restored.path] })
workflows.markTabsRestored()
return restored
}

it('PM-2332 waits for a page reload to restore the unsaved draft tab before calling the chat target unavailable', async () => {
await bindDraftThenReload()
const {
selection,
workflows,
panel,
listCloudWorkflows,
getCloudWorkflow,
warnRestoreFailed
} = setup({ tabsRestored: false })

const restoration = selection.restoreTarget('wf-draft', () => true)
await vi.waitFor(() => expect(listCloudWorkflows).toHaveBeenCalled())
await new Promise((resolve) => setTimeout(resolve, 0))

expect(panel.targetUnavailable).toBe(false)

const restored = restoreDraftTab(workflows)

expect(await restoration).toBe(true)
expect(restored.path).toBe(draftPath)
expect(getCloudWorkflow).toHaveBeenCalledWith('wf-draft')
expect(panel.targetUnavailable).toBe(false)
expect(panel.selectedWorkflow?.path).toBe(draftPath)
expect(workflows.activeWorkflow?.path).toBe(draftPath)
expect(warnRestoreFailed).not.toHaveBeenCalled()
})

it('waits for the reloaded draft tab even when the listing is incomplete', async () => {
await bindDraftThenReload()
const {
selection,
workflows,
panel,
listCloudWorkflows,
warnRestoreFailed
} = setup({ tabsRestored: false })
listCloudWorkflows.mockImplementationOnce(async () =>
listing([{ id: 'wf-saved', name: 'saved' }], false)
)

const restoration = selection.restoreTarget('wf-draft', () => true)
await vi.waitFor(() => expect(listCloudWorkflows).toHaveBeenCalled())
await new Promise((resolve) => setTimeout(resolve, 0))
expect(workflows.syncWorkflows).not.toHaveBeenCalled()
expect(warnRestoreFailed).not.toHaveBeenCalled()

restoreDraftTab(workflows)

expect(await restoration).toBe(true)
expect(panel.selectedWorkflow?.path).toBe(draftPath)
expect(panel.targetUnavailable).toBe(false)
expect(warnRestoreFailed).not.toHaveBeenCalled()
})

it('calls the target unavailable when startup never finishes restoring tabs', async () => {
vi.useFakeTimers()
try {
const { selection, panel, listCloudWorkflows, getCloudWorkflow } = setup({
tabsRestored: false
})
let settled = false
const restoration = selection
.restoreTarget('wf-deleted', () => true)
.finally(() => {
settled = true
})
await vi.waitFor(() => expect(listCloudWorkflows).toHaveBeenCalled())

await vi.advanceTimersByTimeAsync(14_000)
expect(settled).toBe(false)
expect(panel.targetUnavailable).toBe(false)

await vi.advanceTimersByTimeAsync(1_000)
expect(settled).toBe(true)
expect(await restoration).toBe(true)
expect(panel.targetUnavailable).toBe(true)
expect(getCloudWorkflow).not.toHaveBeenCalled()
} finally {
vi.useRealTimers()
}
})

it('still calls the target unavailable once a reload restores no tab for it', async () => {
const {
selection,
panel,
getCloudWorkflow,
listCloudWorkflows,
workflows
} = setup({ tabsRestored: false })

const restoration = selection.restoreTarget('wf-deleted', () => true)
await vi.waitFor(() => expect(listCloudWorkflows).toHaveBeenCalled())
await new Promise((resolve) => setTimeout(resolve, 0))
expect(panel.targetUnavailable).toBe(false)

workflows.markTabsRestored()

expect(await restoration).toBe(true)
expect(panel.targetUnavailable).toBe(true)
expect(getCloudWorkflow).not.toHaveBeenCalled()
})

it('does not mark a superseded restoration unavailable when its listing omits the workflow', async () => {
const { selection, panel, current, listCloudWorkflows, warnRestoreFailed } =
setup()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { until } from '@vueuse/core'
import { storeToRefs } from 'pinia'
import { computed, onScopeDispose, ref } from 'vue'
import { computed, nextTick, onScopeDispose, ref } from 'vue'
import { useI18n } from 'vue-i18n'

import { useToast } from '@/components/ui/toast/toastStore'
Expand All @@ -25,6 +26,8 @@ type RestorationOutcome =
| { outcome: 'deleted' }
| { outcome: 'superseded' }

const STARTUP_TAB_RESTORE_TIMEOUT_MS = 15_000

function restorationOutcomeFor(
lifecycle: CloudWorkflowLifecycle,
target: ComfyWorkflow | null
Expand Down Expand Up @@ -243,17 +246,35 @@ export function useAgentWorkflowSelection({
): Promise<RestorationOutcome> {
const listed = await refreshCloudWorkflowIds()
if (!isCurrent()) return { outcome: 'superseded' }
const target =
boundOrOpenWorkflowFor(workflowId) ?? storedWorkflowFor(workflowId)
let target = localOwnerFor(workflowId)
if (target === null) {
if (!(await startupTabsRestored(isCurrent)))
return { outcome: 'superseded' }
target = localOwnerFor(workflowId)
}
if (!listed || !cloudListingOmits(workflowId))
return { outcome: 'open', target }
if (target === null) return { outcome: 'deleted' }
const lifecycle = await cloudWorkflowLifecycle(workflowId)
if (!isCurrent()) return { outcome: 'superseded' }
return restorationOutcomeFor(
lifecycle,
boundOrOpenWorkflowFor(workflowId) ?? storedWorkflowFor(workflowId)
)
return restorationOutcomeFor(lifecycle, localOwnerFor(workflowId))
}

function localOwnerFor(workflowId: string): ComfyWorkflow | null {
return boundOrOpenWorkflowFor(workflowId) ?? storedWorkflowFor(workflowId)
}

async function startupTabsRestored(
isCurrent: () => boolean
): Promise<boolean> {
if (!workflowStore.tabsRestored) {
await until(() => workflowStore.tabsRestored).toBe(true, {
timeout: STARTUP_TAB_RESTORE_TIMEOUT_MS,
throwOnTimeout: false
})
await nextTick()
}
return isCurrent()
}

async function onWorkflowRestored(
Expand Down
Loading