feat(workflows): test-run unsaved drafts and browse workflow version history
A test run pins a validated draft, runs with forge and push writes suppressed and recorded per step, and is excluded from workflow stats. The History tab lists revisions that changed a workflow, diffs them as YAML and on the canvas, restores into the editor, and ties runs to the revision they used.
This commit is contained in:
1 parent
2f05cbd34f
commit
2a066f6d4f
37 files changed
+677
-132
No files matched your search
@@ -1,12 +1,17 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import { Play } from "@lucide/vue";
|
||||
import { FlaskConical, Play } from "@lucide/vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
|
||||
import NewTaskForm from "@/tasks/NewTaskForm.vue";
|
||||
|
||||
defineProps<{ workflow: string; disabled?: boolean }>();
|
||||
defineProps<{
|
||||
workflow: string;
|
||||
disabled?: boolean;
|
||||
/** The unsaved definition to test-run; absent runs the stored one. */
|
||||
draft?: string;
|
||||
}>();
|
||||
const emit = defineEmits<{ started: [taskId: number] }>();
|
||||
const open = ref(false);
|
||||
|
||||
@@ -19,14 +24,20 @@ function started(taskId: number): void {
|
||||
<template>
|
||||
<Dialog v-model:open="open">
|
||||
<DialogTrigger as-child>
|
||||
<Button type="button" size="sm" variant="outline" :disabled="disabled" :title="disabled ? 'Save your changes first' : undefined">
|
||||
<Play data-icon="inline-start" /> Run</Button>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="outline"
|
||||
:disabled="disabled"
|
||||
:title="draft !== undefined ? 'Run this draft once without touching the forge' : disabled ? 'Save your changes first' : undefined"
|
||||
>
|
||||
<component :is="draft !== undefined ? FlaskConical : Play" data-icon="inline-start" /> {{ draft !== undefined ? "Test" : "Run" }}</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent class="sm:max-w-[640px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Run {{ workflow }}</DialogTitle>
|
||||
<DialogTitle>{{ draft !== undefined ? "Test" : "Run" }} {{ workflow }}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<NewTaskForm v-if="open" :workflow="workflow" @started="started" @cancel="open = false" />
|
||||
<NewTaskForm v-if="open" :workflow="workflow" :draft="draft" @started="started" @cancel="open = false" />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -16,8 +16,15 @@ const STATE_CLASSES: Record<string, string> = {
|
||||
skipped: "border-dashed border-muted-foreground/60",
|
||||
};
|
||||
|
||||
const MARK_CLASSES: Record<string, string> = {
|
||||
added: "border-ok ring-2 ring-ok/40",
|
||||
removed: "border-danger ring-2 ring-danger/40",
|
||||
changed: "border-warn ring-2 ring-warn/40",
|
||||
};
|
||||
|
||||
const stateClass = computed(() => {
|
||||
if (props.data.kind === "start") return "border-primary/60";
|
||||
if (props.data.mark) return MARK_CLASSES[props.data.mark];
|
||||
return STATE_CLASSES[props.data.run?.status ?? ""] ?? "border-border";
|
||||
});
|
||||
|
||||
@@ -58,6 +65,7 @@ function duration(ms?: number): string {
|
||||
<span v-if="data.step" class="font-mono text-[11px] text-fg-subtle">{{ data.step }}</span>
|
||||
<span class="truncate text-sm font-medium" :title="data.title">{{ data.title }}</span>
|
||||
</div>
|
||||
<div v-if="data.mark" class="text-[11px] font-medium" :class="{ 'text-ok': data.mark === 'added', 'text-danger': data.mark === 'removed', 'text-warn': data.mark === 'changed' }">{{ data.mark === "added" ? "Added" : data.mark === "removed" ? "Removed" : "Changed" }}</div>
|
||||
<div v-if="data.type && data.title !== stepTitle(data.type)" class="truncate font-mono text-[11px] text-fg-subtle">{{ data.type }}</div>
|
||||
<ul v-if="data.kind === 'start' && data.triggers?.length" class="mt-1 space-y-0.5">
|
||||
<li v-for="trigger in data.triggers" :key="trigger.kind + trigger.label" class="flex items-center gap-1.5 text-xs" :title="trigger.detail">
|
||||
|
||||
@@ -81,6 +81,7 @@ const activity = computed(() => events.value.filter((event) => {
|
||||
if (event.data?.step_id != null) return Number(event.data.step_id) === props.stage.id;
|
||||
return names.value.has(event.stage ?? "") && inWindow(event.at);
|
||||
}).sort((a, b) => String(a.at ?? "").localeCompare(String(b.at ?? ""))));
|
||||
const suppressed = computed(() => activity.value.filter((event) => event.kind === "forge_suppressed"));
|
||||
const groups = computed(() => {
|
||||
const agents = props.stage.agents ?? [];
|
||||
const branches = new Set(["", ...agents.map((agent) => agent.name.includes("/") ? agent.name.split("/")[0]! : ""), ...activity.value.map((event) => String(event.data?.branch ?? ""))]);
|
||||
@@ -128,6 +129,12 @@ const scopedLogs = computed(() => logs.value ? { ...logs.value, entries: (logs.v
|
||||
<p v-if="group.reports.length" class="text-xs text-muted-foreground">{{ group.reports.map((report) => describeTimelineEvent(report).detail).filter(Boolean).join(' · ') }}</p>
|
||||
<p v-else-if="group.agents.length" class="text-xs text-muted-foreground">{{ group.agents.reduce((sum, agent) => sum + agent.tokens_used, 0).toLocaleString() }} tokens recorded</p>
|
||||
</section>
|
||||
<section v-if="suppressed.length" class="space-y-1">
|
||||
<h3 class="text-xs font-medium text-muted-foreground" title="This was a test run, so these writes were skipped">Skipped in test run</h3>
|
||||
<ul class="divide-y divide-border rounded-md border border-border">
|
||||
<li v-for="(event, i) in suppressed" :key="i" class="px-3 py-2 text-xs break-words whitespace-pre-wrap">{{ event.detail }}</li>
|
||||
</ul>
|
||||
</section>
|
||||
<section class="space-y-3">
|
||||
<h3 class="text-xs font-medium text-muted-foreground">Captured changes</h3>
|
||||
<p v-if="changesError" role="alert" class="text-danger">{{ changesError }}</p>
|
||||
|
||||
@@ -36,6 +36,8 @@ const props = defineProps<{
|
||||
types?: string[];
|
||||
/** The watched run is parked, so its steps offer to restart it. */
|
||||
restartable?: boolean;
|
||||
/** Steps that differ from the definition being compared, by node id. */
|
||||
marks?: Record<string, "added" | "removed" | "changed">;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
edit: [StepPath];
|
||||
@@ -66,6 +68,8 @@ const nodes = computed(() =>
|
||||
const drop = Math.max(0, (props.triggers?.length ?? 0) - 2) * 18;
|
||||
if (drop) node = { ...node, position: { ...node.position, y: node.position.y + drop } };
|
||||
if (node.type === "lane") return node;
|
||||
const mark = props.marks?.[node.id];
|
||||
if (mark) node = { ...node, data: { ...node.data, mark } };
|
||||
return JSON.stringify(node.data.path ?? null) === selectedKey.value && props.selected
|
||||
? { ...node, data: { ...node.data, selected: true } }
|
||||
: node;
|
||||
@@ -113,13 +117,14 @@ function place(store?: VueFlowStore): void {
|
||||
const width = container.value?.clientWidth ?? 800;
|
||||
const height = container.value?.clientHeight ?? 560;
|
||||
// Scroll only when the furthest step reached would be out of view.
|
||||
const reached = graph.value.nodes.filter((node) => node.data.run).at(-1);
|
||||
const reached = graph.value.nodes.find((node) => props.marks?.[node.id]) ?? graph.value.nodes.filter((node) => node.data.run).at(-1);
|
||||
const below = reached && 24 + (reached.position.y + 180) * ZOOM > height;
|
||||
const y = below ? height / 3 - reached.position.y * ZOOM : 24;
|
||||
void flow.setViewport({ x: width / 2 - NODE_WIDTH / 2, y, zoom: ZOOM }, { duration: animate ? 300 : 0 });
|
||||
}
|
||||
|
||||
watch(() => graph.value.nodes.filter((node) => node.data.run).length, () => place());
|
||||
watch(() => props.marks, () => place());
|
||||
|
||||
// The right-click menu opens at the pointer, for the step under it or for the
|
||||
// canvas itself.
|
||||
|
||||
@@ -32,6 +32,9 @@ import WorkflowSettings from "./WorkflowSettings.vue";
|
||||
import RunWorkflowButton from "./RunWorkflowButton.vue";
|
||||
import TaskRowActions from "@/tasks/TaskRowActions.vue";
|
||||
import WorkflowCanvas from "./WorkflowCanvas.vue";
|
||||
import WorkflowHistory from "./WorkflowHistory.vue";
|
||||
import { useWorkflowHistory } from "./workflow-history";
|
||||
import { revisionOfRun, type WorkflowRevision } from "./workflow-revisions";
|
||||
import { deleteStep, duplicateStep, insertStep, moveStep, type StepPath } from "./workflow-edit";
|
||||
import { useWorkflowRuns } from "./workflow-runs";
|
||||
import { useWorkflowTriggers } from "./workflow-triggers";
|
||||
@@ -102,6 +105,25 @@ async function restartFrom(from: string): Promise<void> {
|
||||
}
|
||||
const { triggers, reload: reloadTriggers } = useWorkflowTriggers(selected);
|
||||
|
||||
const { revisions, error: historyError } = useWorkflowHistory(selected);
|
||||
const historyRevision = ref(0);
|
||||
const historyMode = ref("yaml");
|
||||
// The revision a run used, matched by the definition it pinned.
|
||||
function runRevision(run?: { workflow_definition_yaml?: string; created_at?: string }): WorkflowRevision | undefined {
|
||||
return run ? revisionOfRun(revisions.value, run.workflow_definition_yaml, run.created_at) : undefined;
|
||||
}
|
||||
const watchedRevision = computed(() => runRevision(watchedRun.value));
|
||||
function openRevision(version: number): void {
|
||||
historyRevision.value = version;
|
||||
view.value = "history";
|
||||
}
|
||||
// A restored version is an unsaved edit: nothing is written until Save.
|
||||
function restoreRevision(restored: string): void {
|
||||
yaml.value = restored;
|
||||
selectedStep.value = null;
|
||||
view.value = "canvas";
|
||||
}
|
||||
|
||||
// Canvas edits are edits to the YAML; a newly placed step opens for editing.
|
||||
const stepTypeNames = computed(() => vocabulary.value.map((info) => info.name));
|
||||
function insertAt(after: StepPath, type: string): void {
|
||||
@@ -225,6 +247,7 @@ function syncScroll(event: Event): void {
|
||||
<TabsList>
|
||||
<TabsTrigger value="canvas">Canvas</TabsTrigger>
|
||||
<TabsTrigger value="yaml">YAML</TabsTrigger>
|
||||
<TabsTrigger v-if="stored !== undefined" value="history">History</TabsTrigger>
|
||||
<TabsTrigger v-if="$slots.performance" value="performance">Performance</TabsTrigger>
|
||||
<TabsTrigger v-if="$slots.runs" value="runs">Runs <span class="ml-1 font-mono text-xs text-fg-subtle">{{ runsCount ?? 0 }}</span></TabsTrigger>
|
||||
</TabsList>
|
||||
@@ -238,11 +261,12 @@ function syncScroll(event: Event): void {
|
||||
>
|
||||
<NativeSelectOption value="">Definition only</NativeSelectOption>
|
||||
<NativeSelectOption v-for="run in runs" :key="run.id" :value="String(run.id)">{{
|
||||
[`Run #${run.id}`, run.title, run.status].filter(Boolean).join(" · ")
|
||||
[`${run.source === "test" ? "Test" : "Run"} #${run.id}`, run.title, run.status, runRevision(run) ? `v${runRevision(run)!.version}` : ""].filter(Boolean).join(" · ")
|
||||
}}</NativeSelectOption>
|
||||
</NativeSelect>
|
||||
<template v-if="watchedRun">
|
||||
<RouterLink :to="`/tasks/${watchedRun.id}`" class="shrink-0 px-1 text-xs text-muted-foreground hover:text-foreground hover:underline">Open</RouterLink>
|
||||
<button v-if="watchedRevision" type="button" class="shrink-0 px-1 font-mono text-xs text-muted-foreground hover:text-foreground hover:underline" title="Open the version this run used" @click="openRevision(watchedRevision.version)">v{{ watchedRevision.version }}</button>
|
||||
<TaskRowActions :task="watchedRun" class="shrink-0" @done="refresh" />
|
||||
</template>
|
||||
</div>
|
||||
@@ -263,6 +287,7 @@ function syncScroll(event: Event): void {
|
||||
<DropdownMenuItem variant="destructive" @select="confirmDelete = true"><Trash2 />Delete workflow</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
<RunWorkflowButton v-if="stored !== undefined" :workflow="selected" :draft="yaml" :disabled="!parsed.ok" @started="(id) => { view = 'canvas'; void follow(id); }" />
|
||||
<RunWorkflowButton v-if="stored !== undefined" :workflow="selected" :disabled="dirty" @started="(id) => { view = 'canvas'; void follow(id); }" />
|
||||
<Button type="submit" size="sm" :disabled="state.saving || !parsed.ok || !dirty">
|
||||
<Spinner v-if="state.saving" data-icon="inline-start" />Save</Button>
|
||||
@@ -332,6 +357,9 @@ function syncScroll(event: Event): void {
|
||||
</Transition>
|
||||
</div>
|
||||
</TabsContent>
|
||||
<TabsContent value="history">
|
||||
<WorkflowHistory v-model:selected="historyRevision" v-model:mode="historyMode" :revisions="revisions" :current="yaml" :error="historyError" @restore="restoreRevision" />
|
||||
</TabsContent>
|
||||
<TabsContent value="performance" class="grid gap-4"><slot name="performance" /></TabsContent>
|
||||
<TabsContent value="runs"><slot name="runs" /></TabsContent>
|
||||
<TabsContent value="yaml">
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, watch } from "vue";
|
||||
import { RotateCcw } from "@lucide/vue";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
|
||||
import { ago } from "@/lib/format";
|
||||
import WorkflowCanvas from "./WorkflowCanvas.vue";
|
||||
import { lineDiff, stepMarks, type WorkflowRevision } from "./workflow-revisions";
|
||||
|
||||
const props = defineProps<{ revisions: WorkflowRevision[]; current: string; error?: string }>();
|
||||
const emit = defineEmits<{ restore: [yaml: string] }>();
|
||||
const selected = defineModel<number>("selected", { default: 0 });
|
||||
const mode = defineModel<string>("mode", { default: "yaml" });
|
||||
|
||||
watch(
|
||||
() => props.revisions,
|
||||
(revisions) => {
|
||||
if (revisions.some((revision) => revision.version === selected.value)) return;
|
||||
// Open on the newest version that differs from what is open now.
|
||||
selected.value = (revisions.find((revision) => revision.yaml !== props.current) ?? revisions[0])?.version ?? 0;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const revision = computed(() => props.revisions.find((candidate) => candidate.version === selected.value));
|
||||
const then = computed(() => revision.value?.yaml ?? null);
|
||||
const diff = computed(() => (then.value === null ? [] : lineDiff(then.value, props.current)));
|
||||
const identical = computed(() => then.value !== null && then.value === props.current);
|
||||
const thenMarks = computed(() => (then.value === null ? {} : stepMarks(then.value, props.current, "removed")));
|
||||
const nowMarks = computed(() => (then.value === null ? {} : stepMarks(props.current, then.value, "added")));
|
||||
const CHANGE_VARIANTS = { added: "default", edited: "secondary", removed: "destructive" } as const;
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="grid h-[calc(100dvh-17rem)] min-h-[26rem] grid-cols-[18rem_1fr] gap-3">
|
||||
<ol class="min-h-0 divide-y divide-border overflow-y-auto rounded-lg border border-border" aria-label="Revisions">
|
||||
<li v-for="item in revisions" :key="item.version">
|
||||
<button
|
||||
type="button"
|
||||
class="block w-full px-3 py-2 text-left hover:bg-secondary"
|
||||
:class="item.version === selected && 'bg-secondary'"
|
||||
:aria-current="item.version === selected"
|
||||
@click="selected = item.version"
|
||||
>
|
||||
<span class="flex items-center gap-2 text-sm">
|
||||
<span class="font-mono text-xs text-fg-subtle">v{{ item.version }}</span>
|
||||
<Badge :variant="CHANGE_VARIANTS[item.change]">{{ item.change }}</Badge>
|
||||
</span>
|
||||
<span class="mt-0.5 block truncate text-xs text-muted-foreground" :title="item.at">{{ item.actor || "unknown" }} · {{ item.source || "unknown" }} · {{ ago(item.at) }}</span>
|
||||
</button>
|
||||
</li>
|
||||
<li v-if="!revisions.length" class="px-3 py-2 text-sm text-muted-foreground">{{ error || "No recorded changes" }}</li>
|
||||
</ol>
|
||||
<div v-if="revision" class="flex min-h-0 flex-col gap-2">
|
||||
<div class="flex items-center gap-2">
|
||||
<Tabs v-model="mode"><TabsList><TabsTrigger value="yaml">YAML</TabsTrigger><TabsTrigger value="canvas">Canvas</TabsTrigger></TabsList></Tabs>
|
||||
<span class="text-xs text-muted-foreground">{{ identical ? "Same as the current definition" : "Compared with the current definition" }}</span>
|
||||
<Button type="button" size="sm" variant="outline" class="ml-auto" :disabled="then === null || identical" :title="then === null ? 'This revision removed the workflow' : undefined" @click="emit('restore', then!)">
|
||||
<RotateCcw data-icon="inline-start" /> Restore this version</Button>
|
||||
</div>
|
||||
<p v-if="then === null" class="rounded-lg border border-border p-4 text-sm text-muted-foreground">This revision removed the workflow.</p>
|
||||
<pre v-else-if="mode === 'yaml'" class="min-h-0 flex-1 overflow-auto rounded-lg border border-border py-2 font-mono text-[13px] leading-6"><code><span
|
||||
v-for="(line, i) in diff"
|
||||
:key="i"
|
||||
class="block min-h-6 px-3 whitespace-pre-wrap"
|
||||
:class="{ 'bg-ok/10': line.kind === 'add', 'bg-danger/10 text-danger': line.kind === 'del' }"
|
||||
><span class="inline-block w-4 select-none text-fg-subtle">{{ line.kind === "add" ? "+" : line.kind === "del" ? "-" : "" }}</span>{{ line.text }}</span></code></pre>
|
||||
<div v-else class="grid min-h-0 flex-1 grid-cols-2 gap-3">
|
||||
<div class="flex min-h-0 flex-col gap-1">
|
||||
<span class="text-xs font-medium text-muted-foreground">v{{ revision.version }}</span>
|
||||
<div class="min-h-0 flex-1"><WorkflowCanvas :yaml="then" :marks="thenMarks" /></div>
|
||||
</div>
|
||||
<div class="flex min-h-0 flex-col gap-1">
|
||||
<span class="text-xs font-medium text-muted-foreground">Current</span>
|
||||
<div class="min-h-0 flex-1"><WorkflowCanvas :yaml="current" :marks="nowMarks" /></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -38,6 +38,8 @@ export interface StepNodeData {
|
||||
* names the parallel step it belongs to here. */
|
||||
resume?: string;
|
||||
run?: StageRun;
|
||||
/** How the step differs from the definition it is compared with. */
|
||||
mark?: "added" | "removed" | "changed";
|
||||
/** Where the step lives in the YAML document, for editing it. */
|
||||
path?: (string | number)[];
|
||||
selected?: boolean;
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { computed, ref, watch, type Ref } from "vue";
|
||||
|
||||
import { useSettingsStore, type ResourceRevision } from "@/stores/settings";
|
||||
import { workflowRevisions } from "./workflow-revisions";
|
||||
|
||||
const KIND = "workflow-definitions";
|
||||
|
||||
/** The history of workflow `id`, kept current as the definitions change. */
|
||||
export function useWorkflowHistory(id: Ref<string>) {
|
||||
const store = useSettingsStore();
|
||||
const all = ref<ResourceRevision[]>([]);
|
||||
const error = ref("");
|
||||
|
||||
async function reload(): Promise<void> {
|
||||
try {
|
||||
all.value = await store.history(KIND);
|
||||
error.value = "";
|
||||
} catch (err) {
|
||||
error.value = err instanceof Error ? err.message : "Could not load history";
|
||||
}
|
||||
}
|
||||
watch(() => store.stateFor(KIND).resource?.version, () => void reload(), { immediate: true });
|
||||
|
||||
const revisions = computed(() => workflowRevisions(id.value, all.value));
|
||||
return { revisions, error, reload };
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { parseDocument } from "yaml";
|
||||
|
||||
import type { ResourceRevision } from "../stores/settings.ts";
|
||||
import { workflowGraph } from "./workflow-graph.ts";
|
||||
|
||||
/** One revision of the definitions that changed a single workflow. */
|
||||
export interface WorkflowRevision {
|
||||
version: number;
|
||||
change: "added" | "edited" | "removed";
|
||||
/** The workflow's YAML at this revision; null when the revision removed it. */
|
||||
yaml: string | null;
|
||||
actor: string;
|
||||
source: string;
|
||||
at?: string;
|
||||
}
|
||||
|
||||
function entryYaml(value: unknown, id: string): string | null {
|
||||
const definitions = (value as { definitions?: { id: string; yaml: string }[] } | null)?.definitions;
|
||||
return definitions?.find((entry) => entry.id === id)?.yaml ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The revisions in which workflow `id` was added, edited or removed, newest
|
||||
* first. All workflows share one resource, so a revision that left this one's
|
||||
* YAML as it was is not part of its history.
|
||||
*/
|
||||
export function workflowRevisions(id: string, revisions: ResourceRevision[]): WorkflowRevision[] {
|
||||
const changes: WorkflowRevision[] = [];
|
||||
let previous: string | null = null;
|
||||
for (const revision of [...revisions].sort((a, b) => a.version - b.version)) {
|
||||
const yaml = entryYaml(revision.value, id);
|
||||
if (yaml !== previous) {
|
||||
changes.push({
|
||||
version: revision.version,
|
||||
change: yaml === null ? "removed" : previous === null ? "added" : "edited",
|
||||
yaml,
|
||||
actor: revision.actor,
|
||||
source: revision.source,
|
||||
at: revision.at,
|
||||
});
|
||||
}
|
||||
previous = yaml;
|
||||
}
|
||||
return changes.reverse();
|
||||
}
|
||||
|
||||
/**
|
||||
* The revision a run used: the newest one holding the YAML the run pinned that
|
||||
* was already in place when the run was created. A test run pins a draft that
|
||||
* no revision holds.
|
||||
*/
|
||||
export function revisionOfRun(revisions: WorkflowRevision[], pinned?: string, createdAt?: string): WorkflowRevision | undefined {
|
||||
if (!pinned) return undefined;
|
||||
const matches = revisions.filter((revision) => revision.yaml === pinned);
|
||||
const created = createdAt ? Date.parse(createdAt) : NaN;
|
||||
return matches.find((revision) => !revision.at || Number.isNaN(created) || Date.parse(revision.at) <= created) ?? matches.at(-1);
|
||||
}
|
||||
|
||||
export interface DiffLine {
|
||||
kind: "same" | "add" | "del";
|
||||
text: string;
|
||||
}
|
||||
|
||||
/** A line diff from `before` to `after`: `del` lines are only in `before`. */
|
||||
export function lineDiff(before: string, after: string): DiffLine[] {
|
||||
const a = before.split("\n");
|
||||
const b = after.split("\n");
|
||||
const lcs: number[][] = Array.from({ length: a.length + 1 }, () => new Array<number>(b.length + 1).fill(0));
|
||||
for (let i = a.length - 1; i >= 0; i--)
|
||||
for (let j = b.length - 1; j >= 0; j--)
|
||||
lcs[i]![j] = a[i] === b[j] ? lcs[i + 1]![j + 1]! + 1 : Math.max(lcs[i + 1]![j]!, lcs[i]![j + 1]!);
|
||||
const out: DiffLine[] = [];
|
||||
let i = 0;
|
||||
let j = 0;
|
||||
while (i < a.length && j < b.length) {
|
||||
if (a[i] === b[j]) out.push({ kind: "same", text: a[i++]! }), j++;
|
||||
else if (lcs[i + 1]![j]! >= lcs[i]![j + 1]!) out.push({ kind: "del", text: a[i++]! });
|
||||
else out.push({ kind: "add", text: b[j++]! });
|
||||
}
|
||||
while (i < a.length) out.push({ kind: "del", text: a[i++]! });
|
||||
while (j < b.length) out.push({ kind: "add", text: b[j++]! });
|
||||
return out;
|
||||
}
|
||||
|
||||
export type Mark = "added" | "removed" | "changed";
|
||||
|
||||
function stepsOf(source: string): Map<string, { node: string; signature: string }> {
|
||||
const value: unknown = parseDocument(source).toJS();
|
||||
const steps = new Map<string, { node: string; signature: string }>();
|
||||
for (const node of workflowGraph(source).nodes) {
|
||||
const { kind, path, stage, occurrence } = node.data;
|
||||
if (node.type !== "step" || kind !== "step" || !path || stage === undefined) continue;
|
||||
let at: unknown = value;
|
||||
for (const part of path) at = (at as Record<string | number, unknown> | undefined)?.[part];
|
||||
steps.set(`${stage}#${occurrence ?? 0}`, { node: node.id, signature: JSON.stringify(at ?? null) });
|
||||
}
|
||||
return steps;
|
||||
}
|
||||
|
||||
/**
|
||||
* Marks the steps of `source` that differ from `other`, by canvas node id. A
|
||||
* step `other` lacks is marked `missing`: "removed" when `source` is the older
|
||||
* definition, "added" when it is the newer.
|
||||
*/
|
||||
export function stepMarks(source: string, other: string, missing: "added" | "removed"): Record<string, Mark> {
|
||||
const here = stepsOf(source);
|
||||
const there = stepsOf(other);
|
||||
const marks: Record<string, Mark> = {};
|
||||
for (const [identity, step] of here) {
|
||||
const counterpart = there.get(identity);
|
||||
if (!counterpart) marks[step.node] = missing;
|
||||
else if (counterpart.signature !== step.signature) marks[step.node] = "changed";
|
||||
}
|
||||
return marks;
|
||||
}
|
||||
Reference in new issue
Block a user