Separate editing from running with a draft/publish split

Edits autosave to flow.draft.json and nodes.draft/ instead of the files the
engine reads, so the pipeline keeps running the published version until
someone publishes. Every save carries the version it was based on: a second
client editing the same flow is refused with 409 and offered the choice
between their version and its own, rather than silently overwriting.

Draft saves no longer rebuild the pipeline; validation and node status for a
draft come from a throwaway build that never touches live state.

Also fixes a latent bug where an empty state backend is falsy, so Pipeline
quietly built itself a second, private state and left message history empty.
This commit is contained in:
Melvin Strobl
2026-08-15 23:13:15 +02:00
parent 97b496c9fa
commit 7698289776
18 changed files with 1159 additions and 132 deletions
+99 -15
View File
@@ -3,9 +3,9 @@ import {
useMutation,
useQueryClient,
} from "@tanstack/react-query"
import { useCallback, useEffect, useRef } from "react"
import { useCallback, useEffect, useRef, useState } from "react"
import { type FlowDef_Input, FlowsService } from "@/client"
import { ApiError, type FlowDef_Input, FlowsService } from "@/client"
export const flowKeys = {
all: ["flows"] as const,
@@ -45,55 +45,139 @@ export const messageHistoryQueryOptions = (name: string, message: string) => ({
})
const AUTOSAVE_DELAY = 800
/** How long to wait for a save in flight before sending the next one. */
const RETRY_DELAY = 100
/** Publish the unpublished changes, which is what puts them on the engine. */
export function usePublish(name: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: (version: number) =>
FlowsService.publishFlow({ name, requestBody: { version } }),
onSuccess: (detail) => {
queryClient.setQueryData(flowKeys.detail(name), detail)
queryClient.invalidateQueries({ queryKey: flowKeys.all, exact: true })
},
})
}
/** Throw the unpublished changes away and go back to what is running. */
export function useDiscardDraft(name: string) {
const queryClient = useQueryClient()
return useMutation({
mutationFn: () => FlowsService.discardDraft({ name }),
onSuccess: (detail) => {
queryClient.setQueryData(flowKeys.detail(name), detail)
queryClient.invalidateQueries({ queryKey: flowKeys.all, exact: true })
},
})
}
/**
* Saves the flow a moment after the last edit, and immediately when the editor
* needs the server to be current (closing a panel, switching flow, running).
*
* Identical documents are skipped server-side, so a quiet canvas writes nothing.
* Saving writes a draft — the engine keeps running the published version until
* someone publishes. Identical documents are skipped server-side, so a quiet
* canvas writes nothing.
*
* Every save carries the version it is based on. If another client saved in
* between, the server refuses rather than discarding their work, and `conflict`
* turns true for the editor to ask which version wins.
*/
export function useAutosave(name: string): {
save: (definition: FlowDef_Input) => void
flush: () => void
/** Send what is queued and resolve once the server has it. */
flush: () => Promise<void>
conflict: boolean
resolveConflict: (mode: "theirs" | "mine") => Promise<void>
mutation: UseMutationResult<unknown, unknown, FlowDef_Input, unknown>
} {
const queryClient = useQueryClient()
const pending = useRef<FlowDef_Input | null>(null)
const timer = useRef<ReturnType<typeof setTimeout> | null>(null)
// The freshest version this client has seen. Local edits keep the document
// they were made against, so the version has to be stamped on at send time.
const version = useRef<number | null>(null)
const sent = useRef<FlowDef_Input | null>(null)
const inFlight = useRef(false)
const [conflict, setConflict] = useState(false)
const mutation = useMutation({
mutationFn: (definition: FlowDef_Input) =>
FlowsService.saveFlow({ name, requestBody: definition }),
FlowsService.saveFlow({
name,
requestBody: { ...definition, version: version.current ?? undefined },
}),
onMutate: (definition) => {
inFlight.current = true
sent.current = definition
},
onSettled: () => {
inFlight.current = false
},
onSuccess: (detail) => {
version.current = detail.definition.version ?? null
// Write the server's answer straight into the cache: invalidating would
// pull the document back out from under edits still in flight.
queryClient.setQueryData(flowKeys.detail(name), detail)
queryClient.invalidateQueries({ queryKey: flowKeys.all, exact: true })
},
onError: (error) => {
if (error instanceof ApiError && error.status === 409) setConflict(true)
},
})
// react-query hands back a new mutation object on every render, so flushing
// has to hang off `mutate`, which is stable. Depending on the whole mutation
// re-ran the effect below on every render, and its cleanup cancelled the
// pending save before it ever fired.
const { mutate } = mutation
const flush = useCallback(() => {
const { mutate, mutateAsync } = mutation
const flush = useCallback(async (): Promise<void> => {
if (timer.current) {
clearTimeout(timer.current)
timer.current = null
}
const definition = pending.current
pending.current = null
if (definition) {
mutate(definition)
if (!definition) return
// Two saves in flight at once would race for the same version, and the
// loser would look like someone else's edit.
if (inFlight.current) {
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY))
return flush()
}
}, [mutate])
pending.current = null
// A rejection here is a conflict, which the dialog handles; callers waiting
// on the flush only need to know the attempt is over.
await mutateAsync(definition).catch(() => undefined)
}, [mutateAsync])
const resolveConflict = useCallback(
async (mode: "theirs" | "mine") => {
setConflict(false)
if (mode === "theirs") {
pending.current = null
sent.current = null
version.current = null
await queryClient.invalidateQueries({
queryKey: flowKeys.detail(name),
})
return
}
const current = await FlowsService.readFlow({ name })
version.current = current.definition.version ?? null
const definition = pending.current ?? sent.current
pending.current = null
if (definition) mutate(definition)
},
[mutate, name, queryClient],
)
const save = useCallback(
(definition: FlowDef_Input) => {
pending.current = definition
if (timer.current) clearTimeout(timer.current)
timer.current = setTimeout(flush, AUTOSAVE_DELAY)
timer.current = setTimeout(() => void flush(), AUTOSAVE_DELAY)
},
[flush],
)
@@ -101,15 +185,15 @@ export function useAutosave(name: string): {
// Leaving the tab is the last chance to persist what is still queued.
useEffect(() => {
const onHidden = () => {
if (document.visibilityState === "hidden") flush()
if (document.visibilityState === "hidden") void flush()
}
document.addEventListener("visibilitychange", onHidden)
return () => {
document.removeEventListener("visibilitychange", onHidden)
// Unmounting is a flow switch, not a reason to drop a queued edit.
flush()
void flush()
}
}, [flush])
return { save, flush, mutation }
return { save, flush, conflict, resolveConflict, mutation }
}