feat: resolved runs on home, an easier resolve action, and load fades (#12167)

* feat: show resolved failures on home recent runs and surface the resolve action

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

* fix: read failed run ids on resolve click instead of in the polled response

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

* feat: show a loader while recent runs load for the first time

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

* fix: show a failed recent runs load and keep only the newest response

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

* feat: fade in home content that lands after an api response

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

* fix: pass each cookie through the pages preview proxy on its own

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

* fix: take an item's failed run ids from the recent runs endpoint

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Ruben Fiszel
2026-11-03 06:43:21 +01:00
committed by GitHub
co-authored by Claude Opus 5.5
parent e4d74a3c97
commit 1a6e5440ba
13 changed files with 489 additions and 191 deletions
+113 -3
View File
@@ -1,5 +1,6 @@
//! `jobs/recent_runs` aggregates over the workspace through `user_db`, which applies RLS but not a
//! token's `if_jobs:filter_tags` scope: the handler has to filter on it itself.
//! `jobs/recent_runs`: it aggregates over the workspace through `user_db`, which applies RLS but
//! not a token's `if_jobs:filter_tags` scope, so the handler filters on it itself; and it reports a
//! resolved failure apart from an unresolved one.
use sqlx::{Pool, Postgres};
use windmill_test_utils::*;
@@ -9,9 +10,13 @@ const DENO_JOB: &str = "14141414-1414-1414-1414-141414141414";
const FLOW_JOB: &str = "15151515-1515-1515-1515-151515151515";
async fn recent_runs(port: u16, token: &str) -> String {
recent_runs_query(port, token, "").await
}
async fn recent_runs_query(port: u16, token: &str, query: &str) -> String {
let resp = reqwest::Client::new()
.get(format!(
"http://localhost:{port}/api/w/test-workspace/jobs/recent_runs"
"http://localhost:{port}/api/w/test-workspace/jobs/recent_runs{query}"
))
.header("Authorization", format!("Bearer {token}"))
.send()
@@ -37,3 +42,108 @@ async fn test_recent_runs_honors_tag_scope(db: Pool<Postgres>) -> anyhow::Result
assert!(!scoped.contains(FLOW_JOB), "{scoped}");
Ok(())
}
async fn insert_root_run(
db: &Pool<Postgres>,
id: &str,
status: &str,
resolved: bool,
) -> anyhow::Result<()> {
sqlx::query(
"INSERT INTO v2_job (id, workspace_id, created_by, permissioned_as, permissioned_as_email,
kind, script_lang, runnable_path, tag, visible_to_owner)
VALUES ($1::uuid, 'test-workspace', 'test-user-2', 'u/test-user-2', 'test2@windmill.dev',
'script', 'deno', 'u/test-user-2/flaky', 'deno', true)",
)
.bind(id)
.execute(db)
.await?;
sqlx::query(
"INSERT INTO v2_job_completed (id, workspace_id, duration_ms, status)
VALUES ($1::uuid, 'test-workspace', 10, $2::job_status)",
)
.bind(id)
.bind(status)
.execute(db)
.await?;
if resolved {
sqlx::query(
"INSERT INTO job_resolution (job_id, workspace_id) VALUES ($1::uuid, 'test-workspace')",
)
.bind(id)
.execute(db)
.await?;
}
Ok(())
}
/// A resolved failure is `resolved`, not `failure`: Home's failed counts leave it out, and the
/// failed ids asked for one item are the failures that item counts.
#[sqlx::test(fixtures("base", "jobs_read_auth"))]
async fn test_recent_runs_resolved_failures(db: Pool<Postgres>) -> anyhow::Result<()> {
initialize_tracing().await;
insert_root_run(&db, "a0000000-0000-0000-0000-000000000001", "failure", true).await?;
insert_root_run(&db, "a0000000-0000-0000-0000-000000000002", "failure", false).await?;
insert_root_run(&db, "a0000000-0000-0000-0000-000000000003", "canceled", true).await?;
// A failed single-step flow wrapping a flow at the same path: the flow's failure, not the
// script's, though a job listing by path and kind cannot tell them apart.
sqlx::query(
"INSERT INTO v2_job (id, workspace_id, created_by, permissioned_as, permissioned_as_email,
kind, script_lang, runnable_path, tag, visible_to_owner, raw_flow)
VALUES ('a0000000-0000-0000-0000-000000000004', 'test-workspace', 'test-user-2',
'u/test-user-2', 'test2@windmill.dev', 'singlestepflow', 'deno', 'u/test-user-2/flaky',
'deno', true,
'{\"modules\": [{\"id\": \"a\", \"value\": {\"type\": \"flow\", \"path\": \"u/test-user-2/flaky\"}}]}')",
)
.execute(&db)
.await?;
sqlx::query(
"INSERT INTO v2_job_completed (id, workspace_id, duration_ms, status)
VALUES ('a0000000-0000-0000-0000-000000000004', 'test-workspace', 10, 'failure')",
)
.execute(&db)
.await?;
let server = ApiServer::start(db.clone()).await?;
let body: serde_json::Value = serde_json::from_str(
&recent_runs_query(
server.addr.port(),
"SECRET_TOKEN_2",
"?failed_ids_kind=script&failed_ids_path=u/test-user-2/flaky",
)
.await,
)?;
let item = body["items"]
.as_array()
.unwrap()
.iter()
.find(|i| i["path"] == "u/test-user-2/flaky" && i["kind"] == "script")
.expect("item");
let status_of = |id: &str| {
item["runs"]
.as_array()
.unwrap()
.iter()
.find(|r| r["id"] == id)
.map(|r| r["status"].clone())
};
assert_eq!(status_of("a0000000-0000-0000-0000-000000000001"), Some("resolved".into()));
assert_eq!(status_of("a0000000-0000-0000-0000-000000000002"), Some("failure".into()));
assert_eq!(status_of("a0000000-0000-0000-0000-000000000003"), Some("canceled".into()));
assert_eq!(item["failed_runs"], 1, "{body}");
// Only the item named in the query carries its ids, and they are its own unresolved failures.
assert_eq!(
item["failed_run_ids"],
serde_json::json!(["a0000000-0000-0000-0000-000000000002"]),
"{body}"
);
let flow = body["items"]
.as_array()
.unwrap()
.iter()
.find(|i| i["path"] == "u/test-user-2/flaky" && i["kind"] == "flow")
.expect("flow item");
assert!(flow.get("failed_run_ids").is_none(), "{body}");
assert_eq!(body["failed_runs"], 2, "{body}");
Ok(())
}
+20 -2
View File
@@ -18049,6 +18049,17 @@ paths:
in: query
schema:
type: string
- name: failed_ids_kind
description: with failed_ids_path, the item whose unresolved failed run ids to list in failed_run_ids
in: query
schema:
type: string
enum: [script, flow, agent]
- name: failed_ids_path
description: with failed_ids_kind, the path of that item
in: query
schema:
type: string
responses:
"200":
description: runs that completed in the window or are running, grouped by item, newest run first
@@ -18085,8 +18096,14 @@ paths:
status:
$ref: "#/components/schemas/RecentRunStatus"
failed_runs:
description: failed runs of the item over the whole window, not only those in runs
description: unresolved failed runs of the item over the whole window, not only those in runs
type: integer
failed_run_ids:
description: the ids of those failed runs, only for the item named by failed_ids_kind and failed_ids_path
type: array
items:
type: string
format: uuid
runs:
type: array
items:
@@ -33456,8 +33473,9 @@ components:
- has_preprocessor
RecentRunStatus:
description: a failure someone or something marked as handled is `resolved`, not `failure`
type: string
enum: [success, failure, canceled, running]
enum: [success, failure, resolved, canceled, running]
ScriptLang:
type: string
+20 -4
View File
@@ -41,6 +41,10 @@ const LISTED_ROOT_RUN: &str = "j.workspace_id = $1
#[derive(Deserialize)]
pub(crate) struct RecentRunsQuery {
folder: Option<String>,
/// With `failed_ids_path`: list that item's unresolved failures in `failed_run_ids`. Only on
/// request, since a constantly failing item would put thousands of ids in every poll.
failed_ids_kind: Option<String>,
failed_ids_path: Option<String>,
}
#[derive(Serialize)]
@@ -61,8 +65,11 @@ pub(crate) struct RecentRunItem {
summary: Option<String>,
/// The status of the item's newest run.
status: String,
/// Over the whole window, not only the runs listed.
/// Unresolved failures over the whole window, not only the runs listed.
failed_runs: i64,
/// Their ids, for the item named by the query's `failed_ids_*` only.
#[serde(skip_serializing_if = "Option::is_none")]
failed_run_ids: Option<Vec<uuid::Uuid>>,
/// Newest first.
runs: Vec<RecentRun>,
}
@@ -92,6 +99,7 @@ pub(crate) async fn list_recent_runs(
.folder
.filter(|f| !f.is_empty())
.map(|f| format!("f/{f}/"));
let failed_ids_of = q.failed_ids_kind.zip(q.failed_ids_path);
let mut tx = user_db.begin(&authed).await?;
// A run counts when it completed in the window or is running now, whenever it was queued:
@@ -140,6 +148,7 @@ pub(crate) async fn list_recent_runs(
CASE WHEN r.status IS NULL THEN 'running'
WHEN r.status IN ('success', 'skipped') THEN 'success'
WHEN r.status = 'canceled' THEN 'canceled'
WHEN EXISTS (SELECT 1 FROM job_resolution jr WHERE jr.job_id = r.id) THEN 'resolved'
ELSE 'failure' END AS status,
COALESCE(r.started_at, j.created_at) AS ran_at,
r.duration_ms,
@@ -166,10 +175,16 @@ pub(crate) async fn list_recent_runs(
let mut items: Vec<RecentRunItem> = vec![];
let mut index: HashMap<(String, String), usize> = HashMap::new();
for run in runs {
let failed = (run.status == "failure") as i64;
let failed = run.status == "failure";
let wanted = failed_ids_of
.as_ref()
.is_some_and(|(k, p)| *k == run.kind && *p == run.path);
match index.get(&(run.kind.clone(), run.path.clone())) {
Some(&i) => {
items[i].failed_runs += failed;
items[i].failed_runs += failed as i64;
if failed && wanted {
items[i].failed_run_ids.get_or_insert_with(Vec::new).push(run.id);
}
if items[i].runs.len() < RUNS_PER_ITEM {
items[i].runs.push(run);
}
@@ -181,7 +196,8 @@ pub(crate) async fn list_recent_runs(
kind: run.kind.clone(),
summary: None,
status: run.status.clone(),
failed_runs: failed,
failed_runs: failed as i64,
failed_run_ids: wanted.then(|| if failed { vec![run.id] } else { vec![] }),
runs: vec![run],
});
}
@@ -244,81 +244,96 @@
{#snippet forkAction()}
{@const total = comparison?.summary.total_diffs ?? 0}
{@const conflicts = comparison?.summary.conflicts ?? 0}
{@const status = loading
? 'loading'
: error
? 'error'
: showDraftsOnly
? 'drafts'
: total > 0
? 'drift'
: undefined}
<!-- What the comparison has to say is a mark beside the button, never instead of it: a fork
still being counted, or one whose count failed, is exactly when a reader wants the page
that does the counting properly. The button below renders in every state. -->
{#if loading}
<span class="text-2xs text-tertiary">Checking for changes…</span>
{:else if error}
<span class="text-2xs text-red-600 dark:text-red-400" title={error}>Comparison failed</span>
{:else if showDraftsOnly}
<Badge color="blue" small>
{draftCount} draft{draftCount !== 1 ? 's' : ''}
</Badge>
{:else if total > 0}
<!-- Which way the drift goes is the thing to know at a glance: ahead is what this fork has
to give its parent, behind is what it has yet to take. -->
<!-- The colours and the icons the compare page gives these three, so the counts in the bar
and the rows behind the button say the same thing the same way. -->
{#if changesAhead > 0}
<Badge
color="green"
small
clickable
onclick={() => openCompareDir('deploy_to')}
title="{changesAhead} ahead of {parentWorkspaceId} — review what this {currentNoun} has to give"
>
<ArrowUp class="w-3 h-3 inline" />
{changesAhead}{compactCounts ? '' : ' ahead'}
</Badge>
{/if}
{#if changesBehind > 0}
<Badge
color="blue"
small
clickable
onclick={() => openCompareDir('update')}
title="{changesBehind} behind {parentWorkspaceId} — review what this {currentNoun} has yet to take"
>
<ArrowDown class="w-3 h-3 inline" />
{changesBehind}{compactCounts ? '' : ' behind'}
</Badge>
{/if}
{#if conflicts > 0}
<!-- A conflict is ahead and behind at once, so it has no direction of its own; it opens
the side the reader resolves it from before deploying. -->
<Badge
color="orange"
small
clickable
onclick={() => openCompareDir('deploy_to')}
title="{conflicts} conflicting item{conflicts !== 1 ? 's' : ''} — review them"
>
<AlertTriangle class="w-3 h-3 inline" />
{conflicts}{compactCounts ? '' : ` conflict${conflicts !== 1 ? 's' : ''}`}
</Badge>
{/if}
<!-- Drafts are a different axis from the drift beside them: ahead and behind count deployed
items against the parent, this counts work in this fork that is not deployed anywhere
yet. It shares blue with "behind" and is told apart by the pencil and by naming what it
counts, rather than by an arrow that would read as a third direction. Clicking goes to
the drafts half of the compare page rather than the drawer the button opens. It shows at
every drift — a fork both behind and holding drafts said nothing about the drafts. -->
{#if draftCount > 0}
<Badge
color="blue"
small
clickable
onclick={openDraftCompare}
title="{draftCount} draft{draftCount !== 1
? 's'
: ''} in this {currentNoun}, not deployed anywhere yet — review and deploy"
>
<Pencil class="w-3 h-3 inline" />
{draftCount}{compactCounts ? '' : ` draft${draftCount !== 1 ? 's' : ''}`}
</Badge>
{/if}
{/if}
<!-- Keyed on what it says, so each answer the comparison lands with fades in rather than
popping into a bar that is already showing. -->
{#key status}
<span class="flex items-center gap-2 wm-page-in" class:hidden={!status}>
{#if loading}
<span class="text-2xs text-tertiary">Checking for changes…</span>
{:else if error}
<span class="text-2xs text-red-600 dark:text-red-400" title={error}>Comparison failed</span>
{:else if showDraftsOnly}
<Badge color="blue" small>
{draftCount} draft{draftCount !== 1 ? 's' : ''}
</Badge>
{:else if total > 0}
<!-- Which way the drift goes is the thing to know at a glance: ahead is what this fork has
to give its parent, behind is what it has yet to take. -->
<!-- The colours and the icons the compare page gives these three, so the counts in the bar
and the rows behind the button say the same thing the same way. -->
{#if changesAhead > 0}
<Badge
color="green"
small
clickable
onclick={() => openCompareDir('deploy_to')}
title="{changesAhead} ahead of {parentWorkspaceId} — review what this {currentNoun} has to give"
>
<ArrowUp class="w-3 h-3 inline" />
{changesAhead}{compactCounts ? '' : ' ahead'}
</Badge>
{/if}
{#if changesBehind > 0}
<Badge
color="blue"
small
clickable
onclick={() => openCompareDir('update')}
title="{changesBehind} behind {parentWorkspaceId} — review what this {currentNoun} has yet to take"
>
<ArrowDown class="w-3 h-3 inline" />
{changesBehind}{compactCounts ? '' : ' behind'}
</Badge>
{/if}
{#if conflicts > 0}
<!-- A conflict is ahead and behind at once, so it has no direction of its own; it opens
the side the reader resolves it from before deploying. -->
<Badge
color="orange"
small
clickable
onclick={() => openCompareDir('deploy_to')}
title="{conflicts} conflicting item{conflicts !== 1 ? 's' : ''} — review them"
>
<AlertTriangle class="w-3 h-3 inline" />
{conflicts}{compactCounts ? '' : ` conflict${conflicts !== 1 ? 's' : ''}`}
</Badge>
{/if}
<!-- Drafts are a different axis from the drift beside them: ahead and behind count deployed
items against the parent, this counts work in this fork that is not deployed anywhere
yet. It shares blue with "behind" and is told apart by the pencil and by naming what it
counts, rather than by an arrow that would read as a third direction. Clicking goes to
the drafts half of the compare page rather than the drawer the button opens. It shows at
every drift — a fork both behind and holding drafts said nothing about the drafts. -->
{#if draftCount > 0}
<Badge
color="blue"
small
clickable
onclick={openDraftCompare}
title="{draftCount} draft{draftCount !== 1
? 's'
: ''} in this {currentNoun}, not deployed anywhere yet — review and deploy"
>
<Pencil class="w-3 h-3 inline" />
{draftCount}{compactCounts ? '' : ` draft${draftCount !== 1 ? 's' : ''}`}
</Badge>
{/if}
{/if}
</span>
{/key}
{#if showDraftsOnly}
<Button
variant="subtle"
@@ -55,6 +55,7 @@
the bar has room for one thing. -->
{#if phone}
<Button
btnClasses="wm-page-in"
variant="subtle"
unifiedSize="sm"
onclick={openDraftCompare}
@@ -63,11 +64,14 @@
<Badge color="blue" small>{draftCount}</Badge>
</Button>
{:else}
<Badge color="blue" small>
{draftCount} draft{draftCount !== 1 ? 's' : ''}
</Badge>
<Button variant="subtle" unifiedSize="sm" onclick={openDraftCompare}>
Review & deploy drafts
</Button>
<!-- Fades in: the count lands after the bar it joins has already painted. -->
<span class="flex items-center gap-2 wm-page-in">
<Badge color="blue" small>
{draftCount} draft{draftCount !== 1 ? 's' : ''}
</Badge>
<Button variant="subtle" unifiedSize="sm" onclick={openDraftCompare}>
Review & deploy drafts
</Button>
</span>
{/if}
{/snippet}
@@ -1138,13 +1138,15 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
{/if}
{/snippet}
{#snippet toolbar()}
<!-- Its rows fade in (`wm-page-in`): they land with the copilot config, after the
box Home's skeleton already drew. -->
<div
class="flex flex-row flex-wrap items-center gap-x-1.5 gap-y-1"
class:justify-between={showFooterLeftControls}
class:justify-end={!showFooterLeftControls}
>
{#if showFooterLeftControls}
<div class="flex flex-row items-center gap-x-1.5 min-w-0 flex-wrap">
<div class="flex flex-row items-center gap-x-1.5 min-w-0 flex-wrap wm-page-in">
{#if showContextPicker && !disabled}
<Popover placement="bottom-start">
{#snippet trigger()}
@@ -1385,11 +1387,11 @@ the panel, or the Escape-to-stop focus check would wrongly reject them. -->
</div>
{/if}
{#if footerMessageShown}
<div class="text-primary text-xs my-2 px-2">
<div class="text-primary text-xs my-2 px-2 wm-page-in">
<Markdown md={disabledMessage} />
</div>
{:else}
<div class="flex flex-row gap-x-1.5 min-w-0 flex-wrap items-center">
<div class="flex flex-row gap-x-1.5 min-w-0 flex-wrap items-center wm-page-in">
{#if chatHost.mode === AIMode.GLOBAL}
<AttachedFilesBar />
{/if}
@@ -1,8 +1,9 @@
<script lang="ts">
import { goto } from '$app/navigation'
import { workspaceStore } from '$lib/stores'
import { CircleCheck, CircleSlash, CircleX, Loader2 } from 'lucide-svelte'
import { CircleCheck, CircleSlash, CircleX, Loader2, Wrench } from 'lucide-svelte'
import { Button } from '$lib/components/common'
import { useRoleCapabilities } from '$lib/operatorWriteRights'
import {
askAI,
canAskAI,
@@ -23,9 +24,14 @@
/** What a click on the row does; without it the row opens the item's page. The run links
* open runs either way. */
onSelect?: (item: RecentRunItem) => void
/** Resolves the item's failed runs; without it the row offers no resolve action. */
onResolve?: (item: RecentRunItem) => Promise<void>
}
let { item, now, prefix, strip = true, onSelect }: Props = $props()
let { item, now, prefix, strip = true, onSelect, onResolve }: Props = $props()
const roleCaps = useRoleCapabilities()
let resolving = $state(false)
const STRIP_SLOTS = 10
// The strip reads oldest to newest; the item's runs arrive newest first.
@@ -43,12 +49,14 @@
const statusLabel = {
success: 'Succeeded',
failure: 'Failed',
resolved: 'Failed, resolved',
canceled: 'Canceled',
running: 'Running'
}
const barClass = {
success: 'bg-green-500 dark:bg-green-600',
failure: 'bg-red-500 dark:bg-red-600',
resolved: 'bg-orange-300 dark:bg-orange-700',
canceled: 'bg-gray-400 dark:bg-gray-500',
running: 'bg-yellow-500'
}
@@ -93,6 +101,8 @@
<Loader2 size={14} class="animate-spin text-yellow-500" />
{:else if failing}
<CircleX size={14} class="text-red-500" />
{:else if item.status === 'resolved'}
<span class="text-orange-500" title="Failed, marked as resolved"><Wrench size={14} /></span>
{:else if item.status === 'canceled'}
<CircleSlash size={14} class="text-hint" />
{:else}
@@ -114,6 +124,31 @@
number comes from. -->
{#if item.failed_runs > 0}
<span class="shrink-0 text-red-600 dark:text-red-400">{item.failed_runs} failed</span>
{#if onResolve && $roleCaps.code}
<!-- Negative margins keep the button's height from growing the row on hover. -->
<span
class="hidden group-hover:inline-flex group-focus-within:inline-flex shrink-0 -my-[3px]"
>
<Button
variant="subtle"
unifiedSize="2xs"
btnClasses="!text-accent !text-[10.5px] !px-1 font-medium"
title="Mark the {item.failed_runs} failed runs of {title} as handled"
loading={resolving}
onClick={async (e) => {
e?.stopPropagation()
resolving = true
try {
await onResolve(item)
} finally {
resolving = false
}
}}
>
{item.failed_runs === 1 ? 'Resolve' : 'Resolve all'}
</Button>
</span>
{/if}
{/if}
{#if failing && canAskAI() && latest}
<button
@@ -1,7 +1,7 @@
<script lang="ts">
import Popover from '$lib/components/meltComponents/Popover.svelte'
import { Button } from '$lib/components/common'
import { ChevronDown, ExternalLink, PanelRightOpen, Play } from 'lucide-svelte'
import { Button, Skeleton } from '$lib/components/common'
import { ChevronDown, ExternalLink, Loader2, PanelRightOpen, Play } from 'lucide-svelte'
import RecentRunRow from './RecentRunRow.svelte'
import {
allRunsHref,
@@ -66,6 +66,9 @@
</span>
{:else}
<span>{data ? totalLabel(data) : 'Recent runs'}</span>
{#if !data && runs.loading}
<Loader2 size={12} class="animate-spin text-hint" />
{/if}
{#if data && data.failed_runs > 0}
<span class="flex items-center gap-1.5 text-red-600 dark:text-red-400">
<span class="w-[7px] h-[7px] rounded-full bg-red-500"></span>
@@ -120,6 +123,7 @@
{item}
now={runs.now}
prefix={prefixes.get(itemKey(item))}
onResolve={runs.resolveFailures}
strip={false}
onSelect={onFocusItem &&
((item) => {
@@ -140,6 +144,13 @@
{data.items.length - MAX_ITEMS} more
</a>
{/if}
{:else if runs.loading}
<Skeleton class="px-2.5 pt-2" layout={[[2.5], 0.25, [2.5], 0.25, [2.5]]} />
{:else if runs.failed}
<p class="flex items-center gap-1 px-2.5 pt-2 text-secondary text-[12.5px]">
Could not load recent runs.
<Button variant="subtle" unifiedSize="xs" onClick={() => runs.retry()}>Retry</Button>
</p>
{/if}
<div
@@ -1,5 +1,5 @@
<script lang="ts">
import { Button } from '$lib/components/common'
import { Button, Skeleton } from '$lib/components/common'
import { ExternalLink, PanelRightClose } from 'lucide-svelte'
import RecentRunRow from './RecentRunRow.svelte'
import {
@@ -24,6 +24,8 @@
let { runs, folder, onCollapse, onFocusItem }: Props = $props()
let data = $derived(runs.current)
// Rows' height (2.5 × 16px) with their gap: without it a first load reads as "nothing ran".
const LOADING_LAYOUT = [[2.5], 0.25, [2.5], 0.25, [2.5]]
// The failed count also holds runs an item has since recovered from; Ask AI attaches only
// the items still failing, so it shows only when there is one.
let failing = $derived(data?.items.filter((i) => i.status === 'failure') ?? [])
@@ -42,7 +44,7 @@
{/if}
{#if data}
<span
class="relative min-w-0 truncate text-xs font-normal text-hint"
class="relative min-w-0 truncate text-xs font-normal text-hint wm-page-in"
title="{windowText} · {totalLabel(data)} · {data.failed_runs} failed"
>
{#if data.failed_runs > 0}
@@ -88,17 +90,28 @@
</div>
<div class="flex-1 min-h-0 overflow-y-auto overscroll-contain -mx-2.5">
{#if data && data.items.length === 0}
{#if !data && runs.loading}
<Skeleton class="px-2.5" layout={LOADING_LAYOUT} />
{:else if !data && runs.failed}
<p class="flex items-center gap-1 px-2.5 text-xs text-hint">
Could not load recent runs.
<Button variant="subtle" unifiedSize="xs" onClick={() => runs.retry()}>Retry</Button>
</p>
{:else if data && data.items.length === 0}
<p class="px-2.5 text-xs text-hint">Runs show up here once something runs.</p>
{:else if data}
{#each data.items as item (itemKey(item))}
<RecentRunRow
{item}
now={runs.now}
prefix={prefixes.get(itemKey(item))}
onSelect={onFocusItem}
/>
{/each}
<!-- Fades in once, when the first read lands; refreshes update the rows in place. -->
<div class="wm-page-in">
{#each data.items as item (itemKey(item))}
<RecentRunRow
{item}
now={runs.now}
prefix={prefixes.get(itemKey(item))}
onResolve={runs.resolveFailures}
onSelect={onFocusItem}
/>
{/each}
</div>
{/if}
</div>
</div>
@@ -1,5 +1,6 @@
import { JobService, type ListRecentRunsResponse } from '$lib/gen'
import { getLocalSetting, storeLocalSetting } from '$lib/utils'
import { getLocalSetting, MAX_RESOLUTION_BATCH, storeLocalSetting } from '$lib/utils'
import { sendUserToast } from '$lib/toast'
import { IsDocumentVisible, useInterval } from 'runed'
import { persistedResource } from '$lib/persistedResource.svelte'
import { homeComposerContext } from '$lib/components/sessions/homeComposerContext.svelte'
@@ -30,7 +31,7 @@ export function useRecentRuns(
workspace && enabled ? await JobService.listRecentRuns({ workspace, folder }) : undefined,
{
name: 'recent_runs',
version: 1,
version: 2,
scope: ({ workspace, folder, enabled }) =>
workspace && enabled ? { workspace, args: { folder } } : undefined
}
@@ -49,8 +50,49 @@ export function useRecentRuns(
get current() {
return runs.current
},
/** A read is in flight; with no `current` yet, nothing is known about the window. */
get loading() {
return runs.loading
},
/** The latest read failed: with no `current`, the panel would otherwise read as empty. */
get failed() {
return runs.error !== undefined
},
retry() {
if (!runs.loading) runs.refetch()
},
get now() {
return now
},
/** Marks every unresolved failure of `item` in the window as resolved. */
async resolveFailures(item: RecentRunItem) {
const { workspace, folder } = args()
if (!workspace) return
let resolved = 0
try {
// Read on click, for this item only: the endpoint files each run under its item the
// way the row counts it, which a job listing cannot (a `singlestepflow` wraps a script
// or a flow).
const read = await JobService.listRecentRuns({
workspace,
folder,
failedIdsKind: item.kind,
failedIdsPath: item.path
})
const ids =
read.items.find((i) => i.kind === item.kind && i.path === item.path)?.failed_run_ids ?? []
for (let i = 0; i < ids.length; i += MAX_RESOLUTION_BATCH) {
const affected = await JobService.resolveCompletedJobs({
workspace,
requestBody: { job_ids: ids.slice(i, i + MAX_RESOLUTION_BATCH) }
})
resolved += affected.length
}
sendUserToast(`Resolved ${resolved} failed run${resolved === 1 ? '' : 's'}`)
} catch (e) {
sendUserToast(`Could not resolve the failed runs: ${e}`, true)
}
runs.refetch()
}
}
}
@@ -14,7 +14,16 @@
import TimeAgo from '$lib/components/TimeAgo.svelte'
import { enterpriseLicense, userStore } from '$lib/stores'
import Tooltip from '$lib/components/meltComponents/Tooltip.svelte'
import { ExternalLink, ListFilter, ChevronDown, Share2, Link, Copy } from 'lucide-svelte'
import {
ExternalLink,
ListFilter,
ChevronDown,
Share2,
Link,
Copy,
CircleCheck,
Undo2
} from 'lucide-svelte'
import JobStatus from '$lib/components/JobStatus.svelte'
import JobStatusIcon from '$lib/components/runs/JobStatusIcon.svelte'
import RunBadges from '$lib/components/runs/RunBadges.svelte'
@@ -459,7 +468,9 @@
>
{#if job}
<!-- Header with status icon and two-row title/badges section -->
<div class="flex items-center gap-3 min-w-0 grow">
<!-- Wraps so the resolve button does not widen the card's min-content basis, which
would push the metadata grid beside it down to one column. -->
<div class="flex flex-wrap items-center gap-3 min-w-0 grow">
<!-- Status icon -->
<div class="flex-shrink-0">
<JobStatusIcon {job} roundedFull />
@@ -474,7 +485,8 @@
{@const isScript = job.job_kind === 'script'}
{@const viewHref = isScript
? `/${stem}/get/${job?.script_hash}`
: (agentRunHref(job, $operatingWorkspace) ?? flowPathToHref(job?.script_path ?? ''))}
: (agentRunHref(job, $operatingWorkspace) ??
flowPathToHref(job?.script_path ?? ''))}
<a
href={viewHref}
target="_blank"
@@ -501,67 +513,6 @@
<div class="flex items-baseline flex-wrap gap-x-2 gap-y-1">
<JobStatus {job} />
{#if isJobResolvable(job) && $roleCaps.code}
<!-- No startIcon on these: the row is baseline-aligned, and a Button is
itself a flex container whose baseline comes from its icon rather
than its label, which sits the text ~3px above the badges. Text
only keeps it on the badges' baseline exactly. -->
{#if job.resolved}
<Button
size="xs2"
variant="subtle"
disabled={togglingResolution}
onClick={() => setResolution(false)}
title="Show this run as unhandled again"
>
Unresolve
</Button>
{:else}
<Popover placement="bottom-start" usePointerDownOutside>
{#snippet trigger()}
<Button
size="xs2"
variant="subtle"
nonCaptureEvent
title="Mark this run as handled"
>
Mark resolved
</Button>
{/snippet}
{#snippet content({ close })}
<div class="p-3 flex flex-col gap-2 w-80">
<p class="text-xs text-secondary">
Resolving keeps the run's status but marks it as handled in the runs list.
</p>
<TextInput
bind:value={resolutionNote}
inputProps={{
placeholder: $enterpriseLicense
? 'Why is this handled? (optional)'
: 'Notes and attribution require ee',
disabled: !$enterpriseLicense
}}
size="sm"
/>
<div class="flex flex-row justify-end gap-2">
<Button size="xs2" variant="subtle" onClick={close}>Cancel</Button>
<Button
size="xs2"
variant="accent"
disabled={togglingResolution}
onClick={async () => {
if (await setResolution(true, resolutionNote)) close()
}}
>
Mark resolved
</Button>
</div>
</div>
{/snippet}
</Popover>
{/if}
{/if}
<RunBadges
{job}
{displayPersistentScriptDefinition}
@@ -573,6 +524,68 @@
/>
</div>
</div>
{#if isJobResolvable(job) && $roleCaps.code}
<div class="flex-shrink-0">
{#if job.resolved}
<Button
unifiedSize="sm"
variant="default"
startIcon={{ icon: Undo2 }}
disabled={togglingResolution}
onClick={() => setResolution(false)}
title="Show this run as unhandled again"
>
Unresolve
</Button>
{:else}
<Popover placement="bottom-start" usePointerDownOutside>
{#snippet trigger()}
<Button
unifiedSize="sm"
variant="default"
startIcon={{ icon: CircleCheck }}
btnClasses="!bg-green-100 !text-green-800 hover:!bg-green-200 !border-green-300 dark:!bg-green-700/40 dark:!text-green-100 dark:hover:!bg-green-700/60 dark:!border-green-700"
nonCaptureEvent
title="Mark this run as handled"
>
Mark resolved
</Button>
{/snippet}
{#snippet content({ close })}
<div class="p-3 flex flex-col gap-2 w-80">
<p class="text-xs text-secondary">
Resolving keeps the run's status but marks it as handled in the runs list.
</p>
<TextInput
bind:value={resolutionNote}
inputProps={{
placeholder: $enterpriseLicense
? 'Why is this handled? (optional)'
: 'Notes and attribution require ee',
disabled: !$enterpriseLicense
}}
size="sm"
/>
<div class="flex flex-row justify-end gap-2">
<Button unifiedSize="sm" variant="subtle" onClick={close}>Cancel</Button>
<Button
unifiedSize="sm"
variant="accent"
disabled={togglingResolution}
onClick={async () => {
if (await setResolution(true, resolutionNote)) close()
}}
>
Mark resolved
</Button>
</div>
</div>
{/snippet}
</Popover>
{/if}
</div>
{/if}
</div>
{/if}
</div>
+30 -8
View File
@@ -61,14 +61,32 @@ export function persistedResource<A, T>(
fetcher: (args: A) => Promise<T | undefined>,
opts: PersistOptions<A>
) {
// runed's `resource` neither orders overlapping requests nor ties `loading` to the newest:
// an older response landing last would replace the newer one, and the first to settle would
// end `loading` while a later request is still in flight. Only the latest request does either.
let latest = 0
let inFlight = $state(false)
let error = $state<unknown>(undefined)
const res = resource<A, Tagged<T>>(source, async (args) => {
const keys = keysFor(opts, args)
if (keys) void loadEntry(keys.key, opts.version)
const sentWith = readSessionHint()
const value = await fetcher(args)
if (keys && value !== undefined && sameSessionSince(sentWith))
saveEntry(keys.key, opts.version, value)
return { keys, value }
const id = ++latest
inFlight = true
try {
const keys = keysFor(opts, args)
if (keys) void loadEntry(keys.key, opts.version)
const sentWith = readSessionHint()
const value = await fetcher(args)
if (keys && value !== undefined && sameSessionSince(sentWith))
saveEntry(keys.key, opts.version, value)
// An AbortError is how runed is told to keep its value without recording an error.
if (id !== latest) throw new DOMException('superseded', 'AbortError')
error = undefined
return { keys, value }
} catch (e) {
if (id === latest) error = e
throw e
} finally {
if (id === latest) inFlight = false
}
})
const keys = $derived(keysFor(opts, source()))
const shown = $derived(
@@ -79,7 +97,11 @@ export function persistedResource<A, T>(
return shown
},
get loading() {
return res.loading
return inFlight
},
/** Why the latest request failed; cleared when one succeeds. */
get error() {
return error
},
refetch() {
return res.refetch()
+9 -12
View File
@@ -30,18 +30,15 @@ export async function onRequest(context) {
});
const newResponse = new Response(res.body, res);
// Extract domain from target hostname for cookie domain replacement
const targetDomain = targetHostname.split(".").slice(-2).join(".");
newResponse.headers.set(
"set-cookie",
"token" +
(newResponse.headers
.get("set-cookie")
?.replace(`Domain=${targetDomain};`, "")
?.split("token")
?.pop() ?? "")
);
// Each cookie is passed on by itself, without its Domain: the backend's (e.g.
// `windmill.dev`) does not match this host, and a browser drops a cookie whose Domain
// does not match. Reading them joined (`headers.get`) would merge the session cookie with
// the `wm_session` hint set beside it, Domain included.
const setCookies = res.headers.getSetCookie();
newResponse.headers.delete("set-cookie");
for (const c of setCookies) {
newResponse.headers.append("set-cookie", c.replace(/;\s*Domain=[^;]*/gi, ""));
}
newResponse.headers.set("Cross-Origin-Resource-Policy", "cross-origin");
return newResponse;