Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

22.2 KB
Raw Blame

Queue

Paths are relative to the webv2 src/ directory.

Queue's private QueueBackendPort is adapter seam; public callers use domain reads, commands, and production runtime factories from @features/queue. Private snake_case HTTP DTOs map explicitly to camelCase Queue read models before crossing that interface. TanStack Query owns global backend queue read model (reads and hydrates only a bounded recent window) and a status-only read for count summaries such as Home; non-React runtimes own reconciliation and realtime orchestration. Persisted per-project queue history stays in Workbench aggregate.

Queue exposes board-independent active backend sessions, including preparation and result settlement. Auto-switch is one policy in core/activeSessions.ts, used by Preview (viewerAutoSwitch) and Canvas staging (autoSwitchMode): selectsLandedResult (Newest and In progress select each landed result, Off only while none is selected), getAutoSwitchFollowedLive (only In progress shows generating slots: the pinned one while it runs, else the newest running one with a frame of its own, else the first settling one with a frame) and pickAutoSwitch (a user picking a finished result turns it Off; picking a generating slot turns it In progress and pins that slot). Staging adapts them in the Workbench (reconcileCanvasStagingFollow): it hears which slots have frames from this feature's first-frame signal, and cannot tell a slot waiting to start from one running, so a staging pin holds until its slot is gone where Preview's is released once its session stops running (or never holds on a waiting one). Gallery progress section includes every unfinished batch slot, queued work too; Preview follows executing and settling sessions, each only once it has shown a progress frame of its own (activeProgressTargetStore framed slots, marked by the coordinator on a slot's first frame). Until then the previous result stays on screen: a finished slot's last frame while its result routes, then the selected result, swapped in over that frame until it decodes (progressImageStore swap frames). Preview shows its run's progress message for a starting session instead of switching to an empty frame (model loads are not named: the server does not say which session they are for), and its status line announces the gap once; it shows the frameless session only when nothing is selected or the user pinned it. The coordinator reports the same first frame to the Workbench (QueueHistoryCommands.noteFirstProgressFrame), where Canvas staging follows it. Both use gallery-destination projections of active project's queue; eligibility is presentation policy, separate from discovery. Workbench owns transient overview/pinned follow selection for its mounted lifetime, clears pins on project changes or when following stops, and never persists pins or preview frames. Live sessions take no part in board counts, saved-image selection, or navigation. Saved outputs keep their actual backend board destinations; automatic result selection does not change browsed board or its paging window.

Gallery owns coalesced socket-completion invalidation for the account across tabs; Queue retains its connection reconciliation refresh. Completion invalidation does not depend on whether this tab tracks the run.

Retry re-runs failed or canceled backend items under new ids; the run owning them reopens around the reruns so its captured destination receives their results. A rerun no open run adopts reaches the Gallery, or the current Canvas of a tab with its project open. Canvas reruns use an account-wide server delivery claim (POST queue/{id}/i/{item_id}/delivery): claim, stage locally, then confirm. Local staging and server acknowledgement are separate. The account runtime shares one confirmation budget per staged backend item across run/tab claimants and synchronous notifications. runtime/deliveryClaims.ts drains at most eight confirmation requests concurrently. A failed or lost confirmation retries idempotently at most five times with 1/2/4/8-second waits while this account's runtime is active; definitive client errors stop retries. Only actually granted live claims renew every 40 seconds: adopted claims before staging, and owned staged claims while confirmation is queued or unresolved. The latter use a separate coalesced drain of at most eight renewal requests, so a recovery backlog cannot leave a live claimant idle for its lease lifetime. Recovery/fail-open staging never marks a claim owned; deduplicated confirmation can upgrade to the actual holder without changing its retry budget. Confirmation does not claim arbitrary recovered items. Exhaustion reports that local results remain staged but another browser may deliver them again; the same candidate does not automatically restart its budget in that runtime. A later editor/project recovery may start a fresh budget. Delivery requests time out after 10 seconds. Server confirmation is claimant-independent even after a lease changes; only a response of delivered confirms server delivery; a lost successful response is harmless on replay. Staged work is never released. Unstaged work is released when its run ends or its project closes, while an abandoned claim lapses after two minutes. Same-account disposal releases owned unstaged claims, including late grants. Account changes fence releases as well as confirmations; abandoned leases expire. Disposal/account changes stop owned retries and renewals; they do not establish server cancellation or confirmation.

A reopened run claims as run:<project, run> after its tab holds the existing browser run lock. A tab staging an unadopted rerun claims as itself, after waiting for the browser tab tracking the run. Another claimant waits until confirmation or lease expiry. Each image retains its producing backend item id through batch result flattening, so Canvas acknowledgement never depends on its position in the image list. Production's history adapter exposes existing Canvas candidates with their backend ids: routing must actually leave a candidate before confirmation, and candidates restored through project recovery resume acknowledgement without restaging. Live routing excludes known ordinary results from metadata recovery before staging notifies subscribers, and retains that exclusion only while their candidates survive, independently of queue history. Restored candidates are unknown and require authoritative validation. Recovery reads backend metadata serially in batches of 64, with a 10-second timeout and at most three attempts separated by 1/2-second waits. Only rows with retry ancestry, Canvas destination, and the candidate's project/run origin are confirmed; ordinary staged generations do not trigger confirmation after reload or completed-history clearing. A missing backend row cannot be recovered. An exhausted metadata batch stops recovery for that runtime and reports the need to reload the editor, rather than continuing through an outage with all remaining candidates. This adds no persisted fields. Recovery requires that the candidate survived existing project/journal persistence; a crash before that, or removal of a candidate before an offline acknowledgement and reload, has no durable delivery ledger. A frozen browser can lose its lease to another browser. Local image deduplication only protects the current project snapshot; these guarantees do not establish global exactly-once delivery. Claims intentionally fail open when the endpoint is unsupported (404), or remains unavailable for a claim lifetime, preserving availability with a risk of duplicate delivery across stale browser snapshots.

Submission recovery

A run the backend has not accepted keeps resubmitting, and records its latest failed attempt on the run (QueueItem.submissionRetry, cleared once the backend accepts the run or the run ends). Each failure is reconciled before the run submits again, and the run waits from that failure by its own consecutive failures, whatever their reason: 1 s, doubling to at most 15 s. A reconcile never shortens that wait. When the connection comes back after a disconnect, each run this tab is waiting to submit then goes within a random share of 2 s, or sooner if its own wait ends first, so a restarting server and every tab do not get them all at once. The record names why the attempt failed: unavailable for 408, 429, 502, 503 and 504; unreachable when the request got no answer (fetch rejected or timed out); error for any other failure that is not a 5xx, such as an answer that could not be read, which may still have committed the batch; all three retry without limit. Any other 5xx is a server-error and counts toward a budget: three consecutive ones, the last at least 10 seconds after the first (five attempts at this pace), fail the run with the server's message, unless the reconcile that follows the last finds the backend accepted it after all. Any other failure starts that count over, and so does an attempt starting more than 5 minutes after the run's previous failure, measured from the attempt's start so a slow answer cannot reset its own count; minutes, because a hidden tab's timers may fire only once a minute. The recorded message keeps at most its first 500 characters, ending with an ellipsis when cut, since a 5xx without a JSON body is the whole response page. The whole record travels with the run in the queue-run journal, written again after every failed attempt (so the pace bounds those writes), and a reload or a restarted runtime continues the budget and the remaining wait; restoring bounds the message again and drops a record it cannot read, such as one with a reason it does not know, but keeps the run. Both are judged from the recorded failure times; a clock set back before them restarts the 10 seconds without resetting the count and waits at most one delay. core/submissionRetry.ts owns these rules (create, pace, exhausted, clear, equality, restore); the runtime keeps the timers and reconnect spread, and the Workbench reducer and run restoration use it through @features/queue/contracts.

Utility operations

Utility graphs (@features/queue/utility) get a fresh operation origin/key per deliberate invocation. Admission freezes graph, origin, prepend and key, uses at most three 10-second POST attempts, and looks up the same receipt after ambiguous failures (each read also bounded to 10 seconds). Missing/unavailable receipts replay that same key after abortable 1/2-second waits between admission/receipt pairs: absence is not evidence the first POST cannot commit. Conflicts and definitive validation errors are surfaced. The backend's existing project-less idempotency contract admits one logical operation across these retries. Exhausted admission recovery explicitly reports that backend work may still be running; calling the API again is a new operation, and reload recovery is unavailable because utility operations own no persistent ledger.

The runtime acknowledges a utility receipt only after retaining accepted ids, including late ids needed for best-effort cancellation or malformed-response cleanup. Acknowledgement is independent of watching and retries at most five times with 1/2/4/8-second waits and a 10-second request bound. Definitive client rejections stop acknowledgement retries. Account changes abort these requests and waits; retries never run under a replacement account. Failed final acknowledgement or reload before acknowledgement can leave a server receipt; no unbounded in-memory retry or new persistence is introduced. Acknowledged receipts use the server's existing retention policy; unacknowledged receipts have no TTL and count against the 10,000-receipt quota shared with keyed generation enqueues. Exhausted utility acknowledgement is not reclaimed automatically; filling that quota rejects all keyed enqueues with 429 until server receipts are reclaimed. Server-side expiry/reclamation of abandoned unacknowledged receipts remains a follow-up.

Both utility APIs reconcile accepted status every 15 seconds while active, coalescing overlapping reconnect, clear, bulk-cancel and periodic reads with one follow-up read for events received during an outstanding read. Each production status read times out after 10 seconds: with a responsive backend, a missed terminal event is observed within one interval plus its read latency. Failed/canceled items and removed items (404) settle truthfully. Transient read failures leave the watch open for the next event/read. Three consecutive failed reads for an item spanning at least 30 seconds end the watch with a visible reconciliation error saying backend work may still be running. Event bursts cannot exhaust the budget immediately; every successful status read, including pending, in_progress and waiting, resets that item's health budget. With interval-driven immediate failures this settles at about 45 seconds after admission; hung 10-second reads settle by about 75 seconds. No cancellation is claimed by this health error. runUtilityGraph recovers completed output with bounded retries; malformed data fails reconciliation. There is no universal utility deadline, so model downloads, long queue waits and calibration remain supported. An explicit timeoutMs covers admission and waiting; before reporting timeout it performs an authoritative status read, allowing completed-output recovery to finish. Output reads/retries are separate from admission retries.

submitUtilityGraph returns accepted ids and a settled promise. Aborting it stops watching and leaves accepted backend work alone. Aborting or explicitly timing out runUtilityGraph requests best-effort cancellation, including ids recovered after the caller stopped waiting; cancellation is never represented as confirmed. Account changes stop watches and fence late cancellation from a replacement account. Terminal paths detach listeners and stop periodic and retry timers. Rerun retry waits resolve on abort as before, remove their abort listener after ordinary completion, and clear their timer on abort. runUtilityGraph accepts prepend: true for interactive utilities and an optional onStatus observer. It publishes only observed pending/in_progress states, deduplicates them and never regresses after execution begins. Origin-scoped events can arrive before the enqueue response. An initial accepted-item read for observers repairs a missed early event; the shared 15-second reconciliation and reconnect reads repair subsequent gaps without a separate progress polling loop. Terminal cleanup fences late reads and callbacks; observer errors cannot disrupt settlement.

Live read model

The realtime runtime applies each queue_item_status_changed event to every loaded read model at once (applyQueueItemStatusChange in data/queries.ts) and still invalidates, coalesced, so the next read reconciles. Read models carry each item's priority and statusSequence; a change applies only when it is newer than the cached item (a higher sequence when both have one, otherwise never to an item already finished), so a late event never undoes a read, and once a read brings in a restarted server's lower sequences its events apply again. The current and next items follow the event: an item leaving progress hands current to another item still running, or clears it, and the next waiting item becomes the window's first pending item in run order (highest priority, then oldest) until the read names the server's, when the window can hold it (see Actions). Counts: an unscoped model, and the whole-queue status read, take an event's whole-queue counts, even when the model already shows the item so (after the viewer's own cancel); otherwise a change to an item the model knows, an event or this tab's own assumed cancel, moves it between the aggregate buckets. The server sends the full event, with own-item counts and current-item identifiers computed for the item's owner, to that owner and to every administrator, so the viewer's own counts wait for the read. Only cached data changes; account changes clear the cache with everything else.

Actions

ui/queueMenuActions.tsx is the one queue action model: the top bar's button and menu, the widget header and its menu, and shortcuts (requestQueueAction in @features/queue/reveal, taken by the queue's always-mounted host once the read model has loaded) all call an action's trigger, never its runner. Its policy: cancelling the current item never asks, since Retry brings it back; cancelling all, cancelling all but the current item, and clearing failed, finished or all items always confirm, naming the scope and how many items they reach, with a way out that never reads "Cancel". Results report the same scope and counts. Pause and resume are one toggle that states what waits on the processor.

Cancel-current (the top bar's ×, Shift+X, the command palette) runs through one non-React function, cancelCurrentQueueItem (ui/cancelCurrent.ts). It stops the item in progress the viewer can manage (getCancelCurrentTarget), else, only in the gap between two items, the next one waiting in run order. The gap is the processor running (not paused) with nothing in progress anywhere in the queue: the hand-off between items, a cached reading that is behind, or a canceled item's worker still finishing; stopping the next item is then what stops the run from the viewer's side. While the processor is paused, or anything runs that it would not cancel, nothing waiting is stopped and the × is disabled. "Anywhere" is the whole queue whatever the view's scope: an unscoped read model's own counts, else the whole-queue status read (useWholeQueueStatus, the key the Launchpad's status band shares, read only while the view is scoped); unknown counts as something running. processor.isProcessing is not used: it stays true while a canceled item's worker finishes. The next item is the server's; the read window stands in for it only when it holds exactly the pending items the counts report, since the window is the newest items and the true next may be older (a long batch, a member's items among everyone's); otherwise, or when an item the window does not list starts waiting, it is unknown until the next read. The action's name says which it will stop ("Cancel current item" or "Cancel next item"). One runs at a time per account, and after it stops an item the command stays busy for a settle window (at least 400 ms, until the reconciling read lands, at most 2 s), so a double click, a double tap of the shortcut or a double activation in the palette stops one item, and a deliberate press after the window stops the next; the × also ignores a click's follow-up clicks (detail > 1) and a held Enter's auto-repeat, which clicks on every repeat (Space clicks on release), and the shortcut ignores a held key's auto-repeat (ignoreRepeat). It picks its target from the loaded read model when it runs, shows the item canceled there and in the whole-queue status at once, and puts both back if the request fails, only where nothing changed them since; when an event reported the item canceled meanwhile, the server did cancel it though its answer was lost, so nothing is put back and the cancel reports as requested. The server answers a cancel of an item that already finished with the item unchanged, which the read models take at once (its higher status sequence wins); the action then reads the queue afresh (its own read, started after the answer and bounded by the cancel's 10-second deadline, so a stalled read cannot hold the command busy; a read already in flight is neither joined nor cancelled, since others such as the palette's queue search may await it), within the same account, and stops what is current now, once, and says there is nothing to cancel when nothing is. When that read fails or times out, it says the item had already finished: nothing failed to cancel. It never reports a cancel that did nothing. Shift-click on the × is cancel-all, within the queue scope setting.

Counts and scope follow what the action does for the viewer (QueueUiAdapter.viewer). A member's cancels count their own unfinished items; an administrator's count everyone's, since their cancel and clear reach every user. Across all projects the server counts every user's history, so a member's clears confirm without a count. Each scope (one project, all projects, all projects and users, all of a member's projects) has its own whole sentence in the catalog (translateScoped), never a fragment stitched into one. Cancel-all also cancels this tab's runs the backend has not accepted (QueueUiAdapter.localRuns), so it stays available offline while there are any. The widget lists those runs in its Submitting section above the current batch, under All and Active and within the queue scope setting, and counts them in those tabs (useShownLocalRuns). A run shows once its enqueue has failed, while the tab is offline, or once it has gone a second unaccepted, so an ordinary Invoke never flashes a row. Each says whether it is being sent, retried after a server error, waiting on a busy or unreachable server (with the attempt it is on), or held while the tab is offline, and cancels on its own without asking, as any single cancel does. Cancel-all counts every unaccepted run in scope, shown or not. The section's rows load with the first such run; if they cannot load, the section offers Retry and the rest of the widget keeps working.

The top bar's button, the status chip and the queue widget read one activity (core/queueActivity.ts) from the same open work: the viewer's own pending and running items within the queue scope setting (useScopedQueueOpenWork). The top bar and chip count the larger of that and the active project's runs, whose progress they show (useQueueChromeActivity in workbench/queue-integration), so neither reads idle while the widget, under the same scope, shows work waiting or running.

A cancel or clear this tab announced itself (noteQueueCancelRequested, recorded before the request and dropped if it fails) keeps the runs it ends from reporting again. It covers only runs submitted before it, leaves out the item a cancel-all-but-current kept, lapses after two minutes and clears with the account. The runtime reads it through its cancelRequests port. A run that fails names the backend item that failed (QueueItemFailedError), so its failure notice can show and retry it. An item that vanished, as a clear deletes rows without a terminal event, is removed: canceled without a notice inside a request from this tab, otherwise a failure with nothing to show or retry.