Files
windmill/frontend/src/lib/components/JobLoader.svelte
T
Ruben FiszelandClaude Opus 4.6 31d6660d56 feat: script module mode with CLI sync, preview, and WAC UI improvements (#8380)
* feat: add script module mode with folder model for Bun and Python

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: add missing modules field to RawCode in bun_executor

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* sqlx

* feat: enrich WAC templates with checkpoint and replay semantics

Add prominent comments explaining that all computation must happen
inside task/step/taskScript or it will be replayed on resume/retry.
Clarify that waitForApproval does not hold a worker and that
approve/reject URLs are available in the timeline step details.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix(cli): script module sync idempotency, per-module hash tracking, and preview support

- Fix pull→push idempotency: use `??` instead of `||` for module lock
  field so empty strings are preserved (matches API's `lock: ""`)
- Add per-module hash tracking in wmill-lock.yaml following the flow
  inline script pattern (SCRIPT_TOP_HASH + per-module subpath hashes)
- Selective module lock regeneration: only regenerate locks for modules
  whose content actually changed, not all modules
- Use unfiltered rawWorkspaceDependencies for module hashes to match
  what updateModuleLocks passes to fetchScriptLock
- Show changed module names in stale script output for clarity
- Add module support to `script preview` command: read modules from
  __mod/ folder and pass them in the preview API request
- Add preview tests for taskScript pattern (flat and folder layout)
- Update test assertion for module stale detection output

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(frontend): WAC UI improvements — reorder templates, module tab rename, import consolidation

- Reorder WAC template buttons: TypeScript before Python in
  ScriptBuilder, CreateActionsScript, and CreateActionsFlow
- Remove dropdown items from +Script button (simplify to direct link)
- Move "Import Workflow-as-Code" to +Flow dropdown with dedicated drawer
- Add module tab rename: pencil icon on hover opens popover with
  validation, fixed-width icon container prevents layout shift

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: remaining module-mode changes from working branch

- Backend parser updates for WAC detection
- CLI sync/types updates for raw app path and module support
- Frontend UI polish (Dev.svelte, ScriptRow, script hash page)
- Test fixture updates

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test(cli): add test for module modification detection in generate-metadata

Verifies that modifying a single module file re-triggers stale
detection and only the changed module is listed, not all modules.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): critical fixes from PR review

- Fix hardcoded dev path in bun_executor.rs WAC v2 wrapper — use
  "windmill-client" import instead of absolute filesystem path
- Fix missed no_main_func → auto_kind rename in parser TS test
- Add modules column to clone_script SQL (windmill-common and
  windmill-api-workspaces) so cloned scripts retain their modules
- Add modules: None to RawCode structs in worker tests
- Restore complete sqlx cache (merge main's cache + our new queries)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): fix clone warning treated as error in CI

Change `.clone()` on double reference to `*k` dereference in
scripts.rs hash implementation. Update sqlx cache with new query
hashes from modified clone_script SQL.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(frontend): use published parser wasm versions for CI build

The local file:// paths for windmill-parser-wasm-py and
windmill-parser-wasm-ts don't exist in the Cloudflare Pages build
environment. Revert to published npm versions (1.655.0).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(frontend): update parser wasm packages to 1.657.2

Use newly published windmill-parser-wasm-ts and windmill-parser-wasm-py
v1.657.2 which include auto_kind/WAC detection changes.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(frontend): regenerate package-lock.json for npm ci compatibility

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(frontend): use main's lockfile as base, update only parser wasm packages

Regenerating package-lock.json from scratch pulled different dependency
versions causing svelte-check type errors. Instead, start from main's
lockfile and only update the two changed packages.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): add modules column to fetch_script_for_update query

The Script<SR> struct has a modules field (FromRow), but
fetch_script_for_update didn't SELECT modules, causing a runtime
error "no column found for name: modules" when the worker processed
dependency jobs. This was the root cause of the relock_skip test
timeout.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): fix script module execution for Python and Bun

- Fix modules not passed through job queue: inject _MODULES into
  PushArgs.extra when pushing Code jobs so worker can extract them
- Fix Python module imports: use relative imports (from .helper)
  and add sys.path.insert for module directory in wrapper
- Fix Python tests: use relative imports and empty lock to prevent
  pip from resolving module names as packages
- Add local file check in Bun loader for module resolution
- Ignore Bun module test (bundle mode loader integration tracked
  separately)
- Add missing modules column to fetch_script_for_update query

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): remove unnecessary empty lock in Python module tests

Relative imports (from .helper) are not parsed as pip packages,
so the empty lock workaround is not needed.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(backend): fix module execution for Python and Bun — all tests pass

Python modules:
- Use relative imports (from .helper import greet) since scripts run
  as packages
- Add sys.path.insert for module directory in wrapper to ensure local
  modules take precedence over pip packages with same name

Bun modules:
- Use bundled output (./out/main.js) as wrapper import when modules
  are present — the bundled output has module content inlined by
  Bun.build, avoiding runtime loader resolution issues
- Add local file check in loader.bun.js onResolve to short-circuit
  API URL resolution for module files on disk

Job queue:
- Inject _MODULES into PushArgs.extra when pushing Code jobs so
  the worker can extract them at execution time

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* refactor: address PR review — simplify, fix correctness, remove dead code

Critical fixes:
- Replace all CLI `no_main_func` references with `auto_kind` (string)
  to match the backend migration and API changes
- Remove duplicated `compute_python_module_dir` in worker.rs, use
  the canonical version from python_executor.rs

High priority:
- Auto-create `__init__.py` in intermediate directories for nested
  Python modules so imports like `from .utils.math import add` work
  without users manually creating __init__.py files
- Remove redundant `sys_path_insert` — relative imports use Python's
  package system, not sys.path

Medium:
- Fix lock file base name extraction: use regex to strip only the
  final extension (`.replace(/\.[^.]+$/, '')`) instead of `indexOf(".")`
  which breaks for files like `helper.test.ts`

Simplification:
- Remove dead `{#if false}` Popover block in ScriptEditor.svelte
- Guard loader.bun.js local file check to only run for relative paths
  (matching the Windows loader pattern)
- Add clarifying comment on Bun dual mechanism (build + run phases)
- Add maintenance comment on manual Hash impl for NewScript

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: final review fixes — stale cleanup, baseName, auto_kind export

- Fix sync.ts baseName extraction using indexOf(".") → regex
  (same fix as script.ts/metadata.ts, missed this instance)
- Add stale module file cleanup in writeModulesToDisk: removes files
  from __mod/ that are no longer in the modules map before writing,
  fixing the pull→push cycle that couldn't delete modules
- Log warning when _MODULES serialization fails in job push instead
  of silently dropping modules
- Use strict equality (===) for auto_kind comparison
- Exclude auto_kind from workspace export — it is auto-detected by
  the parser at deploy time from script content

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(cli): remove auto_kind from push, comparison, and metadata

auto_kind is auto-detected by the parser at deploy time, so the CLI
should not send it, compare it, or write it to script.yaml.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: remove erroneously added backend/backend/.sqlx directory

Duplicate .sqlx cache was committed at the wrong nested path.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: address PR review feedback + fix CI dead_code warning

Frontend (ScriptEditor.svelte):
- Fix switchToMain() missing lastSyncedCode update — prevents stale
  code sync on external changes while editing a module tab
- Fix formatAction saving module code to main script's localStorage
  draft — now saves main code when on a module tab
- Fix non-null assertion on inferModuleLang in renameModule — fall
  back to original language instead of force unwrap
- Remove redundant activeModuleTab truthy check in runTest

CLI (script.ts):
- Clean up empty directories after removing stale module files in
  writeModulesToDisk

Backend:
- Add path traversal guard in write_module_files — reject module
  paths containing ".."
- Fix dead_code warning on auto_kind field in workspace export struct

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(frontend): improve auto_kind UX + address review findings

- Rename "Include without main function" toggle to "Include library
  scripts" in script list (ItemsList.svelte)
- Update NoMainFuncBadge: "No main" → "Library" with clearer tooltip
- Filter module file extensions by main script language — Python
  scripts only allow .py modules, TypeScript only .ts, etc.
- Split flushModuleState into flushModuleContent (no UI side-effect)
  and flushModuleState (flush + reset tab), reducing duplication
- Dynamic placeholder and hint text in add module popover based on
  main script language

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-17 01:20:09 +00:00

886 lines
22 KiB
Svelte

<script module lang="ts">
import pLimit from 'p-limit'
const plimit = pLimit(5)
</script>
<script lang="ts">
import {
type Job,
JobService,
type FlowStatus,
type Preview,
type GetJobUpdatesResponse,
type WorkflowStatus,
type OpenFlow
} from '$lib/gen'
import { workspaceStore } from '$lib/stores'
import { getContext, onDestroy, tick, untrack } from 'svelte'
import type { SupportedLanguage } from '$lib/common'
import { sendUserToast } from '$lib/toast'
import { DynamicInput, isScriptPreview } from '$lib/utils'
import {
getActiveRecording,
getActiveReplay,
getReplayStartTime
} from './recording/flowRecording.svelte'
// Will be set to number if job is not a flow
export type Callbacks = {
done?: (x: Job & { result?: any }) => void
doneResult?: ({ id, result }: { id: string; result: any }) => void
doneError?: ({ id, error }: { id?: string; error: Error }) => void
change?: (x: Job) => void
cancel?: ({ id }: { id: string }) => void
started?: ({ id }: { id: string }) => void
running?: ({ id }: { id: string }) => void
resultStreamUpdate?: ({ id, result_stream }: { id: string; result_stream?: string }) => void
loadExtraLogs?: ({ id, logs }: { id: string; logs: string }) => void
}
interface Props {
isLoading?: boolean
job?: (Job & { result_stream?: string }) | undefined
noCode?: boolean
noLogs?: boolean
workspaceOverride?: string | undefined
notfound?: boolean
allowConcurentRequests?: boolean
jobUpdateLastFetch?: Date | undefined
toastError?: boolean
onlyResult?: boolean
loadPlaceholderJobOnStart?: Job
// If you want to find out progress of subjobs of a flow, check job.flow_status.progress
scriptProgress?: number | undefined
children?: import('svelte').Snippet<[any]>
}
let {
isLoading = $bindable(false),
job = $bindable(undefined),
noCode = false,
allowConcurentRequests = false,
workspaceOverride = undefined,
notfound = $bindable(false),
jobUpdateLastFetch = $bindable(undefined),
toastError = false,
onlyResult = false,
loadPlaceholderJobOnStart = undefined,
scriptProgress = $bindable(undefined),
noLogs = false,
children
}: Props = $props()
let workspace = $derived(workspaceOverride ?? $workspaceStore)
let syncIteration: number = 0
let errorIteration = 0
let logOffset = 0
let resultStreamOffset = 0
let lastCallbacks: Callbacks | undefined = undefined
let finished: string[] = []
let ITERATIONS_BEFORE_SLOW_REFRESH = 10
let ITERATIONS_BEFORE_SUPER_SLOW_REFRESH = 100
let lastStartedAt: number = Date.now()
let currentId: string | undefined = $state(undefined)
let noPingTimeout: number | undefined = undefined
let lastNoLogs = $state(untrack(() => noLogs))
let lastCompletedJobId = $state<string | undefined>(undefined)
let token = getContext<{ token?: string }>('AuthToken')
$effect(() => {
let newIsLoading = currentId !== undefined
untrack(() => {
if (isLoading !== newIsLoading) {
isLoading = newIsLoading
}
})
})
const noLogsChangeRestartEvent = 'SSE restart after no logs change'
$effect(() => {
if (noLogs != lastNoLogs) {
lastNoLogs = noLogs
if (!noLogs) {
currentEventSource?.onerror?.(new Event(noLogsChangeRestartEvent))
const lastJobId = lastCompletedJobId
if (lastJobId && (job || lastCallbacks?.loadExtraLogs)) {
plimit(() =>
JobService.getCompletedJobLogsTail({
workspace: $workspaceStore!,
id: lastJobId
})
).then((res) => {
if (res && job) {
job.logs = res
}
if (res && lastCallbacks?.loadExtraLogs) {
lastCallbacks.loadExtraLogs({ id: lastJobId, logs: res })
}
})
}
}
}
})
function clearCurrentId() {
if (currentId) {
if (allowConcurentRequests) {
finished.push(currentId)
} else {
currentId = undefined
}
}
}
export async function abstractRun(fn: () => Promise<string>, callbacks?: Callbacks) {
try {
isLoading = true
scriptProgress = undefined
lastCompletedJobId = undefined
clearCurrentJob()
lastCallbacks = callbacks
noPingTimeout = undefined
const startedAt = Date.now()
const testId = await fn()
if (lastStartedAt < startedAt || allowConcurentRequests) {
lastStartedAt = startedAt
if (testId) {
callbacks?.started?.({ id: testId })
try {
await watchJob(testId, callbacks)
} catch {
if (currentId === testId) {
clearCurrentId()
}
}
}
}
return testId
} catch (err) {
if (toastError) {
sendUserToast(err.body, true)
}
callbacks?.doneError?.({ error: err })
// if error happens on submitting the job, reset UI state so the user can try again
isLoading = false
currentId = undefined
job = undefined
throw err
}
}
export async function runScriptByPath(
path: string,
args: Record<string, any>,
callbacks?: Callbacks
): Promise<string> {
return abstractRun(
() =>
JobService.runScriptByPath({
workspace: $workspaceStore!,
path: path ?? '',
requestBody: args,
skipPreprocessor: true
}),
callbacks
)
}
export async function runScriptByHash(
hash: string,
args: Record<string, any>,
callbacks?: Callbacks
): Promise<string> {
return abstractRun(
() =>
JobService.runScriptByHash({
workspace: $workspaceStore!,
hash: hash ?? '',
requestBody: args,
skipPreprocessor: true
}),
callbacks
)
}
export async function runFlowByPath(
path: string,
args: Record<string, any>,
callbacks?: Callbacks
): Promise<string> {
return abstractRun(
() =>
JobService.runFlowByPath({
workspace: $workspaceStore!,
path: path ?? '',
requestBody: args,
skipPreprocessor: true
}),
callbacks
)
}
export async function runFlowPreview(
args: Record<string, any>,
flow: OpenFlow & { tag?: string },
callbacks?: Callbacks,
path?: string
): Promise<string> {
return abstractRun(
() =>
JobService.runFlowPreview({
workspace: $workspaceStore!,
requestBody: {
args,
value: flow.value,
tag: flow.tag,
path
}
}),
callbacks
)
}
function refreshLogOffset() {
if (logOffset == 0) {
logOffset = job?.logs?.length ? job.logs?.length + 1 : 0
}
}
export async function getLogs() {
if (job) {
refreshLogOffset()
const getUpdate = await JobService.getJobUpdates({
workspace: workspace!,
id: job.id,
running: `running` in job && job.running,
logOffset: logOffset
})
if ((job?.logs ?? '').length == 0) {
job.logs = getUpdate.new_logs ?? ''
logOffset = getUpdate.log_offset ?? 0
}
}
}
export async function runDynamicInputScript(
entrypoint_function: string,
runnable_ref: DynamicInput.HelperScript,
args: Record<string, any>,
callbacks?: Callbacks
): Promise<string> {
return abstractRun(
() =>
JobService.runDynamicSelect({
workspace: $workspaceStore!,
requestBody: { entrypoint_function, args, runnable_ref }
}),
callbacks
)
}
export async function runPreview(
path: string | undefined,
code: string,
lang: SupportedLanguage | undefined,
args: Record<string, any>,
tag: string | undefined,
lock?: string,
hash?: string,
callbacks?: Callbacks,
flowPath?: string,
modules?: Record<string, import('$lib/gen').ScriptModule> | null
): Promise<string> {
return abstractRun(
() =>
JobService.runScriptPreview({
workspace: $workspaceStore!,
requestBody: {
path,
content: code,
args,
language: lang as Preview['language'],
tag,
lock,
script_hash: hash,
flow_path: flowPath,
modules: modules ?? undefined
}
}),
callbacks
)
}
export async function cancelJob() {
const id = currentId
if (id) {
lastCallbacks?.cancel?.({ id })
clearCurrentId()
// Clean up SSE connection
currentEventSource?.close()
currentEventSource = undefined
try {
await JobService.cancelQueuedJob({
workspace: $workspaceStore ?? '',
id,
requestBody: {}
})
} catch (err) {
console.error(err)
}
}
}
export async function clearCurrentJob() {
if (currentId && !allowConcurentRequests) {
job = undefined
lastCallbacks?.cancel?.({ id: currentId })
await cancelJob()
}
}
function supportsSSE() {
const sseSupported = typeof EventSource !== 'undefined'
if (!sseSupported) {
console.error('SSE not supported, falling back to polling')
}
return sseSupported
}
let replayTimeouts: ReturnType<typeof setTimeout>[] = []
let startedWatchingJob: number | undefined = undefined
export async function watchJob(testId: string, callbacks?: Callbacks) {
logOffset = 0
resultStreamOffset = 0
syncIteration = 0
errorIteration = 0
currentId = testId
scriptProgress = undefined
// Replay mode: feed recorded events instead of real SSE
const replay = getActiveReplay()
if (replay) {
const recorded = replay.jobs[testId]
if (recorded) {
job = JSON.parse(JSON.stringify(recorded.initial_job))
callbacks?.change?.(job!)
// Compute delays relative to replay start so sub-jobs (discovered
// later by FlowStatusViewerInner) stay in sync with the root job.
const elapsed = Date.now() - getReplayStartTime()
for (const event of recorded.events) {
const delay = Math.max(0, event.t - elapsed)
const timeout = setTimeout(() => {
if (job) {
updateJobFromProgress(event.data, job, callbacks)
}
if (event.data.completed) {
const njob = (event.data as any).job as Job & { result_stream?: string }
if (njob) {
// Use whichever logs are more complete (longer)
const streamedLogs = job?.logs ?? ''
const completedLogs = njob.logs ?? ''
njob.logs =
streamedLogs.length >= completedLogs.length ? streamedLogs : completedLogs
const streamedResult = job?.result_stream ?? ''
const completedResult = njob.result_stream ?? ''
njob.result_stream =
streamedResult.length >= completedResult.length ? streamedResult : completedResult
job = njob
onJobCompleted(testId, job, callbacks)
}
}
}, delay)
replayTimeouts.push(timeout)
}
return
}
// Job not in recording — stub it to prevent API calls
const stubJob = { id: testId, type: 'CompletedJob', success: true } as Job
job = stubJob
callbacks?.change?.(stubJob)
clearCurrentId()
return
}
if (loadPlaceholderJobOnStart) {
job = structuredClone(loadPlaceholderJobOnStart)
} else {
job = undefined
}
startedWatchingJob = Date.now()
// Clean up any existing SSE connection
currentEventSource?.close()
currentEventSource = undefined
lastCallbacks = callbacks
// Try SSE first, fall back to polling if needed
if (supportsSSE()) {
await loadTestJobWithSSE(testId, 0, callbacks)
} else {
syncer(testId, callbacks)
}
}
const clamp = (num: number, min: number, max: number) => Math.min(Math.max(num, min), max)
function updateJobFromProgress(
previewJobUpdates: GetJobUpdatesResponse,
job: Job & { result_stream?: string },
callbacks: Callbacks | undefined
) {
// Clamp number between two values with the following line:
if (previewJobUpdates.running) {
if (job && job.type == 'QueuedJob' && !job.running) {
callbacks?.running?.({ id: job.id })
job.running = true
}
}
if (previewJobUpdates.progress) {
console.log('progress', previewJobUpdates.progress)
// Progress cannot go back and cannot be set to 100
scriptProgress = clamp(previewJobUpdates.progress, scriptProgress ?? 0, 99)
}
if (previewJobUpdates.new_logs) {
if (logOffset == 0) {
job.logs = previewJobUpdates.new_logs ?? ''
} else {
job.logs = (job?.logs ?? '').concat(previewJobUpdates.new_logs)
}
}
if (previewJobUpdates.new_result_stream) {
if (!job.result_stream) {
job.result_stream = previewJobUpdates.new_result_stream
} else {
job.result_stream = job.result_stream.concat(previewJobUpdates.new_result_stream)
}
callbacks?.resultStreamUpdate?.({
id: job.id,
result_stream: job.result_stream
})
}
if (previewJobUpdates.log_offset) {
logOffset = previewJobUpdates.log_offset ?? 0
}
if (previewJobUpdates.stream_offset) {
resultStreamOffset = previewJobUpdates.stream_offset ?? 0
}
if (previewJobUpdates.flow_status) {
job.flow_status = previewJobUpdates.flow_status as FlowStatus
}
if (previewJobUpdates.workflow_as_code_status) {
job.workflow_as_code_status = previewJobUpdates.workflow_as_code_status as WorkflowStatus
}
if (previewJobUpdates.mem_peak && job) {
job.mem_peak = previewJobUpdates.mem_peak
}
if (
job &&
(previewJobUpdates.running ||
previewJobUpdates.progress ||
previewJobUpdates.log_offset ||
previewJobUpdates.flow_status ||
previewJobUpdates.mem_peak ||
previewJobUpdates.stream_offset)
) {
callbacks?.change?.(job)
}
}
async function loadTestJob(id: string, callbacks?: Callbacks): Promise<boolean> {
let isCompleted = false
if (isCurrentJob(id)) {
try {
if (job && `running` in job) {
callbacks?.running?.({ id })
refreshLogOffset()
let previewJobUpdates = await JobService.getJobUpdates({
workspace: workspace!,
id,
running: job.running,
logOffset: logOffset,
streamOffset: resultStreamOffset,
getProgress: false
})
if ((previewJobUpdates.running ?? false) || (previewJobUpdates.completed ?? false)) {
job = await JobService.getJob({
workspace: workspace!,
id,
noCode,
noLogs: onlyResult || noLogs
})
callbacks?.change?.(job)
}
updateJobFromProgress(previewJobUpdates, job, callbacks)
} else {
job = await JobService.getJob({
workspace: workspace!,
id,
noLogs: onlyResult || noLogs,
noCode
})
}
jobUpdateLastFetch = new Date()
if (job?.type === 'CompletedJob') {
//only CompletedJob has success property
isCompleted = true
if (onlyResult) {
callbacks?.doneResult?.({
id,
result: job?.result
})
clearCurrentId()
} else {
onJobCompleted(id, job, callbacks)
}
}
notfound = false
} catch (err) {
errorIteration += 1
if (errorIteration == 5) {
notfound = true
job = undefined
clearCurrentId()
}
callbacks?.doneError?.({ error: err, id })
console.warn(err)
}
return isCompleted
} else {
return true
}
}
let currentEventSource: EventSource | undefined = undefined
async function onJobCompleted(
id: string,
job: Job & { result?: any; success?: boolean },
callbacks?: Callbacks
) {
if (isCurrentJob(id)) {
await tick()
if (
callbacks?.doneError &&
!job?.success &&
typeof job?.result == 'object' &&
'error' in (job?.result ?? {})
) {
callbacks?.doneError?.({
id,
error: job.result.error
})
} else {
callbacks?.done?.(job)
}
callbacks?.change?.(job)
clearCurrentId()
lastCompletedJobId = id
}
}
function setNoPingTimeout(id: string, attempt: number, callbacks?: Callbacks) {
if (noPingTimeout) {
clearTimeout(noPingTimeout)
}
if (isCurrentJob(id)) {
noPingTimeout = setTimeout(() => {
if (isCurrentJob(id)) {
currentEventSource?.close()
currentEventSource = undefined
loadTestJobWithSSE(id, attempt + 1, callbacks)
}
}, 10000)
}
}
function isCurrentJob(id: string) {
return currentId === id || (allowConcurentRequests && !finished.includes(id))
}
async function loadTestJobWithSSE(
id: string,
attempt: number,
callbacks?: Callbacks
): Promise<boolean> {
let isCompleted = false
let resultOnlyResultStream: string = ''
if (isCurrentJob(id)) {
try {
// First load the job to get initial state
if ((!job || job.id == '') && !onlyResult) {
job = await JobService.getJob({
workspace: workspace!,
id,
noLogs: noLogs,
noCode
})
callbacks?.change?.(job)
getActiveRecording()?.recordInitialJob(id, job)
}
if (!onlyResult) {
callbacks?.resultStreamUpdate?.({
id,
result_stream: undefined
})
}
// If job is already completed, don't start SSE
if (job?.type === 'CompletedJob') {
isCompleted = true
if (isCurrentJob(id)) {
onJobCompleted(id, job, callbacks)
}
return isCompleted
} else if (onlyResult || (job?.type === 'QueuedJob' && !currentEventSource)) {
if (job?.type === 'QueuedJob' && job?.running) {
callbacks?.running?.({ id })
if (!job.running) {
job.running = true
}
}
let getProgress: boolean | undefined =
onlyResult || !job
? undefined
: job.job_kind == 'script' || isScriptPreview(job.job_kind)
refreshLogOffset()
// Build SSE URL with query parameters
const params = new URLSearchParams({
log_offset: logOffset.toString()
})
if (job && job.type === 'QueuedJob') {
params.set('running', job.running.toString())
} else if (onlyResult && callbacks?.running) {
params.set('running', 'false')
}
if (getProgress !== undefined) {
params.set('get_progress', getProgress.toString())
}
if (onlyResult) {
params.set('only_result', 'true')
}
if (startedWatchingJob && startedWatchingJob > Date.now() - 5000) {
params.set('fast', 'true')
}
if (noLogs) {
params.set('no_logs', 'true')
}
if (resultStreamOffset) {
params.set('stream_offset', resultStreamOffset.toString())
}
if (job) {
params.set(
'is_flow',
(job.job_kind === 'flow' || job.job_kind === 'flowpreview').toString()
)
}
if (token?.token && token.token != '') {
params.set('token', token.token)
}
const sseUrl = `/api/w/${workspace}/jobs_u/getupdate_sse/${id}?${params.toString()}`
currentEventSource = new EventSource(sseUrl)
setNoPingTimeout(id, attempt, callbacks)
currentEventSource.onmessage = async (event) => {
if (!isCurrentJob(id)) {
currentEventSource?.close()
currentEventSource = undefined
return
}
try {
const previewJobUpdates = JSON.parse(event.data)
let type = previewJobUpdates.type
if (type == 'timeout') {
currentEventSource?.close()
currentEventSource = undefined
loadTestJobWithSSE(id, 0, callbacks)
return
} else if (type == 'ping') {
setNoPingTimeout(id, attempt, callbacks)
return
} else if (type == 'error') {
currentEventSource?.close()
currentEventSource = undefined
console.error('SSE error:', previewJobUpdates)
throw new Error('SSE error: ' + previewJobUpdates)
} else if (type == 'not_found') {
currentEventSource?.close()
currentEventSource = undefined
console.error('Not found')
throw new Error('Not found')
}
jobUpdateLastFetch = new Date()
getActiveRecording()?.recordEvent(id, previewJobUpdates)
if (job) {
updateJobFromProgress(previewJobUpdates, job, callbacks)
} else if (onlyResult && callbacks?.running && previewJobUpdates.running) {
callbacks?.running?.({ id })
}
if (onlyResult && previewJobUpdates.new_result_stream) {
resultOnlyResultStream = resultOnlyResultStream.concat(
previewJobUpdates.new_result_stream
)
// console.log('resultOnlyResultStream', resultOnlyResultStream)
callbacks?.resultStreamUpdate?.({
id,
result_stream: resultOnlyResultStream
})
}
// Check if job is completed
if (previewJobUpdates.completed) {
currentEventSource?.close()
currentEventSource = undefined
if (noPingTimeout) {
clearTimeout(noPingTimeout)
noPingTimeout = undefined
}
isCompleted = true
if (onlyResult) {
callbacks?.doneResult?.({
id,
result: previewJobUpdates?.only_result
})
clearCurrentId()
} else {
const njob = previewJobUpdates.job as Job & { result_stream?: string }
njob.logs = job?.logs ?? ''
njob.result_stream = job?.result_stream ?? ''
job = njob
onJobCompleted(id, job, callbacks)
}
}
} catch (parseErr) {
console.warn('Failed to parse SSE data:', parseErr)
}
}
currentEventSource.onerror = (error) => {
console.warn('SSE error:', error)
currentEventSource?.close()
currentEventSource = undefined
let delay = 1000
let isNoLogsChange = error.type == noLogsChangeRestartEvent
if (isNoLogsChange) {
delay = 0
}
if (attempt < 3 || isNoLogsChange) {
if (!isNoLogsChange) {
console.log(`SSE error (1), retrying ... attempt: ${attempt + 1}/3`)
}
setTimeout(() => loadTestJobWithSSE(id, attempt + 1, callbacks), delay)
} else {
// Fall back to polling on error
setTimeout(() => syncer(id, callbacks), 1000)
}
}
currentEventSource.onopen = () => {
console.log('SSE connection opened for job:', id)
}
}
notfound = false
} catch (err) {
errorIteration += 1
if (errorIteration == 5) {
notfound = true
job = undefined
}
console.warn(err)
// Fall back to polling on error
currentEventSource?.close()
currentEventSource = undefined
if (attempt < 3) {
console.log(`SSE error (2), retrying ... attempt: ${attempt}/3`)
attempt++
loadTestJobWithSSE(id, attempt, callbacks)
} else {
// Fall back to polling on error
setTimeout(() => syncer(id, callbacks), 1000)
}
}
return isCompleted
} else {
// Clean up SSE connection if current ID changed
currentEventSource?.close()
currentEventSource = undefined
return true
}
}
async function syncer(id: string, callbacks?: Callbacks): Promise<void> {
if (!isCurrentJob(id)) {
callbacks?.cancel?.({ id })
return
}
syncIteration++
if (await loadTestJob(id, callbacks)) {
return
}
let nextIteration = 50
if (syncIteration > ITERATIONS_BEFORE_SLOW_REFRESH) {
nextIteration = 500
} else if (syncIteration > ITERATIONS_BEFORE_SUPER_SLOW_REFRESH) {
nextIteration = 2000
}
setTimeout(() => syncer(id, callbacks), nextIteration)
}
onDestroy(async () => {
clearCurrentId()
currentEventSource?.close()
currentEventSource = undefined
replayTimeouts.forEach(clearTimeout)
replayTimeouts = []
})
</script>
{@render children?.({
job,
isLoading,
workspaceOverride,
notfound,
abstractRun,
runScriptByPath,
runFlowByPath,
runPreview,
cancelJob,
clearCurrentJob,
watchJob,
loadTestJob,
syncer
})}