import { useAtomValue } from "@effect/atom-react"; import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { isAtomCommandInterrupted, squashAtomCommandFailure, type AtomCommandResult, } from "@t3tools/client-runtime/state/runtime"; import { EnvironmentId, ThreadId, type WorkflowQuestion, type WorkflowRun, type WorkflowRunReference, } from "@t3tools/contracts"; import { formatModelSlugName } from "@t3tools/shared/model"; import { formatDuration } from "@t3tools/shared/orchestrationTimingCopy"; import { msg, T, useGT, useMessages, Var } from "gt-react"; import { ArrowLeftIcon, ArrowUpRightIcon, ExternalLinkIcon, ChevronRightIcon, BotIcon, CheckIcon, CircleAlertIcon, HourglassIcon, MoonIcon, SquareIcon, } from "lucide-react"; import { secondTick } from "@t3tools/client-runtime/clock"; import { createContext, useContext, useRef, useState, useSyncExternalStore, type ReactNode, } from "react"; import { requestConfirmDialog } from "../../confirmDialog"; import { useNowMinute } from "../../hooks/useNowMinute"; import { cn } from "../../lib/utils"; import { useQuietThreadShell } from "../../state/entities"; import { useEnvironmentProviders } from "../../state/environments"; import { type MessageResolver } from "../../i18n/messages"; import { useEnvironmentQuery } from "../../state/query"; import { serverEnvironment } from "../../state/server"; import { useEnvironmentSessionId } from "../../state/session"; import { useAtomCommand } from "../../state/use-atom-command"; import { formatRelativeTimeLabel } from "../../timestampFormat"; import ChatMarkdown from "../ChatMarkdown"; import { ProviderInstanceIcon } from "../chat/ProviderInstanceIcon"; import { Button } from "../ui/button"; import { Input } from "../ui/input"; import { stackedThreadToast, toastManager } from "../ui/toast"; import { buildWorkflowFeed, buildWorkflowTimeline, readWorkflowQuestion, workflowAgentSummary, isOwnWorkflowAnswer, workflowAnswer, workflowChip, workflowFlowFocus, workflowPausedBeat, workflowResultLines, workflowRunNow, workflowRunState, workflowWithdrawal, workflowSaidStart, workflowStepReferences, workflowStepTime, workflowOneLine, type WorkflowBeat, type WorkflowFeedRow, type WorkflowQuestionChoice, type WorkflowQuickSteps, type WorkflowRunNode, type WorkflowRunTone, } from "@t3tools/client-runtime/workflows"; import type { WorkflowPaneTab } from "./workflowPane.logic"; import { WorkflowReferenceChip } from "./WorkflowReferences"; import { useWorkflowThreadOpen } from "./useWorkflowThreadOpen"; /** An agent's thread, as a step names it: the linked environment it is in, or null for this one. */ export interface WorkflowThreadTarget { readonly threadId: string; readonly environmentId: string | null; } // An agent that wrote a page gets a few lines of it; the rest is a click away. const SAID_SHOWN = 320; // What waits on a person is what they came for, so it is in view when the run opens. const revealOnMount = (element: HTMLElement | null) => { element?.scrollIntoView({ block: "nearest" }); }; function reportFailure(title: string, result: AtomCommandResult) { if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; toastManager.add( stackedThreadToast({ type: "error", title, description: String(squashAtomCommandFailure(result)), }), ); } // Reads the minute tick because the compiler caches a render-time Date.now() on the timestamp. function useNowMs(): number { return Date.parse(`${useNowMinute()}:00.000Z`); } // A time still counting is told to the second: its tenths would only flicker. const wholeSeconds = (ms: number) => Math.max(1000, Math.round(ms / 1000) * 1000); const elapsedOf = (beat: WorkflowBeat) => beat.status === "running" ? wholeSeconds(beat.endMs - beat.startMs) : beat.endMs - beat.startMs; const never = () => () => {}; const noTick = () => 0; /** The clock a run is told by: to the second while it is under way, to the minute after. */ function useRunNowMs(live: boolean): number { const minute = useNowMs(); const second = useSyncExternalStore( live ? secondTick.subscribe : never, live ? secondTick.getSnapshot : noTick, live ? secondTick.getSnapshot : noTick, ); return live ? second : minute; } export function RelativeLabel({ value }: { readonly value: string }) { return formatRelativeTimeLabel(value, useNowMs()); } const CHIP_TONES = [ "bg-sky-500/15 text-sky-700 dark:text-sky-300", "bg-violet-500/15 text-violet-700 dark:text-violet-300", "bg-amber-500/15 text-amber-700 dark:text-amber-300", "bg-emerald-500/15 text-emerald-700 dark:text-emerald-300", "bg-rose-500/15 text-rose-700 dark:text-rose-300", ] as const; /** Which workflow a run is of, at a glance: the same letters and colour wherever it shows. */ export function WorkflowChip({ name }: { readonly name: string }) { const chip = workflowChip(name); return ( {chip.letters} ); } // The thread list's own colours for the same states, so a run reads like a thread does. const WORKFLOW_TONE_CLASS: Record = { input: "text-warning-foreground", failed: "text-destructive", working: "text-info-foreground", quiet: "text-muted-foreground", done: "text-success-foreground", }; export function WorkflowStateWord({ node }: { readonly node: WorkflowRunNode }) { const m = useMessages(); const state = workflowRunState(node, m); return ( {state.tone === "working" ? ( ) : state.tone === "done" ? ( ) : null} {state.word} ); } const nthTry = (count: number, resolve: MessageResolver) => resolve( msg( "{count, selectordinal, one {{count}st try} two {{count}nd try} few {{count}rd try} other {{count}th try}}", { count }, ), ); const queuedText = (beat: WorkflowBeat, resolve: MessageResolver) => beat.ahead === undefined || beat.ahead === 0 ? resolve(msg("queued, next in line", { $context: "a workflow step waits for a free place" })) : resolve( msg("{count, plural, one {queued, {count} ahead} other {queued, {count} ahead}}", { count: beat.ahead, }), ); // The loading view and the timeline each draw a question's card, so a reason typed while the // steps load is kept here rather than in the card that is about to be replaced. const AnswerDrafts = createContext<{ readonly get: (key: string) => string | null; readonly set: (key: string, reason: string | null) => void; } | null>(null); export function WorkflowRunFeed({ environmentId, node, parent: liveParent, shownTab, onSelect, onOpenThread, onOpenReference, }: { readonly environmentId: EnvironmentId; readonly node: WorkflowRunNode; readonly parent: WorkflowRun | null; /** What shows beside the run, so the card or chip that opened it can say so. */ readonly shownTab: WorkflowPaneTab | null; readonly onSelect: (runId: string | null) => void; readonly onOpenThread: (thread: WorkflowThreadTarget) => void; readonly onOpenReference: (reference: WorkflowRunReference) => void; }) { const { run } = node; const gt = useGT(); const m = useMessages(); const clockMs = useRunNowMs(node.run.endedAt === null); // An ended run's last step can still read as running for a moment; it ran until the run ended. const nowMs = node.run.endedAt === null ? clockMs : Date.parse(node.run.endedAt); const panel = useRef(null); const [picked, setPicked] = useState(null); // Steps already there when the run opens are simply shown; only later ones arrive with motion. const [openedAtMs] = useState(() => Date.now()); const detail = useEnvironmentQuery( serverEnvironment.workflowRun({ environmentId, input: { runId: run.runId } }), ); const history = useEnvironmentQuery( liveParent === null && run.parentRunId !== null ? serverEnvironment.workflowRun({ environmentId, input: { runId: run.runId, includeRelatedRuns: true }, }) : null, ); const parent = liveParent ?? history.data?.relatedRuns?.find((related) => related.runId === run.parentRunId) ?? null; const canResume = useAtomValue(serverEnvironment.resumeWorkflowRun.permissionAtom(environmentId)); const canCancel = useAtomValue(serverEnvironment.cancelWorkflowRun.permissionAtom(environmentId)); const resume = useAtomCommand(serverEnvironment.resumeWorkflowRun, { label: "workflow resume" }); const cancel = useAtomCommand(serverEnvironment.cancelWorkflowRun, { label: "workflow cancel" }); const [busy, setBusy] = useState(false); const target = { environmentId, input: { runId: run.runId } }; const [drafts, setDrafts] = useState>(() => new Map()); const answerDrafts = { get: (key: string) => drafts.get(key) ?? null, set: (key: string, reason: string | null) => setDrafts((current) => { const next = new Map(current); if (reason === null) next.delete(key); else next.set(key, reason); return next; }), }; const resumeRun = async () => { if (busy) return; setBusy(true); const result = await resume(target); setBusy(false); reportFailure(gt("Could not resume the run"), result); }; const cancelRun = async () => { if (busy) return; // Busy while the dialog is up, so a second click does not open a second one. setBusy(true); const confirmed = await (requestConfirmDialog( gt("Cancel {title}? Its agents stop and the run cannot be resumed.", { title: run.title }), { variant: "destructive" }, ) ?? Promise.resolve(false)); if (!confirmed) return setBusy(false); const result = await cancel(target); setBusy(false); reportFailure(gt("Could not cancel the run"), result); }; const ended = run.endedAt !== null; const ranMs = ended ? Date.parse(run.endedAt) - Date.parse(run.startedAt) : wholeSeconds(nowMs - Date.parse(run.startedAt)); const steps = detail.data?.steps; const references = detail.data?.references ?? []; // An open transcript is one thread in one environment; `env` is absent for the run's own. const openThread = shownTab !== null && "thread" in shownTab ? shownTab : null; const chip = (reference: WorkflowRunReference, small = false) => ( onOpenReference(reference)} /> ); const feed = steps === undefined ? null : buildWorkflowFeed( buildWorkflowTimeline({ run, steps, children: node.children.map((child) => child.run), nowMs, }), ); const beats = (feed ?? []).flatMap((row) => row.kind === "quick" ? [] : row.kind === "together" ? row.beats : [row], ); // A question is told where it was asked. One whose step is not in the list yet still shows. const questionOf = (beat: WorkflowBeat) => beat.kind === "ask" && beat.status === "running" ? (node.questions.find((question) => question.name === beat.name) ?? null) : null; const loose = node.questions.filter( (question) => !beats.some((beat) => questionOf(beat) === question), ); const pausedAt = feed === null ? null : workflowPausedBeat(feed, run.status); const pause = (name: string | null, attempts: number, reason: string | null) => ( void resumeRun()} kept={(steps ?? []).some((step) => step.status === "completed")} /> ); const beatCard = (beat: WorkflowBeat) => { if (beat === pausedAt) { // The step's own card stays, so its transcript can be read before resuming. return (
{pause(beat.name, beat.attempts, beat.detail ?? run.detail)} {stepCard(beat)}
); } return stepCard(beat); }; const stepCard = (beat: WorkflowBeat) => ( child.run.runId === beat.childRun?.runId) ?? null} nowMs={nowMs} open={ beat.thread !== null && openThread !== null && beat.thread.threadId === openThread.thread && (beat.thread.environmentId ?? undefined) === openThread.env } onSelect={onSelect} onOpenThread={onOpenThread} /> ); const resultLines = workflowResultLines(run.result); const pausedApart = run.status === "paused" && pausedAt === null; const keys = new Set([ ...(feed ?? []).flatMap((row) => (row.kind === "quick" ? [`quick:${row.steps[0]?.name}`] : [])), ...beats.map((beat) => `step:${beat.name}`), ...loose.map((question) => `question:${question.name}`), ...(pausedApart ? ["pause"] : []), ...(ended ? ["end"] : []), ]); // A run that finished opens on what it came to: its result when that says more than the last // answer, else the last agent's reply. The header already says it is done. const lastAnswer = beats.findLast((beat) => beat.kind === "ask" && beat.status === "completed"); const answered = lastAnswer === undefined ? null : workflowAnswer(lastAnswer.result); const resultSaysMore = resultLines.length > 0 && !(resultLines.length === 1 && answered !== null && resultLines[0]?.value === answered.choice); const latest = (found: ReadonlyArray) => found.reduce( (best, beat) => (best === undefined || beat.endMs >= best.endMs ? beat : best), undefined, ); const lastAgent = latest( beats.filter((beat) => beat.kind === "agent" && beat.status === "completed"), ); const finishedFocus = run.status !== "completed" || resultSaysMore || lastAgent === undefined ? "end" : `step:${lastAgent.name}`; const focus = picked !== null && keys.has(picked) ? picked : feed === null ? null : ended ? finishedFocus : workflowFlowFocus({ rows: feed, status: run.status, ended, questions: node.questions.map((question) => question.name), }); const pick = (key: string) => { const asks = key.startsWith("question:") || beats.some((beat) => `step:${beat.name}` === key && questionOf(beat) !== null); setPicked(asks ? null : key); // Below the flow on a narrow page, so picking a step brings what it shows into view; a // question is answered where it is, so the page stays put. if (!asks) panel.current?.scrollIntoView({ block: "nearest" }); }; const endWord = run.status === "completed" ? gt("Finished", { $context: "how a workflow run ended" }) : run.status === "stopped" ? gt("Stopped", { $context: "how a workflow run ended" }) : run.status === "skipped" ? gt("Skipped", { $context: "how a workflow run ended" }) : gt("Cancelled", { $context: "how a workflow run ended" }); // A question is answered where it was asked, so beside it is what led up to it. const asking = focus !== null && (focus.startsWith("question:") || beats.some( (beat) => `step:${beat.name}` === focus && // Answered, its question is gone a moment before the step itself says it is done. (questionOf(beat) !== null || (beat.kind === "ask" && beat.status === "running")), )); // The latest agent's reply is what a person weighs before answering; failing that, the last // step that left something behind. A sleep or a wait has nothing to say. const before = asking ? (latest(beats.filter((beat) => beat.kind === "agent" && beat.status !== "running")) ?? beats.findLast( (beat) => beat.status !== "running" && beat.kind !== "ask" && beat.kind !== "sleep" && beat.kind !== "wait" && beat.kind !== "queue", ) ?? null) : null; const shown = asking ? (before === null ? null : `step:${before.name}`) : focus; const shownBeat = beats.find((beat) => `step:${beat.name}` === shown); const shownQuick = (feed ?? []).find( (row) => row.kind === "quick" && `quick:${row.steps[0]?.name}` === shown, ); return (
{parent === null ? null : ( )}

{run.title}

{ended ? null : ( )}

{run.workflow} · started{" "} {run.status === "paused" ? null : ( <> · {ended ? gt("took {duration}", { duration: formatDuration(ranMs, m) }) : gt("{duration} so far", { duration: formatDuration(ranMs, m) })} )} {run.retired ? ( <> · its version is no longer registered ) : null}

{references.length === 0 ? null : (
    {references.map((reference) => (
  • {chip(reference, reference.title !== "" && run.title.includes(reference.title))}
  • ))}
)}
{detail.error || feed === null || (feed.length === 0 && run.status === "paused" && loose.length === 0) ? ( <> {detail.error ? (

{detail.error}

) : feed === null ? (

Loading steps…

) : null} {/* A question the run already asks is answerable without its step history. */} {run.status === "paused" ? (
{pause(null, run.pauses, run.detail)}
) : null} {node.questions.map((question) => (
))} ) : (
{shownBeat !== undefined ? ( // Keyed by the step: a reason typed for one question must not follow to the next.
{beatCard(shownBeat)} {(() => { // With one reference, the header already says it. const touched = references.length > 1 ? workflowStepReferences(references, shownBeat.name) : []; return touched.length === 0 ? null : (
{touched.map((reference) => chip(reference, true))}
); })()}
) : shownQuick !== undefined && shownQuick.kind === "quick" ? ( ) : asking ? null : focus === "pause" ? ( pause(null, run.pauses, run.detail) ) : focus === "end" ? ( ) : null } name={endWord} sub={} /> {run.status !== "completed" && run.detail ? (

{run.detail}

) : null}
) : (

Nothing yet.

)}
)}
); } type StepTone = "working" | "input" | "quiet" | "done" | "failed" | "ended"; // Colour says what is live: blue for work under way, amber for a person's turn. Done is quiet. const RING: Record = { working: "stroke-info", input: "stroke-warning", quiet: "stroke-muted-foreground/60", done: "stroke-muted-foreground/45", failed: "stroke-destructive", ended: "stroke-muted-foreground/60", }; const VERB_TONE = { working: "text-info-foreground", input: "text-warning-foreground", quiet: "text-muted-foreground", failed: "text-destructive", } as const; /** * A step's place on the rail: a ring, filled while it works, ticked when it is done. `pulse` and * `draw` never change for a step, so each plays once, when its part of the mark first appears. */ function StepMark({ tone, pulse, draw, }: { readonly tone: StepTone; /** It started while the run was open here. */ readonly pulse: boolean; /** It ended while the run was open here. */ readonly draw: boolean; }) { const live = tone === "working" || tone === "input"; return ( {live && pulse ? ( ) : null} {live || tone === "quiet" ? ( ) : tone === "done" ? ( ) : tone === "failed" ? ( ) : ( )} ); } /** One line of the run: its mark on the rail, name, what it is doing, a word on how it went, its time. */ function TimelineRow({ tone, enters, draw, lead, name, note, verb, verbTone = "working", aside, asideTone, duration, selected, current = false, onPick, sub = false, }: { readonly tone: StepTone; /** It started while the run was open here, so it arrives instead of just being there. */ readonly enters: boolean; /** It ended while the run was open here. */ readonly draw: boolean; /** A small mark before the name, such as the agent's provider. */ readonly lead?: ReactNode; readonly name: string; /** A quieter word after the name, such as the agent's model. */ readonly note?: string | null; readonly verb?: string | null; readonly verbTone?: keyof typeof VERB_TONE; readonly aside?: string | null; readonly asideTone?: "failed"; readonly duration?: string | null; readonly selected: boolean; /** The pane beside the timeline shows it. */ readonly current?: boolean; readonly onPick: () => void; /** A step of a fork, hanging off the branch rather than the rail. */ readonly sub?: boolean; }) { const live = tone === "working" || tone === "input"; return ( ); } /** The rail beside a row: from the row above to this mark, and on to the next unless it is last. */ function Rail({ first, last }: { readonly first: boolean; readonly last: boolean }) { return ( ); } // A fork leaves the rail under its mark, runs through each step's dot, and rejoins the rail. // The rail's centre is 10px in and a step's dot 39px in; the mark ends 26px down, the first dot // sits 46px down, and each dot is 14px below its own row's top. function BranchOut() { return ( ); } function BranchBack() { return ( <> ); } /** * The run as it went, one line per step that took time or involved someone. Steps that ran at once * hang off a branch. It never draws what comes next: a run can branch, so the rail just goes on. */ function WorkflowTimeline({ environmentId, rows, node, nowMs, focus, onPick, loose, paused, end, question, onOpenThread, openedAtMs, current, }: { readonly environmentId: EnvironmentId; readonly rows: ReadonlyArray; readonly node: WorkflowRunNode; readonly nowMs: number; readonly focus: string | null; readonly onPick: (key: string) => void; /** Questions whose step is not in the list yet. */ readonly loose: ReadonlyArray; /** The run is paused, and not at a step that failed. */ readonly paused: boolean; /** How the run ended, once it has. */ readonly end: string | null; /** What it ended with, in a few words. */ /** The question a step waits on a person for, answered right under it. */ readonly question: (beat: WorkflowBeat) => WorkflowQuestion | null; readonly onOpenThread: (thread: WorkflowThreadTarget) => void; /** When this run was opened here: only what changes after that arrives with motion. */ readonly openedAtMs: number; /** What the pane beside the timeline shows. */ readonly current: string | null; }) { const gt = useGT(); const m = useMessages(); const completed = node.run.status === "completed"; const ask = (asked: WorkflowQuestion) => (
); const beatRow = (beat: WorkflowBeat, sub = false) => ( child.run.runId === beat.childRun?.runId) ?? null} asks={node.questions.some((asked) => asked.name === beat.name)} nowMs={nowMs} selected={focus === `step:${beat.name}`} current={current === `step:${beat.name}`} onPick={() => onPick(`step:${beat.name}`)} sub={sub} openedAtMs={openedAtMs} /> ); const items: Array<{ readonly key: string; readonly body: ReactNode; /** Its steps hang off a branch, which carries the rail past them. */ readonly branch?: boolean; }> = []; for (const row of rows) { if (row.kind === "quick") { const key = `quick:${row.steps[0]?.name}`; // Keyed by its first step, as that step's own row was, so regrouping does not remount it. const itemKey = row.steps[0]?.name ?? key; const names = row.steps.map((step) => step.name); items.push({ key: itemKey, body: ( openedAtMs} name={ names.length <= 2 ? names.join(" · ") : gt("{names} and {count} more", { names: names.slice(0, 2).join(" · "), count: names.length - 2, }) } duration={workflowStepTime(Math.max(0, row.endMs - row.startMs), m)} selected={focus === key} current={current === key} onPick={() => onPick(key)} /> ), }); continue; } if (row.kind === "together") { const running = row.beats.filter((beat) => beat.status === "running").length; // Steps that only sleep or wait are under way without working. const working = row.beats.some( (beat) => beat.status === "running" && beat.kind !== "sleep" && beat.kind !== "wait" && beat.kind !== "queue", ); const failed = row.beats.some((beat) => beat.status === "failed"); const asks = row.beats.some( (beat) => beat.status === "running" && node.questions.some((q) => q.name === beat.name), ); const startMs = Math.min(...row.beats.map((beat) => beat.startMs)); const endMs = Math.max(...row.beats.map((beat) => beat.endMs)); const first = row.beats[0]; items.push({ key: first?.name ?? "together", branch: true, body: ( <>
0 ? "quiet" : failed ? "failed" : "done" } pulse={startMs > openedAtMs} draw={running === 0 && endMs > openedAtMs} /> 0 ? "font-medium" : "text-muted-foreground", )} > {gt("{count} in parallel", { count: row.beats.length })} {working ? ( {gt("{count} running", { count: running })} ) : null} {workflowStepTime(running > 0 ? wholeSeconds(endMs - startMs) : endMs - startMs, m)}
    {row.beats.map((beat, index) => { const firstBeat = index === 0; const lastBeat = index === row.beats.length - 1; const asked = question(beat); return (
  1. {lastBeat ? : null} {beatRow(beat, true)} {asked === null ? null : ask(asked)}
  2. ); })}
), }); continue; } const asked = question(row); items.push({ key: row.name, body: ( <> {beatRow(row)} {asked === null ? null : ask(asked)} ), }); } for (const asked of loose) { // Keyed like its step's row, which replaces it once the step arrives, so it does not arrive twice. items.push({ key: asked.name, body: ( <> openedAtMs} draw={false} name={asked.name} verb={gt("Asks you", { $context: "a workflow step waits on a person's answer" })} verbTone="input" selected={focus === `question:${asked.name}`} current={current === `question:${asked.name}`} onPick={() => onPick(`question:${asked.name}`)} /> {ask(asked)} ), }); } if (paused) { items.push({ key: "pause", body: ( onPick("pause")} /> ), }); } // A finished run needs no closing row: the header says so, and the last step is the end. if (end !== null && !completed) { const endedMs = Date.parse(node.run.endedAt ?? node.run.updatedAt); items.push({ key: "end", body: ( openedAtMs} draw={false} name={end} aside={node.run.detail} selected={focus === "end"} current={current === "end"} onPick={() => onPick("end")} /> ), }); } const live = end === null; return ( ); } function WorkflowBeatRow({ environmentId, beat, child, asks, nowMs, selected, onPick, sub, openedAtMs, current, }: { readonly environmentId: EnvironmentId; readonly beat: WorkflowBeat; readonly child: WorkflowRunNode | null; /** A person's answer is what it waits for. */ readonly asks: boolean; readonly nowMs: number; readonly selected: boolean; readonly onPick: () => void; readonly sub: boolean; readonly openedAtMs: number; readonly current: boolean; }) { const gt = useGT(); const m = useMessages(); const threadEnvironmentId = beat.thread?.environmentId == null ? environmentId : EnvironmentId.make(beat.thread.environmentId); const shell = useQuietThreadShell( beat.thread === null ? null : scopeThreadRef(threadEnvironmentId, ThreadId.make(beat.thread.threadId)), ); const provider = useEnvironmentProviders() .get(threadEnvironmentId) ?.find((candidate) => candidate.instanceId === shell?.modelSelection.instanceId); const under = beat.status === "running"; const failed = beat.status === "failed"; const said = workflowAgentSummary(beat).said; const answer = beat.kind === "ask" ? workflowAnswer(beat.result) : null; const sessionId = useEnvironmentSessionId(environmentId); const wakes = beat.detail === null ? Number.NaN : Date.parse(beat.detail); // An agent's own approval or question needs a person as much as the workflow's does. const agentAsks = beat.kind === "agent" && under && shell !== null ? shell.hasPendingUserInput ? gt("Asks you", { $context: "a workflow step waits on a person's answer" }) : shell.hasPendingApprovals ? gt("waits for your approval") : null : null; // A question waits on a person until its step ends, answered or not; the list of open // questions drops it a moment before the step reports done. const needsYou = (under && (asks || beat.kind === "ask")) || agentAsks !== null; const model = shell === null ? null : formatModelSlugName(shell.modelSelection.model); const verb = (() => { if (!under) return null; if (agentAsks !== null) return agentAsks; switch (beat.kind) { case "agent": return shell?.runtime?.status === "preparing" || shell?.runtime?.status === "starting" ? gt("starting") : gt("working"); case "ask": // Without its question it was just answered, and the step is about to say so. return asks ? gt("Asks you", { $context: "a workflow step waits on a person's answer" }) : null; case "sleep": return Number.isFinite(wakes) && wakes > nowMs ? gt("wakes in {duration}", { duration: formatDuration(wholeSeconds(wakes - nowMs), m) }) : gt("about to wake"); case "wait": return gt("waiting"); case "queue": return queuedText(beat, m); case "run": return child === null ? gt("running") : workflowRunNow(child, m); case "step": return gt("running"); } })(); const aside = (() => { if (failed) return workflowOneLine(beat.detail ?? gt("failed")); if (under) return null; switch (beat.kind) { case "agent": return said === null ? null : workflowOneLine(said); case "ask": if (answer !== null) return answer.answeredBy === null || isOwnWorkflowAnswer(answer, sessionId) ? gt("You said {choice}", { choice: answer.choice }) : gt("{who} said {choice}", { who: answer.answeredBy, choice: answer.choice }); const withdrawal = workflowWithdrawal(beat.result); return withdrawal === null ? gt("nobody answered") : gt("withdrawn by {by}", { by: withdrawal.by }); case "sleep": case "wait": case "queue": return null; case "run": return child === null ? null : workflowRunNow(child, m); case "step": { const first = workflowResultLines(beat.result)[0]; return first === undefined ? null : first.label === null ? first.value : `${first.label}: ${first.value}`; } } })(); return ( openedAtMs} draw={!under && beat.endMs > openedAtMs} lead={ beat.kind === "agent" && provider !== undefined ? ( ) : beat.kind === "run" ? ( ) : undefined } name={beat.childRun?.title ?? beat.name} note={beat.kind === "agent" && (under || said === null) ? model : null} verb={verb} verbTone={ needsYou ? "input" : beat.kind === "sleep" || beat.kind === "wait" || beat.kind === "queue" ? "quiet" : "working" } aside={aside} {...(failed ? { asideTone: "failed" as const } : {})} duration={workflowStepTime(elapsedOf(beat), m)} selected={selected} current={current} onPick={onPick} sub={sub} /> ); } // What happened reads as part of the page. A question, answered in the timeline, is the one box; // a pause says so in its heading and its button. const CARD_TONE = { plain: "", quiet: "", ask: "rounded-xl border border-warning/30 bg-warning-surface px-3 py-2.5", failed: "", done: "", } as const; function FeedCard({ tone = "plain", label, reveal = false, children, }: { readonly tone?: keyof typeof CARD_TONE; readonly label?: string; /** Scroll it into view when it first shows. */ readonly reveal?: boolean; readonly children: ReactNode; }) { return (
{children}
); } function CardHead({ mark, name, sub, action, }: { readonly mark: ReactNode; readonly name: ReactNode; readonly sub?: ReactNode; readonly action?: ReactNode; }) { return (
{mark === null || mark === undefined ? null : ( {mark} )}
{name}
{action === undefined || action === null ? null :
{action}
}
{sub === undefined || sub === null || sub === "" ? null : (
{sub}
)}
); } function ResultLines({ lines, }: { readonly lines: ReadonlyArray<{ readonly label: string | null; readonly value: string }>; }) { if (lines.length === 0) return null; if (lines.every((line) => line.label === null)) { return (
{lines.map((line) => (

{line.value}

))}
); } return ({ label: line.label ?? "", value: line.value }))} />; } /** What a step left behind, as a list of names and values. */ function Facts({ facts, }: { readonly facts: ReadonlyArray<{ readonly label: string; readonly value: string }>; }) { return (
{facts.map((fact) => (
{fact.label}
{fact.value}
))}
); } /** A step with nothing to show but that it happened, and what it left behind. */ function Note({ label, children, detail, }: { readonly label: string; readonly children: ReactNode; readonly detail?: ReactNode; }) { return ( {detail} ); } function WorkflowQuickStepsCard({ row }: { readonly row: WorkflowQuickSteps }) { const gt = useGT(); return (
    {row.steps.map((step) => (
  • {step.name}
  • ))}
); } function WorkflowBeatCard({ environmentId, beat, child, nowMs, open, onSelect, onOpenThread, }: { readonly environmentId: EnvironmentId; readonly beat: WorkflowBeat; readonly child: WorkflowRunNode | null; readonly nowMs: number; readonly open: boolean; readonly onSelect: (runId: string | null) => void; readonly onOpenThread: (thread: WorkflowThreadTarget) => void; }) { const gt = useGT(); const m = useMessages(); const sessionId = useEnvironmentSessionId(environmentId); const under = beat.status === "running"; const length = formatDuration(elapsedOf(beat), m); const tries = beat.attempts > 1 ? ` · ${nthTry(beat.attempts, m)}` : ""; switch (beat.kind) { case "agent": return ( ); case "ask": { const answer = workflowAnswer(beat.result); const withdrawal = answer === null ? workflowWithdrawal(beat.result) : null; if (withdrawal !== null) return ( {withdrawal.reason === null ? gt("Withdrawn by {by}.", { by: withdrawal.by }) : gt("Withdrawn by {by}: {reason}", { by: withdrawal.by, reason: withdrawal.reason, })}

} >{`${gt("withdrawn")} · ${length}`}
); if (answer === null) return {`${gt("nobody answered")} · ${length}`}; // This client's own answer reads "You"; anyone else's, another device of yours too, its name. const who = isOwnWorkflowAnswer(answer, sessionId) ? null : answer.answeredBy; return (

{who !== null && answer.reason === null ? ( {who} said{" "} {answer.choice} . ) : who !== null ? ( {who} said{" "} {answer.choice} : {answer.reason} ) : answer.reason === null ? ( You said{" "} {answer.choice} . ) : ( You said{" "} {answer.choice} : {answer.reason} )}

{answer.answeredAt === null ? null : (

answered{" "}

)}
); } case "sleep": { if (!under) return {`${gt("slept")} · ${length}`}; const wakes = beat.detail === null ? Number.NaN : Date.parse(beat.detail); return ( } name={beat.name} sub={ Number.isFinite(wakes) && wakes > nowMs ? gt("wakes in {duration}", { duration: formatDuration(wholeSeconds(wakes - nowMs), m), }) : gt("about to wake") } /> ); } case "wait": if (!under) return {`${gt("waited")} · ${length}`}; return ( } name={beat.name} sub={gt("{duration} so far", { duration: length })} /> ); case "queue": if (!under) return {`${gt("queued")} · ${length}`}; return ( } name={beat.name} sub={`${queuedText(beat, m)} · ${length}`} /> ); case "run": { const title = beat.childRun?.title ?? beat.name; return ( } name={title} sub={ child === null ? `${beat.childRun?.workflow ?? ""} · ${length}` : `${child.run.workflow} · ${workflowRunNow(child, m)}` } action={ <> {child === null ? null : } } /> ); } case "step": { if (under) { return ( } name={beat.name} sub={`${gt("running for {duration}", { duration: length })}${tries}`} /> ); } const lines = workflowResultLines(beat.result); return ( }> {beat.status === "failed" ? `${gt("failed")} · ${length}` : length} {tries} ); } } } function WorkflowAgentCard({ environmentId, beat, open, onOpenThread, }: { readonly environmentId: EnvironmentId; readonly beat: WorkflowBeat; readonly open: boolean; readonly onOpenThread: (thread: WorkflowThreadTarget) => void; }) { const gt = useGT(); const m = useMessages(); const [all, setAll] = useState(false); const elsewhere = beat.thread !== null && beat.thread.environmentId !== null; const threadEnvironmentId = beat.thread?.environmentId == null ? environmentId : EnvironmentId.make(beat.thread.environmentId); const threadOpen = useWorkflowThreadOpen(environmentId, threadEnvironmentId); const shell = useQuietThreadShell( beat.thread === null ? null : scopeThreadRef(threadEnvironmentId, ThreadId.make(beat.thread.threadId)), ); const provider = useEnvironmentProviders() .get(threadEnvironmentId) ?.find((candidate) => candidate.instanceId === shell?.modelSelection.instanceId); const under = beat.status === "running"; const length = formatDuration(elapsedOf(beat), m); const summary = workflowAgentSummary(beat); const start = summary.said === null ? null : workflowSaidStart(summary.said, SAID_SHOWN); const liveWord = !under ? null : shell?.hasPendingUserInput === true ? gt("Asks you", { $context: "a workflow step waits on a person's answer" }) : shell?.hasPendingApprovals === true ? gt("waits for your approval") : shell?.runtime?.status === "preparing" || shell?.runtime?.status === "starting" ? gt("starting") : gt("working"); const sub = [ shell === null ? null : formatModelSlugName(shell.modelSelection.model), liveWord, length, beat.attempts > 1 ? nthTry(beat.attempts, m) : null, elsewhere ? gt("on {environment}", { environment: threadOpen.label ?? threadEnvironmentId }) : null, ] .filter((part) => part !== null) .join(" · "); return ( ) : ( ) } name={beat.name} sub={sub} action={ beat.thread === null ? null : threadOpen.open === "unavailable" ? ( Thread on {threadEnvironmentId} ) : ( ) } /> {beat.status === "failed" && beat.detail ? (

{beat.detail}

) : null} {summary.said === null ? null : ( // Set off from the head, so headings in the reply read as the agent's, not the page's.
{start !== null ? ( ) : null}
)} {summary.facts.length === 0 ? null : }
); } function WorkflowPauseCard({ run, name, attempts, reason, nowMs, disabled, onResume, kept, }: { readonly run: WorkflowRun; /** The step it stopped at, when the steps say which. */ readonly name: string | null; readonly attempts: number; readonly reason: string | null; readonly nowMs: number; readonly disabled: boolean; readonly onResume: () => void; /** Steps before it finished, and resuming keeps them. */ readonly kept: boolean; }) { const gt = useGT(); const m = useMessages(); const resumes = run.resumesAt === null ? Number.NaN : Date.parse(run.resumesAt); const next = run.retired ? gt("cannot go on until its workflow version is registered again") : !Number.isFinite(resumes) ? gt("waits for you to resume it") : resumes > nowMs ? gt("tries again by itself in {duration}", { duration: formatDuration(resumes - nowMs, m), }) : gt("about to try again by itself"); return ( } name={ name === null ? gt("Paused", { $context: "a workflow run is paused" }) : gt("Paused at {step}", { step: name }) } sub={ <> {attempts > 0 ? `${nthTry(attempts, m)} · ` : null} · {next} } action={ } /> {reason ?

{reason}

: null} {kept ? (

Only the failed step runs again; what finished before it is kept.

) : null}
); } function WorkflowQuestionCard({ environmentId, question, onOpenThread, inline = false, }: { readonly environmentId: EnvironmentId; readonly question: WorkflowQuestion; readonly onOpenThread: (thread: WorkflowThreadTarget) => void; /** Under its step in the run, which already says that it asks. */ readonly inline?: boolean; }) { const gt = useGT(); const view = readWorkflowQuestion(question); const drafts = useContext(AnswerDrafts); const [ownReason, setOwnReason] = useState(null); const draftKey = `${question.runId}:${question.name}:${question.askedAt}`; const reason = drafts === null ? ownReason : drafts.get(draftKey); const setReason = (next: string | null) => drafts === null ? setOwnReason(next) : drafts.set(draftKey, next); const [busy, setBusy] = useState(false); const canAnswer = useAtomValue( serverEnvironment.answerWorkflowQuestion.permissionAtom(environmentId), ); const answer = useAtomCommand(serverEnvironment.answerWorkflowQuestion, { label: "workflow answer", }); const threadEnvironmentId = question.thread?.environmentId == null ? environmentId : EnvironmentId.make(question.thread.environmentId); const reachable = useWorkflowThreadOpen(environmentId, threadEnvironmentId).open !== "unavailable"; const [reasonFor, setReasonFor] = useState(null); const choose = async (choice: WorkflowQuestionChoice) => { if (busy) return; const given = reason?.trim() ?? ""; // The server refuses it without a reason, so the field opens and says so instead. if (choice.requireReason && given === "") { setReasonFor(choice.value); if (reason === null) setReason(""); return; } setBusy(true); const result = await answer({ environmentId, input: { runId: question.runId, name: question.name, choice: choice.value, ...(given === "" ? {} : { reason: given }), }, }); setBusy(false); reportFailure(gt("Could not answer the question"), result); }; return ( {inline ? null : (

Needs you asked{" "} {" "} · the run waits for you

)}

{view.title}

{view.body ? ( ) : null} {view.links.length === 0 ? null : (
{view.links.map((link) => ( ))}
)}
{view.choices.map((choice, index) => (
{choice.description === null ? null : ( {choice.description} )}
))}
{reason === null || (question.thread !== null && reachable) ? (
{reason === null ? ( ) : null} {question.thread === null || !reachable ? null : ( )}
) : null} {reason === null ? null : (
setReason(event.currentTarget.value)} /> {reasonFor === null || (reason?.trim() ?? "") !== "" ? null : (

{reasonFor} needs a reason.

)}
)}
); }