feat(webui): port the dashboard (Phases 3-5)

Every page from the deleted Preact dashboard, rebuilt in Vue 3 + shadcn-vue.
The navigation restructure landed earlier on this branch; this is the surfaces
behind it, and the two are now one app.

Dashboard, Tasks (list and detail), Configuration split six ways, Logs,
Inspector, Mappings, Bindings, Workflows, Skills, Curators, Channels, chat.

Components, not files: docs/prds/dashboard-port-brief.md requires one
component, one job, one file, with shared state in a module beside it. So a
page file composes and holds nothing, and a shape repeated across panes becomes
its own component (LogRow, PageHeader, PanelLoading, WorkflowBar).

Behaviour that had to survive, because each was a fix:

- Live activity's detail is clamped to one line with the payload on the title.
  Unclamped, one row made the dashboard 7,481px tall.
- Each health card takes its own height. Equalising left a mostly-empty box
  taking a quarter of the first screen once setup was done.
- Tasks: `tab`/`attempt` live in the query string and are written with
  router.replace, so a tab click adds no history entry and does not remount.
  The list's deep-link reveal honours prefers-reduced-motion.
- LOG_LEVELS is a wire contract (the server matches that CSV server-side), used
  unchanged by both log panes.
- The chat panel's Phase 5 list: a FAB that is the only toggle, a morph whose
  scale, radius and position interpolate together, no scrim, no close button,
  Escape returning focus to the launcher, Stop only while streaming.
- Unconfigured is not broken. A 501 on /api/version or the log stream renders
  what is true ("Not configured on this deployment") rather than blank, and a
  read-only Configuration says so instead of offering controls that cannot work.

Three things the port decided rather than carried:

- Button gains an `attention` variant and Badge the five status tones, in the
  project's own cva. The pill's dot did not come across: the Badge's shape is
  the affordance, and the same tone now covers a trend indicator.
- The icon module is not ported. Its name-to-glyph lookup is the pattern
  shadcn-vue's rules call out as wrong, so icons come from @lucide/vue at the
  call site. The five bespoke glyphs have no consumer yet and become components
  if a page draws them.
- The theme control left the topbar for /system/appearance, per the approved
  navigation design. ThemeToggle.vue and Placeholder.vue are deleted rather
  than orphaned: every route now resolves to a real page.

Also fixes the bundle freshness check failing on the first build after every
change. ui/dist is committed, so nothing ignores it and Tailwind's content
detection scanned it, making each build an input to the next.
This commit is contained in:
sam committed 2026-09-20 20:04:55 +10:00
1 parent 5fe25045d1
commit b9daa01b4b
276 files changed
+12888 -563

No files matched your search

+75
View File
@@ -0,0 +1,75 @@
<script setup lang="ts">
import { computed } from "vue";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import JsonBlock from "./JsonBlock.vue";
import PanelError from "./PanelError.vue";
import PanelLoading from "./PanelLoading.vue";
import { CONFIG_SCHEMA, selectConfigEvent } from "./attempt-config";
import type { TaskEvent } from "./task-run";
/**
* The effective configuration one attempt ran under, taken from the task's own
* event stream. See attempt-config.ts for why this panel issues no request and
* why the selection is by kind AND attempt.
*/
const props = defineProps<{
events: TaskEvent[] | null | undefined;
attempt: number | null;
}>();
defineEmits<{ retry: [] }>();
const event = computed(() => selectConfigEvent(props.events, props.attempt));
// An unrecognised schema is shown verbatim with a note rather than
// reinterpreted, so a server-side bump degrades to the raw view.
const schema = computed(() => {
const data = event.value?.data || {};
return typeof data.schema === "string" ? data.schema : "";
});
const document = computed(() => event.value?.data?.document ?? {});
const recognised = computed(() => schema.value === CONFIG_SCHEMA);
</script>
<template>
<PanelLoading v-if="events === undefined" label="Loading this task's events…" />
<PanelError
v-else-if="events === null"
title="Could not load this task's events"
detail="The configuration is recorded as an event on the task, so it cannot be shown while the event stream is unreadable. archied did not answer — retry, or check the daemon."
@retry="$emit('retry')"
/>
<Empty v-else-if="!event">
<EmptyHeader>
<EmptyTitle>Not captured for this run</EmptyTitle>
<EmptyDescription>
Archie records the effective configuration when it dispatches an attempt. Attempt {{ attempt }} has no such
record — it predates the record, or the capture did not run. Nothing here says the run used the defaults.
</EmptyDescription>
</EmptyHeader>
</Empty>
<div v-else>
<p class="mb-2 max-w-[75ch] text-sm text-fg-muted">
This is attempt {{ event.attempt }}'s effective task-runtime configuration: a non-secret subset covering bot
identity, models, limits, budgets, dispatch, diff cap, notifications, forge host and tool policy. It is not the
dashboard configuration view — providers, repositories, identities, credentials and lock state are not part of
it.
</p>
<div class="mb-3 text-xs text-fg-muted">
Captured {{ event.at || "at an unrecorded time"
}}<span v-if="event.stage"> in stage {{ event.stage }}</span>
</div>
<JsonBlock v-if="recognised" :value="document" />
<template v-else>
<p class="mb-2 text-sm text-warn">
Recorded in an unknown schema{{ schema ? ` (${schema})` : "" }}. The raw payload is shown verbatim; nothing
here reinterprets it.
</p>
<JsonBlock :value="event.data" />
</template>
</div>
</template>
+57
View File
@@ -0,0 +1,57 @@
<script setup lang="ts">
import { computed } from "vue";
import { Badge } from "@/components/ui/badge";
import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
import { stageStatusMeta } from "./stage-rail";
import { useTaskRun } from "./use-task-run";
/**
* The attempts of this task, each a pill carrying its own status and stage
* count. Selection is the page's, and the stage rail reads the same response,
* so the two views of the same task's attempts can never disagree about which
* one is on screen.
*/
const run = useTaskRun();
const attempts = computed(() => run.attempts?.attempts ?? []);
const selected = computed(() => (run.attemptNumber == null ? "" : String(run.attemptNumber)));
function select(value: unknown): void {
// Re-pressing the selected attempt deselects it (a single-typed group answers
// ""), which is not an attempt: keep the selection rather than moving to
// none.
const n = Number(value);
if (Number.isInteger(n) && n > 0) run.selectAttempt(n);
}
function stageCount(attempt: { stages?: unknown[] }): string {
const n = (attempt.stages || []).length;
return `${n} stage${n === 1 ? "" : "s"}`;
}
</script>
<template>
<ToggleGroup
v-if="attempts.length"
type="single"
variant="outline"
:spacing="2"
:model-value="selected"
aria-label="Attempts of this task"
class="mb-4 flex-wrap"
@update:model-value="select"
>
<ToggleGroupItem
v-for="attempt in attempts"
:key="attempt.attempt"
:value="String(attempt.attempt)"
class="gap-2 rounded-full px-3"
>
<span class="font-medium">Attempt {{ attempt.attempt }}</span>
<Badge :variant="stageStatusMeta(attempt.status).kind">{{ stageStatusMeta(attempt.status).label }}</Badge>
<span class="text-xs text-fg-muted">{{ stageCount(attempt) }}</span>
</ToggleGroupItem>
</ToggleGroup>
</template>
+50
View File
@@ -0,0 +1,50 @@
<script setup lang="ts">
import { computed } from "vue";
import { ago } from "@/lib/format";
import ChangeFileTable from "./ChangeFileTable.vue";
import { captureLinks, totalsLabel } from "./changed-files";
import type { Capture, TaskRecord } from "./task-run";
/**
* One change capture: when and where it was taken, the forge coordinates it
* carries, and the files it recorded.
*/
const props = defineProps<{ capture: Capture; task: TaskRecord | null }>();
const links = computed(() => captureLinks(props.capture, props.task));
const prNumber = computed(() => props.capture.pr_number);
</script>
<template>
<section>
<div class="flex flex-wrap items-baseline justify-between gap-3">
<span class="text-sm font-medium">
{{ capture.captured_after ? `Captured after ${capture.captured_after}` : "Captured"
}}<span v-if="capture.stage"> in stage {{ capture.stage }}</span>
</span>
<span class="text-xs text-fg-muted">{{ capture.captured_at ? ago(capture.captured_at) : "" }}</span>
</div>
<div class="mt-2 mb-3 flex flex-wrap items-center gap-3 text-xs text-fg-muted">
<span class="font-mono">
<a v-if="links.repo" class="text-primary hover:underline" :href="links.repo" target="_blank" rel="noreferrer">
{{ capture.owner }}/{{ capture.repo }}
</a>
<template v-else>{{ capture.owner || "" }}/{{ capture.repo || "" }}</template>
</span>
<span v-if="capture.branch" class="font-mono">
{{ capture.branch }}<span v-if="capture.base"> → {{ capture.base }}</span>
</span>
<span v-if="capture.head_sha" class="font-mono">{{ String(capture.head_sha).slice(0, 8) }}</span>
<template v-if="prNumber">
<a v-if="links.pr" class="text-primary hover:underline" :href="links.pr" target="_blank" rel="noreferrer">
PR #{{ prNumber }}
</a>
<span v-else class="font-mono">PR #{{ prNumber }}</span>
</template>
<span>{{ totalsLabel(capture.totals) }}</span>
</div>
<ChangeFileTable :capture="capture" />
</section>
</template>
+58
View File
@@ -0,0 +1,58 @@
<script setup lang="ts">
import { computed } from "vue";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { fileStatusLabel } from "./changed-files";
import type { Capture } from "./task-run";
/**
* One capture's file entries. The counts beside a path are the diffstat the
* daemon recorded at the producer, not a reading of the file on disk now.
*/
const props = defineProps<{ capture: Capture }>();
const files = computed(() => props.capture.files || []);
const total = computed(() => Number(props.capture.totals?.files) || files.value.length);
</script>
<template>
<p v-if="!files.length" class="py-3 text-xs text-fg-muted">
This capture recorded no file entries{{ total ? `, though its totals cover ${total} file${total === 1 ? "" : "s"}` : ""
}}.
</p>
<template v-else>
<Table>
<TableHeader>
<TableRow>
<TableHead>Path</TableHead>
<TableHead>Change</TableHead>
<TableHead class="text-right">Added</TableHead>
<TableHead class="text-right">Deleted</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-for="(file, i) in files" :key="`${file.path}:${i}`">
<TableCell class="font-mono break-all whitespace-normal">
<span v-if="file.old_path" class="text-fg-muted">{{ file.old_path }} → </span>{{ file.path }}
</TableCell>
<TableCell>
{{ fileStatusLabel(file.status) }}
<!-- binary means "no textual hunks were recorded", not "this is a
binary file on disk": the counts beside it are still real. -->
<span v-if="file.binary" class="block text-xs text-fg-muted">no textual hunks</span>
</TableCell>
<TableCell class="text-right font-mono whitespace-nowrap">
{{ file.additions ? `+${file.additions}` : "—" }}
</TableCell>
<TableCell class="text-right font-mono whitespace-nowrap">
{{ file.deletions ? `−${file.deletions}` : "—" }}
</TableCell>
</TableRow>
</TableBody>
</Table>
<p v-if="capture.truncated" class="mt-2 text-xs text-fg-muted">
Showing the first {{ files.length }} of {{ total }} files. The totals above cover every file in this capture.
</p>
</template>
</template>
+72
View File
@@ -0,0 +1,72 @@
<script setup lang="ts">
import { computed } from "vue";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import ChangeCapture from "./ChangeCapture.vue";
import PanelError from "./PanelError.vue";
import PanelLoading from "./PanelLoading.vue";
import type { ChangesState, TaskRecord } from "./task-run";
/**
* What one attempt changed, as archied captured it.
*
* A capture with `found: true` and no readable payload is NOT reported as "no
* capture was recorded": the server reports `found` from the event's existence
* precisely so the two stay apart. One is a read failure, the other is a
* statement about the run -- and a statement this panel is not entitled to make
* on a read failure.
*/
const props = defineProps<{
state: ChangesState | null | undefined;
task: TaskRecord | null;
}>();
defineEmits<{ retry: [] }>();
const captures = computed(() => props.state?.captures || []);
// A capture event WAS recorded but its payload could not be read.
const undecodable = computed(() => props.state?.found === true && !captures.value.length);
const nothingRecorded = computed(() => !props.state?.found || !captures.value.length);
</script>
<template>
<PanelLoading v-if="state === undefined" label="Loading changed files…" />
<PanelError
v-else-if="state === null"
title="Could not load this attempt's changed files"
detail="archied did not answer for this attempt. It may be restarting — retry, or check the daemon."
@retry="$emit('retry')"
/>
<Empty v-else-if="undecodable">
<EmptyHeader>
<EmptyTitle>A change capture was recorded but could not be read</EmptyTitle>
<EmptyDescription>
This attempt has a change capture event, but this dashboard could not decode its payload. That is a read
failure, not a statement about what the attempt changed.
</EmptyDescription>
</EmptyHeader>
</Empty>
<Empty v-else-if="nothingRecorded">
<EmptyHeader>
<EmptyTitle>No change capture was recorded for this attempt</EmptyTitle>
<EmptyDescription>
Archie records what an attempt changed when it commits or pushes that work. Nothing was recorded here — the
attempt may predate capture, or it produced no commit. This is not the same as "no files changed".
</EmptyDescription>
</EmptyHeader>
</Empty>
<div v-else class="flex flex-col">
<ChangeCapture
v-for="(capture, i) in captures"
:key="`${capture.captured_at || ''}:${i}`"
:capture="capture"
:task="task"
:class="i > 0 ? 'mt-5 border-t border-border pt-4' : ''"
/>
</div>
</template>
+40
View File
@@ -0,0 +1,40 @@
<script setup lang="ts">
import JsonBlock from "./JsonBlock.vue";
import PanelError from "./PanelError.vue";
import PanelLoading from "./PanelLoading.vue";
import type { DebugState } from "./task-run";
/**
* Raw debug view: the stored task record and the task's events, verbatim.
*
* The events are deliberately NOT filtered to the selected attempt. A debug
* view that silently hid events would be worse than useless, so every event is
* shown and each carries its own `attempt` for the operator to attribute. The
* selected attempt is reported in the note and in the envelope's own `attempt`
* field; nothing here is summarised, projected or prettified beyond JSON
* indentation.
*/
defineProps<{
state: DebugState | null | undefined;
attempt: number | null;
}>();
defineEmits<{ retry: [] }>();
</script>
<template>
<PanelLoading v-if="state === undefined" label="Loading the stored record…" />
<PanelError
v-else-if="state === null"
title="Could not load the stored record"
detail="archied did not answer for this task's debug view. It may be restarting — retry, or check the daemon."
@retry="$emit('retry')"
/>
<div v-else>
<p class="mb-3 text-sm text-fg-muted">
The stored task record and its events, verbatim. Events are unfiltered on purpose: this is every event the task
has, and each one carries the attempt it belongs to. Attempt {{ attempt }} is the one selected above.
</p>
<JsonBlock :value="state" />
</div>
</template>
+18
View File
@@ -0,0 +1,18 @@
<script setup lang="ts">
/**
* A JSON payload, verbatim. Two panels show one (the attempt's recorded config
* and the debug view), and both must show exactly what the daemon stored --
* no projection, no prettifying beyond indentation.
*/
defineProps<{ value: unknown }>();
</script>
<template>
<!--
pre-wrap keeps the indentation the JSON is printed with while letting a
long value wrap instead of forcing the panel to scroll sideways.
-->
<pre
class="max-h-[60vh] overflow-auto rounded-sm border border-border bg-muted p-3 font-mono text-xs leading-normal whitespace-pre-wrap break-words"
>{{ JSON.stringify(value ?? {}, null, 2) }}</pre>
</template>
+19
View File
@@ -0,0 +1,19 @@
<script setup lang="ts">
import { Button } from "@/components/ui/button";
/**
* A panel whose read failed. A failed read is reported as a failed read: it is
* never dressed up as an empty result, which would be a claim about the run
* that nothing here can make.
*/
defineProps<{ title: string; detail: string }>();
defineEmits<{ retry: [] }>();
</script>
<template>
<div class="flex flex-col items-start gap-2 py-3">
<p class="font-medium">{{ title }}</p>
<p class="max-w-[60ch] text-sm text-fg-muted">{{ detail }}</p>
<Button variant="outline" @click="$emit('retry')">Retry</Button>
</div>
</template>
+11
View File
@@ -0,0 +1,11 @@
<script setup lang="ts">
/**
* A panel still in flight. One line, said in the panel's own words, because a
* panel that renders blank while it waits reads as a panel with nothing in it.
*/
defineProps<{ label: string }>();
</script>
<template>
<p class="py-5 text-sm text-fg-muted">{{ label }}</p>
</template>
+114
View File
@@ -0,0 +1,114 @@
<script setup lang="ts">
import { computed } from "vue";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Badge } from "@/components/ui/badge";
import PanelError from "./PanelError.vue";
import PanelLoading from "./PanelLoading.vue";
import StageRow from "./StageRow.vue";
import { stageStatusMeta } from "./stage-rail";
import { useTaskRun } from "./use-task-run";
import type { AttemptsState } from "./task-run";
/**
* The per-attempt stage rail.
*
* The rail is built from `GET /api/tasks/{id}/attempts`, which returns each
* attempt with its stages inline, so the selector and the rail can never
* disagree about which attempt is on screen. The rail only ever renders one
* attempt: merging two attempts by stage name is the failure this design
* exists to avoid.
*
* A per-run elapsed time is deliberately NOT rendered. `waiting_human` can span
* days, so wall time from an attempt's start is not a duration of work; only
* per-stage durations exist and only those are shown.
*/
const props = defineProps<{ state: AttemptsState | null | undefined }>();
defineEmits<{ retry: [] }>();
const run = useTaskRun();
const attempts = computed(() => props.state?.attempts || []);
const attempt = computed(() => attempts.value.find((a) => Number(a.attempt) === Number(run.attemptNumber)));
const meta = computed(() => stageStatusMeta(attempt.value?.status));
const stages = computed(() => attempt.value?.stages || []);
/** An attempt's start is rendered as an absolute instant, never as "started 2
* days ago": on a still-running attempt a relative stamp reads as two days of
* work, which is exactly the elapsed-time claim the design forbids. */
const startedAt = computed(() => {
const value = attempt.value?.started_at;
if (!value) return "start time not recorded";
const when = new Date(value);
if (Number.isNaN(when.getTime())) return "start time not recorded";
return `started ${when.toISOString().replace("T", " ").slice(0, 16)} UTC`;
});
</script>
<template>
<PanelLoading v-if="state === undefined" label="Loading this task's attempts…" />
<PanelError
v-else-if="state === null"
title="Could not load this task's attempts"
detail="archied did not answer for this task's run history. It may be restarting — retry, or check the daemon."
@retry="$emit('retry')"
/>
<template v-else>
<Empty v-if="!attempts.length">
<EmptyHeader>
<EmptyTitle>No attempts recorded</EmptyTitle>
<EmptyDescription>
This task has no recorded run. An attempt is written when a stage event is emitted, and none exist here.
</EmptyDescription>
</EmptyHeader>
</Empty>
<Empty v-else-if="!attempt">
<EmptyHeader>
<EmptyTitle>Attempt {{ run.attemptNumber }} is not recorded for this task</EmptyTitle>
<EmptyDescription>
This task recorded attempt {{ attempts.map((a) => a.attempt).join(", ") }}.
</EmptyDescription>
</EmptyHeader>
</Empty>
<div v-else>
<div class="mb-4 flex flex-wrap items-center gap-3">
<span class="font-semibold">Attempt {{ attempt.attempt }}</span>
<Badge :variant="meta.kind">{{ meta.label }}</Badge>
<span class="text-xs text-fg-muted">{{ startedAt }}</span>
</div>
<ol v-if="stages.length" :aria-label="`Stages recorded in attempt ${attempt.attempt}`">
<StageRow
v-for="(stage, i) in stages"
:key="`${stage.seq ?? i}:${stage.name}`"
:stage="stage"
:attempt-number="attempt.attempt"
:events="run.events"
/>
</ol>
<Empty v-else>
<EmptyHeader>
<EmptyTitle>No stages recorded for this attempt</EmptyTitle>
<EmptyDescription>The attempt exists, but nothing recorded a stage for it.</EmptyDescription>
</EmptyHeader>
</Empty>
<p class="mt-3 max-w-[70ch] text-xs text-fg-muted">
<strong>ok</strong> means the stage returned without error. Archie records no exit code and does not verify
that the work was correct, so this is a progress status, not a check result.
</p>
</div>
<!-- Rendered in every loaded state, the empty ones included: a deployment
where every event predates the attempt column answers with no attempts
at all, and reporting "No attempts recorded" there without the count
would present unattributable history as nothing having happened. -->
<p v-if="Number(state.unattributed_events) > 0" class="mt-3 max-w-[70ch] text-xs text-fg-muted">
{{ Number(state.unattributed_events) }} event{{ Number(state.unattributed_events) === 1 ? "" : "s" }} on this
task predate attempt attribution and cannot be assigned to a run.
</p>
</template>
</template>
+73
View File
@@ -0,0 +1,73 @@
<script setup lang="ts">
import { computed } from "vue";
import { Badge } from "@/components/ui/badge";
import { cn } from "@/lib/utils";
import { agentReports, stageStatusMeta } from "./stage-rail";
import { duration } from "./timeline-event";
import type { Stage, TaskEvent } from "./task-run";
/**
* One stage of one attempt: its name, its status word, its own duration, the
* error it returned if it failed, and what the agent said about itself.
*
* No checkmark and no exit status: see stage-rail.ts for what a stage status
* does and does not mean.
*/
const props = defineProps<{
stage: Stage;
attemptNumber: number;
events: TaskEvent[] | null | undefined;
}>();
const meta = computed(() => stageStatusMeta(props.stage.status));
const ran = computed(() => duration(props.stage.duration_ms));
const reports = computed(() => agentReports(props.events, props.attemptNumber, props.stage.name));
// The node carries the status as a shape, the same way the label's own kind
// does; the connector behind it is what makes the stages read as one run rather
// than as unrelated rows.
const nodeClass = computed(() =>
cn(
"relative mt-1 ml-1 size-3.5 shrink-0 rounded-full border-2 bg-card",
props.stage.status === "ok"
? "border-ok"
: props.stage.status === "failed"
? "border-danger"
: props.stage.status === "interrupted"
? "border-warn"
: props.stage.status === "running"
? "border-info"
: "border-border-strong",
),
);
</script>
<template>
<li
class="relative grid grid-cols-[1.75rem_1fr] gap-2 pb-4 before:absolute before:top-4 before:bottom-0 before:left-[0.6875rem] before:w-px before:bg-border-strong last:before:hidden max-[700px]:grid-cols-1 max-[700px]:border-b max-[700px]:border-border max-[700px]:pb-3 max-[700px]:before:hidden"
>
<span :class="nodeClass" aria-hidden="true" class="max-[700px]:hidden" />
<div class="min-w-0">
<div class="flex flex-wrap items-center gap-2">
<!-- A stage name is one unbroken token often enough that it has to be
allowed to break, or a long one pushes the status and duration off
the row. -->
<span class="min-w-0 font-mono font-medium break-words">{{ stage.name || "(unnamed stage)" }}</span>
<Badge :variant="meta.kind">{{ meta.label }}</Badge>
<span class="text-xs text-fg-muted">{{ ran ? `ran for ${ran}` : "duration not recorded" }}</span>
</div>
<div
v-if="stage.error"
class="mt-2 rounded-sm border-l-[3px] border-danger bg-danger-soft px-3 py-2 text-sm break-words whitespace-pre-wrap text-fg-muted"
>
{{ stage.error }}
</div>
<div v-for="(report, i) in reports" :key="i" class="mt-2 text-xs text-fg-muted">
<span>Agent's own report, not verified by archie: </span>
{{ [report.title, report.detail].filter(Boolean).join(" · ") }}
</div>
</div>
</li>
</template>
+96
View File
@@ -0,0 +1,96 @@
<script setup lang="ts">
import { Play, RefreshCw } from "@lucide/vue";
import { computed } from "vue";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Spinner } from "@/components/ui/spinner";
import { statusLabel } from "@/lib/task-meta";
import { useTaskRun } from "./use-task-run";
/**
* Restarting a task as a new run.
*
* The control is only live where the task itself offers the action: a new run
* can only start from a parked task, so anywhere else the page says why rather
* than offering a button that will be refused. The refusal that does arrive
* (the task moved between the read and the click) is rendered from the error
* class, because "you cannot do that", "your session has expired" and "the
* daemon did not answer" need three different responses from the operator.
*/
const props = defineProps<{ id: string }>();
const run = useTaskRun();
// The action's own kind decides how loud the button is: `retry` is primary in
// the served catalogue, and would be quiet on the day it is not.
const variant = computed(() => (run.retryKind === "primary" ? "default" : "outline"));
const confirmText = computed(
() =>
`Start a new run for "${run.task?.title || `task ${props.id}`}"? This is a new attempt, and the previous attempt's commits are discarded.`,
);
const unavailable = computed(() => {
if (run.canRetry || run.taskList === undefined) return "";
return run.task
? `A new run can only start from a parked task. This task is ${statusLabel(run.task.status ?? "")}.`
: "This task's operator controls could not be read, so a new run cannot be started from here.";
});
const errorText = computed(() => {
const err = run.retryError;
if (!err) return "";
if (err.kind === "session-expired") return "Your session has expired. Reload to sign in.";
if (err.kind === "refused") return `${err.message} — this run cannot be restarted from here.`;
return `${err.message} — try again, or check the daemon.`;
});
</script>
<template>
<section class="mb-4 flex flex-wrap items-center gap-3" aria-label="Start a new run">
<AlertDialog>
<AlertDialogTrigger as-child>
<Button :variant="variant" :disabled="!run.canRetry || run.retryBusy" title="Retry this task as a new run">
<Spinner v-if="run.retryBusy" data-icon="inline-start" />
<Play v-else data-icon="inline-start" />
{{ run.retryBusy ? "Starting…" : "Start a new run" }}
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Start a new run</AlertDialogTitle>
<AlertDialogDescription>{{ confirmText }}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction @click="run.performRetry">
<RefreshCw data-icon="inline-start" />
Start a new run
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
<p class="min-w-0 flex-1 basis-[22rem] text-sm text-fg-muted">
Starts a new attempt for this task: a fresh worktree reset onto the base branch. The previous attempt's
commits are discarded — they are not carried into the new run.
</p>
<p v-if="unavailable" class="min-w-0 flex-1 basis-[22rem] text-sm text-fg-muted">{{ unavailable }}</p>
<Alert v-if="errorText" variant="destructive" class="basis-full">
<AlertDescription>{{ errorText }}</AlertDescription>
</Alert>
</section>
</template>
+24
View File
@@ -0,0 +1,24 @@
<script setup lang="ts">
import { TabsList, TabsTrigger } from "@/components/ui/tabs";
import { RUN_TABS } from "./task-run";
/**
* The run page's tab bar. It owns no state and renders no panel: the open tab
* is the page's, carried in the query string, and this renders the list that
* switches it. It must sit inside a `Tabs`, which supplies the roving focus
* and the selection model -- a `TabsTrigger` outside a `TabsList` is not a tab.
*
* Keyboard behaviour is the WAI-ARIA tabs pattern with automatic activation,
* which `Tabs` provides: the list is one stop in the page's tab order,
* Left/Right move between tabs and select as they go, Home/End jump to the
* ends. Automatic activation is right here because every panel is a local
* render, not a fetch: there is no cost to switching.
*/
</script>
<template>
<TabsList variant="line" class="w-full justify-start">
<TabsTrigger v-for="tab in RUN_TABS" :key="tab.id" :value="tab.id">{{ tab.label }}</TabsTrigger>
</TabsList>
</template>
+66
View File
@@ -0,0 +1,66 @@
<script setup lang="ts">
import { ArrowLeft } from "@lucide/vue";
import { computed } from "vue";
import { RouterLink } from "vue-router";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
/**
* A run page that cannot be opened, said plainly. There are two ways in: the
* id in the path is not a task id at all, or archied answers that no such task
* exists. Both are one page head and one card, so they are one component and
* only the words differ.
*/
const props = defineProps<{
kind: "invalid" | "missing";
/** The id as it arrived in the path. */
raw?: string;
}>();
const copy = computed(() =>
props.kind === "invalid"
? {
title: "Not a task id",
sub: "The run view addresses one task by its id: /tasks/42",
empty: `“${props.raw ?? ""}” is not a task id`,
detail: "A task id is a positive whole number. Nothing was requested.",
}
: {
title: "Task not found",
sub: `No task with id ${props.raw ?? ""} in this deployment.`,
empty: `Nothing is recorded for task ${props.raw ?? ""}`,
detail: "archied answered that this task does not exist, so there is no run history to show.",
},
);
</script>
<template>
<div>
<div class="mb-5 flex flex-wrap items-start justify-between gap-5">
<div>
<h1 class="text-3xl font-semibold tracking-[-0.03em]">{{ copy.title }}</h1>
<p class="mt-2 text-sm text-fg-muted">{{ copy.sub }}</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<Button variant="outline" as-child>
<RouterLink to="/tasks">
<ArrowLeft data-icon="inline-start" />
Back to tasks
</RouterLink>
</Button>
</div>
</div>
<Card>
<CardContent>
<Empty>
<EmptyHeader>
<EmptyTitle>{{ copy.empty }}</EmptyTitle>
<EmptyDescription>{{ copy.detail }}</EmptyDescription>
</EmptyHeader>
</Empty>
</CardContent>
</Card>
</div>
</template>
+61
View File
@@ -0,0 +1,61 @@
<script setup lang="ts">
import { computed } from "vue";
import { useRoute } from "vue-router";
import { Card, CardContent } from "@/components/ui/card";
import { Tabs } from "@/components/ui/tabs";
import AttemptSelector from "./AttemptSelector.vue";
import StartNewRun from "./StartNewRun.vue";
import TabBar from "./TabBar.vue";
import TaskDetailNotice from "./TaskDetailNotice.vue";
import TaskHeader from "./TaskHeader.vue";
import TaskMetaBar from "./TaskMetaBar.vue";
import TaskNotes from "./TaskNotes.vue";
import TaskRunPanels from "./TaskRunPanels.vue";
import { parseTaskId } from "./task-run";
import { provideTaskRun } from "./use-task-run";
/**
* The per-task run detail page, reached at /tasks/:id.
*
* One page, one task: which run it is showing, what each stage of that run did,
* its log, what it changed, the configuration it ran under, and the raw record.
* The task id rides in the path and the view state (`tab`, `attempt`) rides in
* the query string, so every view of this page is a deep link that survives a
* reload -- /tasks/42?tab=changes&attempt=2.
*
* This file composes the page and nothing else: the reads and the caches are
* use-task-run, the head, meta bar, notes, restart control, attempt selector,
* tab bar and panel area are each their own component. The router keys this
* component on the path (App.vue), so a different :id gets a fresh instance
* rather than diffing the last task's state in place.
*/
const route = useRoute();
const rawId = computed(() => String(route.params.id ?? ""));
const taskId = computed(() => parseTaskId(rawId.value));
const run = provideTaskRun(taskId);
</script>
<template>
<TaskDetailNotice v-if="taskId === null" kind="invalid" :raw="rawId" />
<TaskDetailNotice v-else-if="run.missing" kind="missing" :raw="rawId" />
<div v-else>
<TaskHeader :id="rawId" />
<TaskMetaBar />
<TaskNotes :id="rawId" />
<StartNewRun :id="rawId" />
<AttemptSelector />
<Card>
<CardContent>
<Tabs class="gap-4" :model-value="run.tab" @update:model-value="run.setTab">
<TabBar />
<TaskRunPanels :id="rawId" />
</Tabs>
</CardContent>
</Card>
</div>
</template>
+90
View File
@@ -0,0 +1,90 @@
<script lang="ts">
import { attentionStatusIds, statusIds } from "@/lib/task-meta";
// The vocabulary is the server catalog, not a hand-synced copy: the "needs
// you" grouping and the set of known statuses come straight from task-meta so
// a status added on the backend shows up here without a frontend change.
// "needs_you" is a UI pseudo-status (work waiting on a human), so it is
// prepended rather than stored in the catalog.
//
// Both are read at call time rather than captured at import. The catalog
// arrives after this module loads, so module-level constants here would freeze
// the defaults for the life of the process -- which is what they did, leaving
// the task filter unable to see a served status no matter when it landed.
export function taskStatuses(): Set<string> {
return new Set(["needs_you", ...statusIds()]);
}
/**
* A ?status= value, kept only when the catalog knows it: the query string is
* operator input, and an unknown status would filter the whole board away with
* no control showing why.
*/
export function initialTaskFilter(requested: string | null | undefined): string {
return requested && taskStatuses().has(requested) ? requested : "";
}
export function taskMatchesStatus(task: { status?: string }, status: string): boolean {
if (!status) return true;
if (status === "needs_you") return attentionStatusIds().has(task.status ?? "");
return task.status === status;
}
</script>
<script setup lang="ts">
import { computed } from "vue";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { statusList } from "@/lib/task-meta";
/**
* The search box and the status filter. It holds no state of its own: the
* search text and the status both belong to the page, because the query string
* owns the status and the table needs the search text to filter.
*/
// A select item cannot carry an empty value, so "no filter" is spelled with a
// sentinel and translated at the edges of this component.
const ALL_STATUSES = "all";
const props = defineProps<{ status: string; search: string }>();
const emit = defineEmits<{
"update:status": [status: string];
"update:search": [search: string];
}>();
const selected = computed(() => props.status || ALL_STATUSES);
function selectStatus(value: unknown) {
emit("update:status", typeof value === "string" && value !== ALL_STATUSES ? value : "");
}
</script>
<template>
<div class="flex flex-wrap items-center gap-2">
<Input
type="search"
:model-value="props.search"
aria-label="Search tasks by title or repository"
placeholder="Search by title or repo…"
class="w-55 max-[480px]:w-full"
@update:model-value="emit('update:search', String($event))"
/>
<Select :model-value="selected" @update:model-value="selectStatus">
<SelectTrigger aria-label="Filter by status" class="w-45 max-[480px]:w-full">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem :value="ALL_STATUSES">All statuses</SelectItem>
<SelectItem value="needs_you">Needs you</SelectItem>
<SelectItem v-for="entry in statusList()" :key="entry.id" :value="entry.id">
{{ entry.label }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</div>
</template>
+50
View File
@@ -0,0 +1,50 @@
<script setup lang="ts">
import { ArrowLeft, RefreshCw } from "@lucide/vue";
import { computed } from "vue";
import { RouterLink } from "vue-router";
import { Button } from "@/components/ui/button";
import { useTaskRun } from "./use-task-run";
/**
* The run page's head: which task this is, and the two things an operator does
* from here -- go back, or re-read everything.
*/
const props = defineProps<{ id: string }>();
const run = useTaskRun();
const title = computed(() => run.task?.title || `Task #${props.id}`);
const sub = computed(() => {
const task = run.task;
return [
`One run of task ${props.id}`,
task?.workflow ? `${task.workflow} workflow` : "",
task?.repo ? `${task.owner}/${task.repo}` : "",
]
.filter(Boolean)
.join(" · ");
});
</script>
<template>
<div class="mb-5 flex flex-wrap items-start justify-between gap-5">
<div>
<h1 class="text-3xl font-semibold tracking-[-0.03em]">{{ title }}</h1>
<p class="mt-2 text-sm text-fg-muted">{{ sub }}</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<Button variant="outline" as-child>
<RouterLink to="/tasks">
<ArrowLeft data-icon="inline-start" />
Back to tasks
</RouterLink>
</Button>
<Button @click="run.refreshAll">
<RefreshCw data-icon="inline-start" />
Refresh
</Button>
</div>
</div>
</template>
+99
View File
@@ -0,0 +1,99 @@
<script setup lang="ts">
import { computed, useId } from "vue";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { LOG_LEVELS } from "@/lib/log";
import type { LogFilters } from "./task-run";
/**
* The log pane's filter row, and the attempt it is showing.
*
* The attempt is not a filter: the page selects the attempt and this row
* reports which one it is, so the pane can never read attempt 1's log while
* claiming attempt 2.
*
* The two "everything" options need a sentinel value: an empty string is how a
* Select spells "nothing selected", so `""` cannot also be an item. The CSV
* LOG_LEVELS carries stays exactly as it is -- the wire contract is the values,
* not the widgets.
*/
const ALL = "__all__";
const props = defineProps<{
filters: LogFilters;
stages: string[];
attempt: number;
}>();
const emit = defineEmits<{ filter: [next: LogFilters] }>();
const levelId = useId();
const stageId = useId();
const levelOptions = computed(() => LOG_LEVELS.map((level) => ({ value: level.value || ALL, label: level.label })));
const levelValue = computed(() => props.filters.level || ALL);
const stageValue = computed(() => props.filters.stage || ALL);
function change(patch: Partial<LogFilters>): void {
emit("filter", { ...props.filters, ...patch });
}
function setLevel(value: unknown): void {
change({ level: String(value) === ALL ? "" : String(value) });
}
function setStage(value: unknown): void {
change({ stage: String(value) === ALL ? "" : String(value) });
}
</script>
<template>
<div class="flex flex-wrap items-center gap-3 border-b border-border pb-3">
<span class="text-sm font-medium">{{ attempt > 0 ? `Attempt ${attempt}` : "Current attempt" }}</span>
<div class="inline-flex items-center gap-2">
<Label :for="levelId" class="text-xs font-normal tracking-[0.05em] text-fg-muted uppercase">Level</Label>
<Select :model-value="levelValue" @update:model-value="setLevel">
<SelectTrigger :id="levelId" size="sm" aria-label="Filter log entries by level">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem v-for="option in levelOptions" :key="option.value" :value="option.value">
{{ option.label }}
</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</div>
<div class="inline-flex items-center gap-2">
<Label :for="stageId" class="text-xs font-normal tracking-[0.05em] text-fg-muted uppercase">Stage</Label>
<Select :model-value="stageValue" @update:model-value="setStage">
<SelectTrigger :id="stageId" size="sm" aria-label="Filter log entries by stage">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectGroup>
<SelectItem :value="ALL">All stages</SelectItem>
<SelectItem v-for="stage in stages" :key="stage" :value="stage">{{ stage }}</SelectItem>
</SelectGroup>
</SelectContent>
</Select>
</div>
<!-- A stage filter is a narrowing, not a clean sweep: only lines a stage
tagged carry a stage, and agent/tool output never does. Saying so
beside the control is what keeps a sparse result from reading as a
broken pane. -->
<p v-if="filters.stage" class="basis-full text-xs text-fg-muted">
A stage filter matches only log lines that record a stage. Agent and tool output carries none, so it is not
shown while this filter is set.
</p>
<p v-else-if="!stages.length" class="basis-full text-xs text-fg-muted">
This attempt recorded no stage names, so the stage filter has nothing to match.
</p>
</div>
</template>
+152
View File
@@ -0,0 +1,152 @@
<script setup lang="ts">
import { computed } from "vue";
import LogRow from "@/base/LogRow.vue";
import { Button } from "@/components/ui/button";
import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { api } from "@/lib/api";
import PanelLoading from "./PanelLoading.vue";
import TaskLogFilters from "./TaskLogFilters.vue";
import { EMPTY_LOG_FILTERS, type LogFilters, type LogState } from "./task-run";
/**
* A task attempt's log pane.
*
* Three read outcomes are kept apart, because only one of them is about the
* operator's configuration or about this attempt:
*
* disabled -- this process cannot read task logs at all (deployment)
* found: false -- a reader exists and this attempt has no log file
* entries: [] -- a log exists and nothing matches the current filter
*
* The filter controls render ABOVE all three, and above the loading and failed
* states too. Putting them inside the success branch is how a deployment that
* cannot read logs ends up showing an empty filtered pane instead of saying so.
* They render when the page can act on a filter change (`filterable`); a
* control that filters nothing is worse than no control. The ordering rule
* belongs here either way.
*/
const props = withDefaults(
defineProps<{
state: LogState | null | undefined;
/** The attempt this pane is showing, 0 meaning the current one. */
attempt: number;
stages?: string[];
filters?: LogFilters;
/** False when the host holds no filter state (the list page's inline pane). */
filterable?: boolean;
taskId?: string | number | null;
}>(),
{
stages: () => [],
filters: () => ({ ...EMPTY_LOG_FILTERS }),
filterable: true,
taskId: null,
},
);
defineEmits<{ retry: []; filter: [next: LogFilters] }>();
const resolvedAttempt = computed(() => Number(props.attempt) || Number(props.state?.attempt) || 0);
/** The pane's state, decided once so the announcement and the body can never
* disagree about which case is on screen. */
const view = computed(() => {
const state = props.state;
if (state === undefined) return { kind: "loading" as const, status: "Loading this attempt's log" };
if (state === null) return { kind: "failed" as const, status: "This attempt's log could not be loaded" };
// A reader exists in this process but the attempt has no log file. That is a
// fact about the attempt, and saying "logging was not enabled" here (which
// this panel used to do) told the operator to go and change a setting that
// was already correct.
if (state.found === false && !state.disabled) {
return { kind: "nolog" as const, status: "No log recorded for this attempt" };
}
// This process cannot read task logs at all. That IS about the deployment,
// and it is the only case where the pane may say so.
if (state.disabled) return { kind: "disabled" as const, status: "This dashboard cannot read task logs" };
const entries = state.entries || [];
if (!entries.length) {
return {
kind: "empty" as const,
status: "This attempt's log has no entries matching the current filter",
entries,
};
}
return {
kind: "entries" as const,
status: `${entries.length} log entr${entries.length === 1 ? "y" : "ies"} shown`,
entries,
};
});
const download = computed(() =>
props.taskId != null ? api.taskLogDownloadURL(String(props.taskId), resolvedAttempt.value || null) : null,
);
</script>
<template>
<div>
<TaskLogFilters
v-if="filterable"
class="mb-3"
:filters="filters"
:stages="stages"
:attempt="resolvedAttempt"
@filter="$emit('filter', $event)"
/>
<!-- The pane's state, announced once. It is a live region for STATE, not
for the log's lines: putting aria-live on the list itself would read
every entry aloud on every load, which for a 500-entry pane is
unusable. -->
<p class="sr-only" role="status" aria-live="polite" aria-atomic="true">{{ view.status }}</p>
<PanelLoading v-if="view.kind === 'loading'" label="Loading attempt log…" />
<div v-else-if="view.kind === 'failed'" class="flex flex-col items-start gap-2 py-3">
<p class="text-sm text-fg-muted">Could not load this attempt's log.</p>
<Button variant="outline" @click="$emit('retry')">Retry</Button>
</div>
<Empty v-else-if="view.kind === 'nolog'">
<EmptyHeader>
<EmptyTitle>No log recorded for this attempt</EmptyTitle>
<EmptyDescription>This attempt produced no output, or it has not started writing yet.</EmptyDescription>
</EmptyHeader>
</Empty>
<Empty v-else-if="view.kind === 'disabled'">
<EmptyHeader>
<EmptyTitle>No persisted log for this attempt</EmptyTitle>
<EmptyDescription>
This dashboard cannot read task logs. The service that owns the log files is not reporting a log reader.
</EmptyDescription>
</EmptyHeader>
</Empty>
<Empty v-else-if="view.kind === 'empty'">
<EmptyHeader>
<EmptyTitle>Nothing recorded</EmptyTitle>
<EmptyDescription>This attempt's log file has no entries matching the current filter.</EmptyDescription>
</EmptyHeader>
<EmptyContent v-if="download">
<Button variant="outline" size="sm" as-child>
<a :href="download" download>Download log</a>
</Button>
</EmptyContent>
</Empty>
<template v-else>
<!-- The detail page's log is the primary content, so it takes a framed
read surface of its own and the tallest one on the page. -->
<div class="max-h-[62vh] overflow-y-auto rounded-sm border border-border bg-card px-2">
<LogRow v-for="(entry, i) in view.entries" :key="i" :entry="entry" />
</div>
<Button v-if="download" variant="outline" size="sm" class="mt-3" as-child>
<a :href="download" download>Download log</a>
</Button>
</template>
</div>
</template>
+74
View File
@@ -0,0 +1,74 @@
<script setup lang="ts">
import { computed } from "vue";
import { Badge } from "@/components/ui/badge";
import type { StatusKind } from "@/lib/status";
import { statusKind, statusLabel } from "@/lib/task-meta";
import { useTaskRun } from "./use-task-run";
/**
* The task's lifecycle status, the attempt this page is showing, and the forge
* coordinates. All three come from reads the page already holds, so the bar
* costs no request of its own.
*
* "Not read" and "loading" are kept apart from "no status": the task list is
* a list of the 100 most recently updated, so a task outside it is a fact
* about the read, not a fact about the task.
*/
const run = useTaskRun();
// The server owns the status vocabulary and answers with the same five kinds
// the Badge draws, which is what makes the cast honest rather than a guess.
const taskKind = computed<StatusKind>(() => statusKind(run.task?.status ?? "") as StatusKind);
const taskStatusLabel = computed(() => statusLabel(run.task?.status ?? ""));
const attemptText = computed(() => {
if (run.attempts === null) return "run history unreadable";
if (run.attempts === undefined) return "loading…";
if (run.attemptNumber == null) return "none recorded";
return `attempt ${run.attemptNumber} of ${run.currentAttempt ?? run.attemptNumber}`;
});
</script>
<template>
<div class="-mt-2 mb-4 flex flex-wrap items-center gap-4 text-sm">
<span class="inline-flex items-center gap-2">
<span class="text-xs tracking-[0.05em] text-fg-muted uppercase">Task status</span>
<span v-if="run.taskList === undefined" class="text-fg-muted">loading…</span>
<Badge v-else-if="run.task" :variant="taskKind">{{ taskStatusLabel }}</Badge>
<span v-else class="text-fg-muted">not read</span>
</span>
<span class="inline-flex items-center gap-2">
<span class="text-xs tracking-[0.05em] text-fg-muted uppercase">Attempt</span>
<span>{{ attemptText }}</span>
</span>
<a
v-if="run.task?.repo_url"
class="text-primary hover:underline"
:href="run.task.repo_url"
target="_blank"
rel="noreferrer"
>
{{ run.task.owner }}/{{ run.task.repo }}
</a>
<a
v-if="run.task?.issue_url && run.task?.issue_number"
class="text-primary hover:underline"
:href="run.task.issue_url"
target="_blank"
rel="noreferrer"
>
Issue #{{ run.task.issue_number }}
</a>
<a
v-if="run.task?.pr_url && run.task?.pr_number"
class="text-primary hover:underline"
:href="run.task.pr_url"
target="_blank"
rel="noreferrer"
>
PR #{{ run.task.pr_number }}
</a>
</div>
</template>
+39
View File
@@ -0,0 +1,39 @@
<script setup lang="ts">
import { AlertTriangle } from "@lucide/vue";
import { computed } from "vue";
import { Alert, AlertDescription } from "@/components/ui/alert";
import { useTaskRun } from "./use-task-run";
/**
* Two things the page can say about its own reads, both warnings rather than
* errors: the page still works, with less than it would like.
*
* The task list is the 100 most recently updated, so a task outside it is
* normal, and saying so is what stops an operator reading the missing status
* and controls as the task having none.
*/
const props = defineProps<{ id: string }>();
const run = useTaskRun();
const note = computed(() => {
if (run.taskList === null) {
return "The task list could not be read, so this page cannot show the task's current status or its operator controls. The run history below comes from the task's own endpoints.";
}
if (Array.isArray(run.taskList) && !run.task) {
return `Task ${props.id} is not among the tasks this dashboard lists (the list covers the 100 most recently updated). Its recorded attempts are shown below; the Debug tab holds the stored record verbatim.`;
}
return "";
});
</script>
<template>
<!-- warn-soft rather than the Alert's default surface: this is a caution the
operator should read past, not a panel to look at. -->
<Alert v-if="note" class="mb-4 border-warn bg-warn-soft">
<AlertTriangle />
<AlertDescription>{{ note }}</AlertDescription>
</Alert>
</template>
+146
View File
@@ -0,0 +1,146 @@
<script lang="ts">
/**
* The task fields this folder reads. One shape for the list, its table, its
* filters and the row itself, declared on the component that renders it.
*/
export interface Task {
id: number | string;
title?: string;
owner?: string;
repo?: string;
repo_url?: string;
issue_number?: number;
issue_url?: string;
pr_number?: number;
pr_url?: string;
source?: string;
status?: string;
workflow?: string;
stage?: string;
attempt?: number;
created_at?: string;
updated_at?: string;
actions?: string[];
}
</script>
<script setup lang="ts">
import { computed } from "vue";
import { RouterLink, useRouter } from "vue-router";
import { Badge } from "@/components/ui/badge";
import { TableCell, TableRow } from "@/components/ui/table";
import { ago } from "@/lib/format";
import type { StatusKind } from "@/lib/status";
import { statusKind, statusLabel } from "@/lib/task-meta";
import TaskRowActions from "./TaskRowActions.vue";
/**
* One task. The whole row opens the task's run detail, which is why it carries
* link semantics and a keyboard path of its own: every control inside it has to
* stop the event on its way out, or activating a button would also navigate.
*/
const props = withDefaults(defineProps<{ task: Task; showRepo?: boolean }>(), { showRepo: true });
const emit = defineEmits<{ done: [taskId: Task["id"]] }>();
const router = useRouter();
// Lifecycle vocabulary is the served catalog, never a hand-synced copy: the
// label and the severity both come from task-meta, so a status the backend
// knows renders with the right words and the right colour.
const label = computed(() => statusLabel(props.task.status ?? ""));
const kind = computed(() => statusKind(props.task.status ?? "") as StatusKind);
const title = computed(() => props.task.title || "untitled task");
// Chat-sourced work has no forge issue behind it, so there is no page to open
// and the number stands on its own.
const issueHref = computed(() => {
if (props.task.source === "chat") return "";
if (!props.task.issue_url || !props.task.issue_number) return "";
return props.task.issue_url;
});
function open() {
void router.push(`/tasks/${props.task.id}`);
}
</script>
<template>
<TableRow
:id="`task-row-${props.task.id}`"
tabindex="0"
role="link"
:aria-label="`Open the run detail for ${title}`"
class="cursor-pointer"
@click="open"
@keydown.enter.prevent="open"
@keydown.space.prevent="open"
>
<!--
The repo column is dropped when every visible row shares it, so the width
it would repeat goes to the title instead. Truncated rather than wrapped:
an owner/name is one token and breaking it mid-word reads as two.
-->
<TableCell v-if="props.showRepo" class="text-fg-muted max-w-40 truncate">
<a
v-if="props.task.repo_url"
class="hover:text-foreground hover:underline"
:href="props.task.repo_url"
target="_blank"
rel="noreferrer"
:title="`Open ${props.task.owner}/${props.task.repo} on the forge`"
@click.stop
@keydown.stop
>
{{ props.task.owner }}/{{ props.task.repo }}
</a>
<template v-else>{{ props.task.owner }}/{{ props.task.repo }}</template>
</TableCell>
<TableCell class="text-fg-muted">
<a
v-if="issueHref"
class="hover:text-foreground hover:underline"
:href="issueHref"
target="_blank"
rel="noreferrer"
:title="`Open issue #${props.task.issue_number} on the forge`"
@click.stop
@keydown.stop
>
#{{ props.task.issue_number }}
</a>
<template v-else>#{{ props.task.issue_number }}</template>
</TableCell>
<!--
The floor belongs on the link, not the cell: a table cell ignores
min-width, so a floor there is dropped and the title wraps to one word a
line as soon as the table is narrower than its columns.
-->
<TableCell class="w-full whitespace-normal">
<RouterLink
class="inline-block min-w-40 hover:underline"
:to="`/tasks/${props.task.id}`"
title="Open the run detail for this task"
@click.stop
@keydown.stop
>
{{ title }}
</RouterLink>
</TableCell>
<TableCell>
<Badge :variant="kind">{{ label }}</Badge>
</TableCell>
<TableCell class="text-fg-muted">{{ props.task.workflow || "—" }}</TableCell>
<TableCell class="text-fg-muted">{{ props.task.stage || "—" }}</TableCell>
<TableCell
class="text-fg-muted"
:title="props.task.created_at ? `Created ${ago(props.task.created_at)}` : ''"
>
{{ ago(props.task.updated_at) }}
</TableCell>
<TableCell>
<TaskRowActions :task="props.task" @done="emit('done', $event)" />
</TableCell>
</TableRow>
</template>
+195
View File
@@ -0,0 +1,195 @@
<script setup lang="ts">
import { computed, ref } from "vue";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from "@/components/ui/alert-dialog";
import { Button } from "@/components/ui/button";
import { api, classifyActionError, type ActionErrorKind } from "@/lib/api";
import { actionFor, type ActionMeta } from "@/lib/task-meta";
import type { Task } from "./TaskRow.vue";
/**
* The lifecycle controls for one task. A task offers whatever the server says
* it offers, so the decisions here are presentation only: which variant a
* control wears, whether it needs confirming, and how a refusal reads.
*/
/** A control with its forge target already resolved. */
interface Control {
id: string;
label: string;
kind: string;
confirm?: string;
href: string;
}
type ControlVariant = "default" | "ghost" | "destructive";
const props = defineProps<{ task: Task }>();
const emit = defineEmits<{ done: [taskId: Task["id"]] }>();
const inFlight = ref(false);
const error = ref<{ kind: ActionErrorKind; message: string } | null>(null);
// The dialog's open flag and the action it will run are two refs, not one:
// pressing the dialog's action closes it, and that close clears the open flag
// before the action's own handler reads it.
const confirming = ref<string | null>(null);
const confirmingId = ref<string | null>(null);
const controls = computed<Control[]>(() =>
(props.task.actions ?? [])
.map((id) => actionFor(id))
.filter((meta): meta is ActionMeta => meta !== null)
.map((meta) => ({ ...meta, href: meta.kind === "link" ? forgeLink(meta.id) : "" })),
);
const confirmingMeta = computed(() => (confirmingId.value ? actionFor(confirmingId.value) : null));
const confirmText = computed(() =>
confirmingMeta.value?.confirm
? confirmingMeta.value.confirm.replaceAll("{title}", props.task.title || "this task")
: "",
);
const confirmLabel = computed(() => confirmingMeta.value?.label || "Confirm");
// A refused action ("you can't do that" -- bad input, a conflicting task state)
// is the operator's to correct; a broken one (5xx, network drop, timeout) is
// the daemon's, and says so. An expired session is neither, and gets its own
// treatment above rather than either framing.
const errorText = computed(() => {
if (!error.value) return "";
if (error.value.kind === "refused") return `${error.value.message} — you can't do that.`;
return `${error.value.message} — try again, or check the daemon.`;
});
// A link control points at the forge artefact the action names. Chat-sourced
// work has no issue on a forge, and a task that never opened a pull request has
// no PR to point at, so the control is disabled rather than a dead link.
function forgeLink(id: string): string {
if (id === "open_pr") {
return props.task.pr_url && props.task.pr_number ? props.task.pr_url : "";
}
if (id === "open_issue") {
if (props.task.source === "chat" || !props.task.issue_number) return "";
return props.task.issue_url ?? "";
}
return "";
}
function variantFor(kind: string): ControlVariant {
if (kind === "quiet") return "ghost";
if (kind === "danger") return "destructive";
return "default";
}
// A control that names a consequence is confirmed first; the two that only open
// a forge page are not, because they change nothing.
function request(id: string) {
error.value = null;
if (actionFor(id)?.confirm) {
confirmingId.value = id;
confirming.value = id;
return;
}
void run(id);
}
async function run(id: string) {
confirming.value = null;
inFlight.value = true;
error.value = null;
try {
// The route path and the API both address a task by string; the list serves
// ids as numbers, so the row's own id is narrowed once, here.
await api.taskAction(String(props.task.id), id);
emit("done", props.task.id);
} catch (err) {
error.value = classifyActionError(err);
} finally {
inFlight.value = false;
}
}
function onConfirmationOpen(open: boolean) {
if (!open) confirming.value = null;
}
// A full reload, not a router navigation: the point is to re-establish the
// session with whatever is in front of archied, which a client-side route
// change would leave exactly as it was.
function reloadPage() {
window.location.reload();
}
</script>
<template>
<div class="flex flex-col items-end gap-1">
<Alert
v-if="error"
variant="destructive"
class="w-56 gap-0.5 px-2 py-1.5 text-xs whitespace-normal"
>
<template v-if="error.kind === 'session-expired'">
<AlertTitle class="text-xs">Your session has expired</AlertTitle>
<AlertDescription class="text-xs">
<Button size="xs" variant="outline" @click.stop="reloadPage">Reload to sign in</Button>
</AlertDescription>
</template>
<AlertDescription v-else class="text-xs">{{ errorText }}</AlertDescription>
</Alert>
<!--
One line, never wrapped: three controls on two lines doubled the height of
every actionable row. Keystrokes stop at this container rather than
bubbling to the row, which would open the task as well as press the button.
-->
<div class="flex items-center gap-1" @keydown.stop>
<template v-for="control in controls" :key="control.id">
<template v-if="control.kind === 'link'">
<Button v-if="control.href" as-child variant="outline" size="sm">
<a :href="control.href" target="_blank" rel="noreferrer" @click.stop>{{ control.label }}</a>
</Button>
<Button v-else variant="outline" size="sm" disabled :title="`${control.label} is unavailable`">
{{ control.label }}
</Button>
</template>
<Button
v-else
:variant="variantFor(control.kind)"
size="sm"
:disabled="inFlight"
@click.stop="request(control.id)"
>
{{ control.label }}
</Button>
</template>
</div>
<AlertDialog :open="confirming !== null" @update:open="onConfirmationOpen">
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>{{ confirmLabel }} this task?</AlertDialogTitle>
<AlertDialogDescription>{{ confirmText }}</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Keep it</AlertDialogCancel>
<AlertDialogAction
:variant="variantFor(confirmingMeta?.kind ?? '')"
@click="confirmingId && run(confirmingId)"
>
{{ confirmLabel }}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
</template>
+87
View File
@@ -0,0 +1,87 @@
<script setup lang="ts">
import { TabsContent } from "@/components/ui/tabs";
import { Empty, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import AttemptConfig from "./AttemptConfig.vue";
import ChangedFiles from "./ChangedFiles.vue";
import DebugView from "./DebugView.vue";
import PanelError from "./PanelError.vue";
import PanelLoading from "./PanelLoading.vue";
import StageRail from "./StageRail.vue";
import TaskLogs from "./TaskLogs.vue";
import { RUN_TABS } from "./task-run";
import { useTaskRun } from "./use-task-run";
/**
* The run page's panel area: one panel per tab, each reading the attempt the
* page has selected.
*
* The rail owns its own loading, failure and empty states. Every other panel is
* scoped to one attempt, and "no attempt" is a claim only a successful read of
* the run history can make -- a read still in flight is not a verdict either,
* and a failed read is reported as a failed read.
*/
const props = defineProps<{ id: string }>();
const run = useTaskRun();
function retryLogs(): void {
if (run.attemptNumber != null) run.loadLogs(run.attemptNumber, { force: true });
}
function retryChanges(): void {
if (run.attemptNumber != null) run.loadChanges(run.attemptNumber, { force: true });
}
function retryDebug(): void {
if (run.attemptNumber != null) run.loadDebug(run.attemptNumber, { force: true });
}
</script>
<template>
<TabsContent v-for="tab in RUN_TABS" :key="tab.id" :value="tab.id">
<StageRail v-if="tab.id === 'stages'" :state="run.attempts" @retry="run.loadAttempts" />
<template v-else>
<PanelLoading v-if="run.attempts === undefined" label="Loading this task's attempts…" />
<PanelError
v-else-if="run.attempts === null"
title="Could not load this task's attempts"
detail="This panel reads one attempt, and the task's run history could not be read."
@retry="run.loadAttempts"
/>
<Empty v-else-if="run.attemptNumber == null">
<EmptyHeader>
<EmptyTitle>No attempt recorded</EmptyTitle>
<EmptyDescription>
This task has no recorded run, so there is nothing to read for an attempt.
</EmptyDescription>
</EmptyHeader>
</Empty>
<TaskLogs
v-else-if="tab.id === 'log'"
:state="run.logState"
:attempt="run.attemptNumber"
:stages="run.stageNames"
:filters="run.filters"
:task-id="props.id"
@filter="run.setFilters"
@retry="retryLogs"
/>
<ChangedFiles v-else-if="tab.id === 'changes'" :state="run.changesState" :task="run.task" @retry="retryChanges" />
<AttemptConfig
v-else-if="tab.id === 'config'"
:events="run.events"
:attempt="run.attemptNumber"
@retry="run.loadEvents"
/>
<DebugView v-else-if="tab.id === 'debug'" :state="run.debugState" :attempt="run.attemptNumber" @retry="retryDebug" />
</template>
</TabsContent>
</template>
+53
View File
@@ -0,0 +1,53 @@
<script setup lang="ts">
import { computed } from "vue";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import TaskRow, { type Task } from "./TaskRow.vue";
/**
* The board. It renders the rows it is given and nothing else: which rows are
* visible, and which state stands in when none are, are the page's decisions.
* The `state` slot is drawn in the body's place so the columns stay announced
* while the table has no rows to show.
*/
const props = withDefaults(defineProps<{ tasks: Task[]; showRepo?: boolean }>(), { showRepo: true });
const emit = defineEmits<{ done: [taskId: Task["id"]] }>();
const columns = computed(() => (props.showRepo ? 8 : 7));
</script>
<template>
<Table>
<TableHeader>
<TableRow>
<TableHead v-if="props.showRepo">Repo</TableHead>
<TableHead>Issue</TableHead>
<!-- Title takes the slack: it is the only column that distinguishes one
row from another, so it should be the one that grows. -->
<TableHead class="w-full">Title</TableHead>
<TableHead>Status</TableHead>
<TableHead>Workflow</TableHead>
<TableHead>Stage</TableHead>
<TableHead>Last activity</TableHead>
<TableHead>Action</TableHead>
</TableRow>
</TableHeader>
<TableBody>
<TableRow v-if="!props.tasks.length">
<TableCell :colspan="columns">
<slot name="state" />
</TableCell>
</TableRow>
<template v-else>
<TaskRow
v-for="task in props.tasks"
:key="task.id"
:task="task"
:show-repo="props.showRepo"
@done="emit('done', $event)"
/>
</template>
</TableBody>
</Table>
</template>
+191
View File
@@ -0,0 +1,191 @@
<script lang="ts">
// The shell's global reduced-motion rule switches CSS transitions and
// animations, NOT the JS smooth scroll this page performs when it reveals a
// deep-linked row. The decision therefore has to be made here, in JavaScript,
// and is exported so it can be tested directly (jsdom implements neither
// matchMedia nor scrollIntoView).
export function prefersReducedMotion(): boolean {
return typeof window !== "undefined" && window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches === true;
}
export function revealBehavior(): ScrollBehavior {
return prefersReducedMotion() ? "auto" : "smooth";
}
</script>
<script setup lang="ts">
import { RefreshCw } from "@lucide/vue";
import { computed, nextTick, onMounted, ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { api } from "@/lib/api";
import TaskFilters, { initialTaskFilter, taskMatchesStatus } from "./TaskFilters.vue";
import type { Task } from "./TaskRow.vue";
import TaskTable from "./TaskTable.vue";
import TasksState from "./TasksState.vue";
import TasksSummary from "./TasksSummary.vue";
/**
* The task board: every issue archied has picked up, and where it stands. It
* owns the two things the query string names -- which status is filtered and
* which task a link pointed at -- and composes the rest.
*/
const route = useRoute();
const router = useRouter();
// null means loading: an empty list and a list that has not arrived are
// different states, and only one of them is worth a spinner.
const tasks = ref<Task[] | null>(null);
const error = ref<string | null>(null);
const search = ref("");
const statusQuery = computed(() => (typeof route.query.status === "string" ? route.query.status : ""));
const requestedTaskId = computed(() => {
const raw = route.query.task;
const id = Number(typeof raw === "string" ? raw : NaN);
return Number.isSafeInteger(id) && id > 0 ? id : null;
});
// The filter follows the URL as well as writing to it: a dashboard link or a
// back-button step has to move the control, not just load the page behind it.
const status = ref(initialTaskFilter(statusQuery.value));
watch(statusQuery, (value) => {
status.value = initialTaskFilter(value);
});
const visible = computed(() =>
(tasks.value ?? []).filter((task) => {
if (!taskMatchesStatus(task, status.value)) return false;
const needle = search.value.trim().toLowerCase();
if (!needle) return true;
return `${task.title ?? ""} ${task.repo ?? ""}`.toLowerCase().includes(needle);
}),
);
// The repo column only earns its width when the rows differ. On a
// single-repository deployment it repeated one value down every row while the
// title was squeezed, so it goes when every visible row shares it.
const showRepo = computed(() => {
const rows = visible.value;
return rows.length < 2 || rows.some((task) => task.repo !== rows[0].repo);
});
const state = computed<"loading" | "error" | "empty" | "no-match">(() => {
if (error.value) return "error";
if (tasks.value === null) return "loading";
if (!tasks.value.length) return "empty";
return "no-match";
});
onMounted(() => {
void load();
});
async function load() {
error.value = null;
try {
tasks.value = await api.tasks<Task[]>();
} catch (err) {
error.value = String((err as Error).message || err);
tasks.value = null;
}
}
// A filter change is a query-only route change, so it must not remount the
// list: the table keeps its identity and only its rows move. An empty status is
// dropped from the query rather than written as `?status=`.
function setStatus(value: string) {
status.value = initialTaskFilter(value);
const query = { ...route.query };
if (status.value) query.status = status.value;
else delete query.status;
void router.replace({ query });
}
function clearFilters() {
search.value = "";
setStatus("");
}
// A deep link (?task=<id>) reveals the row it names: focus it, so keyboard and
// screen-reader users land where the link pointed, then scroll it into view.
// Once per id -- a reload after a row action must not move the page under the
// operator.
const revealed = ref<number | null>(null);
watch([requestedTaskId, tasks], () => {
const id = requestedTaskId.value;
if (id === null || tasks.value === null || revealed.value === id) return;
revealed.value = id;
void reveal(id);
});
async function reveal(id: number) {
// The row has to be in the DOM before it can be found or scrolled to.
await nextTick();
requestAnimationFrame(() => {
const row = document.getElementById(`task-row-${id}`);
if (!row) return;
row.focus({ preventScroll: true });
// Optional call: focusing a deep-linked row is a nicety, and not every
// environment implements scrollIntoView on an element.
row.scrollIntoView?.({ block: "center", behavior: revealBehavior() });
});
}
</script>
<template>
<div>
<div class="mb-5 flex flex-wrap items-start justify-between gap-5">
<div>
<h1 class="text-3xl font-semibold tracking-[-0.03em]">Tasks</h1>
<p class="text-fg-muted mt-2 text-sm">Every issue archied has picked up, and where it stands.</p>
</div>
<div class="flex flex-wrap items-center gap-2">
<Button @click="load">
<RefreshCw data-icon="inline-start" />
Refresh
</Button>
</div>
</div>
<Card v-if="error">
<CardContent>
<TasksState kind="error" :detail="error" @retry="load" />
</CardContent>
</Card>
<template v-else>
<TasksSummary v-if="tasks" :tasks="tasks" />
<Card>
<CardHeader>
<CardTitle>All tasks</CardTitle>
<CardDescription>Click a row for its timeline</CardDescription>
</CardHeader>
<CardContent class="flex flex-col gap-3">
<TaskFilters
:status="status"
:search="search"
@update:status="setStatus"
@update:search="search = $event"
/>
<!--
An action can change what a task is and what it still offers, so the
list is re-read from the server rather than patched in place: the
server owns both the status vocabulary and the controls a status
allows.
-->
<TaskTable :tasks="visible" :show-repo="showRepo" @done="load">
<template #state>
<TasksState :kind="state" @retry="load" @clear="clearFilters" />
</template>
</TaskTable>
</CardContent>
</Card>
</template>
</div>
</template>
+55
View File
@@ -0,0 +1,55 @@
<script setup lang="ts">
import { RefreshCw } from "@lucide/vue";
import { computed } from "vue";
import { Button } from "@/components/ui/button";
import { Empty, EmptyContent, EmptyDescription, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
import { Spinner } from "@/components/ui/spinner";
/**
* What the board says when it has no rows to draw: still fetching, unreachable,
* nothing picked up yet, or nothing matching the filters. One component for all
* four, so no surface invents its own wording for the same situation.
*/
type StateKind = "loading" | "error" | "empty" | "no-match";
const props = defineProps<{ kind: StateKind; detail?: string | null }>();
const emit = defineEmits<{ retry: []; clear: [] }>();
const copy = computed(() => {
if (props.kind === "error") {
return { title: "Cannot reach archied", description: props.detail || "The daemon did not answer." };
}
if (props.kind === "empty") {
return { title: "No tasks yet", description: "Tasks appear here once archied picks up an issue to work." };
}
if (props.kind === "no-match") {
return { title: "No matching tasks", description: "Try a different search or status filter." };
}
return { title: "Loading tasks…", description: "" };
});
</script>
<template>
<div
v-if="props.kind === 'loading'"
class="text-fg-muted flex items-center justify-center gap-2 p-6 text-sm"
>
<Spinner />
{{ copy.title }}
</div>
<Empty v-else>
<EmptyHeader>
<EmptyTitle>{{ copy.title }}</EmptyTitle>
<EmptyDescription>{{ copy.description }}</EmptyDescription>
</EmptyHeader>
<EmptyContent v-if="props.kind !== 'empty'">
<Button v-if="props.kind === 'error'" variant="outline" size="sm" @click="emit('retry')">
<RefreshCw data-icon="inline-start" />
Retry
</Button>
<Button v-else variant="ghost" size="sm" @click="emit('clear')">Clear filters</Button>
</EmptyContent>
</Empty>
</template>
+60
View File
@@ -0,0 +1,60 @@
<script setup lang="ts">
import { computed } from "vue";
import StatTile from "@/base/StatTile.vue";
import { attentionStatusIds } from "@/lib/task-meta";
import type { Task } from "./TaskRow.vue";
/**
* The four numbers that say what the board holds, counted from the tasks the
* page already has rather than from an aggregate endpoint: the same list feeds
* the table, so a tile and a row can never disagree.
*/
const props = defineProps<{ tasks: Task[] }>();
const counts = computed(() => {
const tally: Record<string, number> = {};
for (const task of props.tasks) {
const status = task.status ?? "";
tally[status] = (tally[status] ?? 0) + 1;
}
return tally;
});
const total = computed(() => props.tasks.length);
const working = computed(() => counts.value.running ?? 0);
const delivered = computed(() => (counts.value.merged ?? 0) + (counts.value.pr_open ?? 0));
// "Needs you" is the server's grouping, not a local pair of ids: the same set
// backs the ?status=needs_you filter, so the tile and the filter cannot drift.
const needsYou = computed(() => {
const attention = attentionStatusIds();
return Object.entries(counts.value).reduce((sum, [status, n]) => (attention.has(status) ? sum + n : sum), 0);
});
</script>
<template>
<div class="mb-5 grid grid-cols-[repeat(auto-fit,minmax(220px,1fr))] gap-4">
<StatTile
label="Total tasks"
:value="total"
:compare="total ? 'Everything archied has ever picked up' : 'No tasks yet'"
/>
<StatTile
label="Working now"
:value="working"
:compare="total ? `${working} of ${total} in progress` : 'Nothing running'"
/>
<StatTile
label="Needs you"
:value="needsYou"
:compare="needsYou ? 'Parked or awaiting a reply' : 'Nothing is blocked'"
good-direction="down"
/>
<StatTile
label="Delivered"
:value="delivered"
:compare="total ? `${Math.round((delivered / total) * 100)}% of all tasks` : 'No tasks yet'"
/>
</div>
</template>
+31
View File
@@ -0,0 +1,31 @@
<script setup lang="ts">
import { computed } from "vue";
import { ago } from "@/lib/format";
import { describeTimelineEvent } from "./timeline-event";
import type { TaskEvent } from "./task-run";
/**
* One entry in a task's event timeline: what happened, any detail the event
* carries, and when.
*
* It renders an `<li>`, so its host supplies the list. The words come from
* describeTimelineEvent, which the stage rail's agent reports read too, so a
* timeline and a rail can never describe the same event differently.
*/
const props = defineProps<{ event: TaskEvent }>();
const line = computed(() => describeTimelineEvent(props.event));
</script>
<template>
<li class="flex items-start gap-3">
<span class="mt-[5px] size-2 shrink-0 rounded-full bg-primary" aria-hidden="true" />
<div>
<div class="text-sm font-medium">{{ line.title }}</div>
<div v-if="line.detail" class="mt-0.5 text-xs text-fg-muted">{{ line.detail }}</div>
<div class="mt-0.5 text-xs text-fg-subtle">{{ ago(event.at) }}</div>
</div>
</li>
</template>
+29
View File
@@ -0,0 +1,29 @@
/**
* The per-attempt effective configuration.
*
* There is no config endpoint: the document arrives inside the task's event
* stream, which the page already fetches for the stage rail's agent reports and
* the timeline. So this panel issues no request of its own and adds nothing to
* the API client contract.
*
* Selection is by kind AND attempt. Selecting by kind alone would show the
* newest attempt's configuration on every attempt, which is exactly the
* merge-attempts bug the attempt column exists to prevent.
*/
import type { TaskEvent } from "./task-run";
// The schema name is owned by the daemon (events.ConfigCapturedSchema in
// internal/events/events.go). A payload in an unrecognised schema is shown
// verbatim with a note rather than reinterpreted, so a server-side bump
// degrades to the raw view instead of rendering something wrong.
export const CONFIG_SCHEMA = "archie/task-config@1";
export function selectConfigEvent(
events: TaskEvent[] | null | undefined,
attempt: number | null,
): TaskEvent | null {
return (
(events || []).find((ev) => ev && ev.kind === "config_captured" && Number(ev.attempt) === Number(attempt)) ||
null
);
}
+50
View File
@@ -0,0 +1,50 @@
/**
* Changed files for one attempt, from `GET /api/tasks/{id}/changes`.
*
* The capture happens at the producer: archied records the diffstat at the
* moment it commits or pushes an attempt's work. So the honest empty state is
* "no capture was recorded for this attempt", never "no files changed" -- a run
* that predates capture, or one that produced no commit, has no capture and
* nothing here can turn that into a claim about the repository.
*/
import type { Capture, CaptureTotals, TaskRecord } from "./task-run";
// The change-status ids are a wire vocabulary owned by the daemon
// (internal/domain/workflow/task/changes.go). Only the words are the
// dashboard's: an id added on the server renders as its raw id rather than
// breaking the row. The old test suite pinned the id set on both sides so a
// one-sided rename failed instead of drifting.
const FILE_STATUS: Record<string, string> = {
added: "Added",
modified: "Modified",
deleted: "Deleted",
renamed: "Renamed",
typechange: "Type changed",
};
export function fileStatusLabel(status: string | undefined): string {
return (status && FILE_STATUS[status]) || status || "unknown";
}
/**
* The forge links come from the same projection the task list uses: the task's
* own repo/PR URLs, or the capture's if the server attached them. A link is
* rendered only when there is a URL to render -- a capture with no forge
* coordinates shows its owner/repo and PR number as text rather than a dead
* link.
*/
export function captureLinks(capture: Capture | undefined, task: TaskRecord | null): { repo: string; pr: string } {
const repo = capture?.repo_url || task?.repo_url || "";
const samePR =
task && String(task.pr_number ?? "") !== "" && String(task.pr_number) === String(capture?.pr_number ?? "");
const pr = capture?.pr_url || (samePR ? task?.pr_url || "" : "");
return { repo, pr };
}
export function totalsLabel(totals: CaptureTotals = {}): string {
const files = Number(totals.files) || 0;
const parts = [`${files} file${files === 1 ? "" : "s"}`];
if (totals.additions) parts.push(`+${totals.additions}`);
if (totals.deletions) parts.push(`−${totals.deletions}`);
return parts.join(" · ");
}
+53
View File
@@ -0,0 +1,53 @@
/**
* What a stage status means, and what it does not.
*
* A stage fails when its Go function returned an error. There is NO exit code,
* no pass/fail verdict, and no notion of "the work was correct" -- a stage that
* returned nil after producing a poor diff is `ok`. So the rail never renders
* a checkmark, a badge or an exit status; it renders the status word, the
* duration and the error text, and says plainly what `ok` means. The agent's
* own self-reported outcome (`agent_finish`) is shown separately, labelled as
* the agent's report rather than as archie's verdict.
*/
import type { StatusKind } from "@/lib/status";
import { describeTimelineEvent, type TimelineLine } from "./timeline-event";
import type { TaskEvent } from "./task-run";
export interface StageStatusMeta {
label: string;
kind: StatusKind;
}
const STAGE_STATUS: Record<string, StageStatusMeta> = {
ok: { label: "ok", kind: "ok" },
failed: { label: "failed", kind: "danger" },
interrupted: { label: "interrupted", kind: "warn" },
running: { label: "running", kind: "info" },
unknown: { label: "unknown", kind: "idle" },
};
export function stageStatusMeta(status?: string | null): StageStatusMeta {
return STAGE_STATUS[status ?? ""] || { label: status || "unknown", kind: "idle" };
}
/**
* agentReports returns the agent's own account of a stage: the `agent_finish`
* events whose attempt and stage both match. Returning an array rather than one
* value keeps a stage that ran two agents honest instead of showing the last.
*/
export function agentReports(
events: TaskEvent[] | null | undefined,
attemptNumber: number | null | undefined,
stage: string | undefined,
): TimelineLine[] {
return (events || [])
.filter(
(ev) =>
ev &&
ev.kind === "agent_finish" &&
Number(ev.attempt) === Number(attemptNumber) &&
(ev.stage || "") === (stage || ""),
)
.map((ev) => describeTimelineEvent(ev));
}
+194
View File
@@ -0,0 +1,194 @@
/**
* The task run page's model: what the page can show, the shapes it reads from
* the daemon, and the URL contract that carries the open tab and the pinned
* attempt.
*
* One task id, one page. The id rides in the path and the view state (`tab`,
* `attempt`) rides in the query string, so every view of this page is a deep
* link that survives a reload -- /tasks/42?tab=changes&attempt=2.
*
* The attempt is the unit of every panel. Nothing here merges two attempts:
* the rail, the log, the capture and the config are all selected by attempt,
* and the two views of the same task's attempts (the selector and the rail)
* come from a single response.
*/
import type { LocationQuery, LocationQueryRaw } from "vue-router";
import type { LogEntry } from "@/lib/log";
export interface TaskRunTab {
id: string;
label: string;
}
export const RUN_TABS: TaskRunTab[] = [
{ id: "stages", label: "Stages" },
{ id: "log", label: "Log" },
{ id: "changes", label: "Changed files" },
{ id: "config", label: "Configuration" },
{ id: "debug", label: "Debug" },
];
const TAB_IDS = new Set(RUN_TABS.map((tab) => tab.id));
/** The task record as the task list serves it. */
export interface TaskRecord {
id: number | string;
title?: string;
status?: string;
workflow?: string;
owner?: string;
repo?: string;
repo_url?: string;
issue_number?: number;
issue_url?: string;
pr_number?: number;
pr_url?: string;
actions?: string[];
}
/** One stage of one attempt, as `GET /api/tasks/{id}/attempts` returns it. */
export interface Stage {
seq?: number;
name?: string;
status?: string;
duration_ms?: number;
error?: string;
}
export interface Attempt {
attempt: number;
status?: string;
started_at?: string;
duration_ms?: number;
stages?: Stage[];
}
/**
* The run history. `current_attempt` is 0 on the wire for a task with no run
* at all, which is not an attempt number.
*/
export interface AttemptsState {
attempts?: Attempt[];
current_attempt?: number;
unattributed_events?: number;
}
/** One event off the task's stream, as much of it as this page reads. */
export interface TaskEvent {
kind?: string;
type?: string;
stage?: string;
workflow?: string;
attempt?: number;
at?: string;
detail?: string;
data?: Record<string, unknown>;
}
export interface LogFilters {
level: string;
stage: string;
}
/** The attempt log read's three outcomes: disabled, not found, or entries. */
export interface LogState {
found?: boolean;
disabled?: boolean;
attempt?: number;
entries?: LogEntry[];
}
export interface CaptureFile {
path?: string;
old_path?: string;
status?: string;
binary?: boolean;
additions?: number;
deletions?: number;
}
export interface CaptureTotals {
files?: number;
additions?: number;
deletions?: number;
}
/** One recorded change capture for an attempt. */
export interface Capture {
captured_after?: string;
captured_at?: string;
stage?: string;
owner?: string;
repo?: string;
repo_url?: string;
branch?: string;
base?: string;
head_sha?: string;
pr_number?: number;
pr_url?: string;
totals?: CaptureTotals;
files?: CaptureFile[];
truncated?: boolean;
}
export interface ChangesState {
found?: boolean;
captures?: Capture[];
}
/** The stored task record and its events, verbatim: nothing here projects it. */
export type DebugState = Record<string, unknown>;
export function parseTaskId(raw: unknown): number | null {
const value = String(raw ?? "").trim();
if (!/^\d+$/.test(value)) return null;
const n = Number(value);
return Number.isSafeInteger(n) && n > 0 ? n : null;
}
export function initialTab(query: LocationQuery | undefined): string {
const requested = String(query?.tab ?? "");
return TAB_IDS.has(requested) ? requested : RUN_TABS[0].id;
}
/**
* `?attempt=2` pins attempt 2. An absent, empty or non-numeric value follows
* whatever the server reports as current, and 0 is the wire's own spelling of
* "the current attempt" (taskLogTarget, internal/webui/api_tasks_logs.go), so
* it selects the current attempt rather than a nonexistent attempt 0.
*/
export function initialAttempt(query: LocationQuery | undefined): number | null {
const raw = query?.attempt;
if (raw == null || raw === "") return null;
const n = Number(raw);
return Number.isInteger(n) && n > 0 ? n : null;
}
/** The query string a tab and an attempt are addressed by. */
export function runQuery(tab: string, attempt: number | null): LocationQueryRaw {
const query: LocationQueryRaw = { tab: tab || RUN_TABS[0].id };
if (attempt) query.attempt = String(attempt);
return query;
}
export function attemptKey(id: number, attempt: number | null): string {
return `${id}|${Number(attempt) || 0}`;
}
export const EMPTY_LOG_FILTERS: LogFilters = { level: "", stage: "" };
/**
* The identity of a log read: a task, an attempt, and the filters that produced
* the response. Keying by task alone cannot represent two attempts -- the bug
* this replaces -- and keying without the filters would serve attempt 2's
* unfiltered log in answer to a filtered request.
*/
export function logCacheKey(
id: number,
attempt: number | null,
filters: LogFilters = EMPTY_LOG_FILTERS,
): string {
const applied = filters || EMPTY_LOG_FILTERS;
return [id, Number(attempt) || 0, applied.level || "", applied.stage || ""].join("|");
}
+125
View File
@@ -0,0 +1,125 @@
/**
* The timeline's vocabulary: one human line per event kind.
*
* The formatters live here rather than inside a component because two surfaces
* read them -- the timeline row and the stage rail's agent reports -- and a
* second copy would eventually disagree with this one.
*/
import type { TaskEvent } from "./task-run";
function words(value: unknown): string {
return String(value || "event")
.replaceAll("_", " ")
.replace(/\b\w/g, (letter) => letter.toUpperCase());
}
/** Exported so the stage rail renders a duration exactly the way the timeline
* does; a second formatter would eventually disagree with this one. */
export function duration(milliseconds: unknown): string {
const ms = Number(milliseconds);
if (!Number.isFinite(ms) || ms < 0) return "";
if (ms < 1000) return `${Math.round(ms)} ms`;
const seconds = ms / 1000;
// Under 60s: 1 dp when seconds < 10, 0 dp otherwise (40.6 s, but 41 s).
if (seconds < 60) return `${seconds.toFixed(seconds < 10 ? 1 : 0)} s`;
const roundedSeconds = Math.round(seconds);
const minutes = Math.floor(roundedSeconds / 60);
const remSec = roundedSeconds % 60;
if (minutes < 60) return remSec === 0 ? `${minutes} min` : `${minutes} min ${remSec} s`;
const hours = Math.floor(minutes / 60);
const remMin = minutes - hours * 60;
return remMin === 0 ? `${hours} h` : `${hours} h ${remMin} min`;
}
function count(value: unknown): string {
const n = Number(value);
// Render only for positive counts; zero is treated as "no metric
// reported" so a partially-populated agent_finish (pre-v0.1.24 events,
// or a failed run whose result is the zero Result) does not appear as
// "0 prompt · 0 completion · 0 cached".
if (!Number.isFinite(n) || n <= 0) return "";
return n.toLocaleString("en-US");
}
function text(value: unknown): string {
return typeof value === "string" ? value : "";
}
export interface TimelineLine {
title: string;
detail: string;
}
export function describeTimelineEvent(ev: TaskEvent = {}): TimelineLine {
const data = ev.data || {};
const stage = ev.stage || "unknown stage";
const workflow = ev.workflow ? `${ev.workflow} workflow` : "";
if (ev.kind === "stage_start") {
return { title: `Started stage: ${stage}`, detail: workflow };
}
if (ev.kind === "stage_finish") {
const elapsed = duration(data.duration_ms);
const context = [workflow, elapsed && `ran for ${elapsed}`].filter(Boolean).join(" · ");
return {
title: data.interrupted
? `Stage interrupted: ${stage}`
: data.error
? `Stage failed: ${stage}`
: `Finished stage: ${stage}`,
detail: [context, text(data.error)].filter(Boolean).join(" — "),
};
}
if (ev.kind === "task_retried") {
const retryCount = Number(data.retry_count);
const attempt = Number.isFinite(retryCount) && retryCount > 0 ? `Retry ${retryCount}` : "Retry requested";
const previous = [text(data.previous_stage) && `after ${text(data.previous_stage)}`, text(data.previous_reason)]
.filter(Boolean)
.join(": ");
return { title: attempt, detail: previous || ev.detail || "" };
}
if (ev.kind === "agent_finish") {
const iterations = count(data.iterations);
const total = count(data.tokens);
const cachedRaw = Number(data.cached_tokens) || 0;
// data.prompt_tokens INCLUDES cache hits -- showing it next to "cached"
// reads as two separate charges when it's really one figure containing
// the other. Show the fresh (full-price) remainder instead, so a
// heavily-cached run doesn't look ~10x more expensive than it was billed.
const fresh = count((Number(data.prompt_tokens) || 0) - cachedRaw);
const completion = count(data.completion_tokens);
const cached = count(data.cached_tokens);
const usage = [
iterations && `${iterations} iterations`,
total && `${total} tokens`,
fresh && `${fresh} fresh prompt`,
completion && `${completion} completion`,
cached && `${cached} cached`,
text(data.model),
].filter(Boolean);
return {
title: `Agent ${text(data.status) || "finished"}: ${stage}`,
detail: usage.join(" · ") || ev.detail || "",
};
}
// Condition (d): the two provenance kinds render as one human line. The
// captured payload is rendered by its own panel, never dumped into the
// timeline, so these cases name what was recorded and nothing more.
if (ev.kind === "config_captured") {
return {
title: "Configuration captured",
detail: "The effective task-runtime configuration for this run.",
};
}
if (ev.kind === "changes_captured") {
const totals = (data.totals ?? {}) as { files?: unknown };
const fileCount = Number(totals.files);
const files =
Number.isFinite(fileCount) && fileCount > 0 ? `${fileCount} file${fileCount === 1 ? "" : "s"} changed` : "";
const after = data.captured_after ? `captured after ${text(data.captured_after)}` : "";
return { title: "Change capture recorded", detail: [files, after].filter(Boolean).join(" · ") };
}
return { title: words(ev.kind || ev.type), detail: ev.detail || "" };
}
+352
View File
@@ -0,0 +1,352 @@
/**
* One task's run: the reads, the caches and the view state the run page and its
* panels share.
*
* The page provides it and the panels inject it, rather than the page threading
* a dozen props through a host component: the attempt a panel reads and the
* attempt the selector shows come from the same place, so they cannot disagree.
*
* Every keyed fetch goes through keyedLoad: the key is what the response
* belongs to, so a late response for an attempt the operator has already left
* lands under its own key and is never shown against another attempt.
*/
import { computed, inject, onMounted, provide, reactive, ref, watch, type ComputedRef, type InjectionKey, type Ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { api, classifyActionError, type ActionErrorKind } from "@/lib/api";
import { actionFor } from "@/lib/task-meta";
import {
attemptKey,
EMPTY_LOG_FILTERS,
initialAttempt,
initialTab,
logCacheKey,
runQuery,
type AttemptsState,
type ChangesState,
type DebugState,
type LogFilters,
type LogState,
type TaskEvent,
type TaskRecord,
} from "./task-run";
/** A keyed read has three states: pending, failed, or the response. */
type Cache<T> = Map<string, T | null | undefined>;
export interface RetryError {
kind: ActionErrorKind;
message: string;
}
export interface TaskRun {
tab: string;
attempts: AttemptsState | null | undefined;
taskList: TaskRecord[] | null | undefined;
events: TaskEvent[] | null | undefined;
missing: boolean;
filters: LogFilters;
retryBusy: boolean;
retryError: RetryError | null;
task: TaskRecord | null;
attemptNumber: number | null;
currentAttempt: number | null;
stageNames: string[];
retryKind: string;
canRetry: boolean;
logState: LogState | null | undefined;
changesState: ChangesState | null | undefined;
debugState: DebugState | null | undefined;
/** A tab id, as the Tabs root reports it (its model value is string|number). */
setTab(id: string | number): void;
selectAttempt(attempt: number): void;
setFilters(next: LogFilters): void;
refreshAll(): void;
performRetry(): Promise<void>;
loadAttempts(): void;
loadEvents(): void;
loadTaskList(): void;
loadLogs(attempt: number, opts?: { force?: boolean }): void;
loadChanges(attempt: number, opts?: { force?: boolean }): void;
loadDebug(attempt: number, opts?: { force?: boolean }): void;
}
const TASK_RUN: InjectionKey<TaskRun> = Symbol("task-run");
/**
* Creates the run state for one task and provides it to the page's subtree.
* `id` is the parsed task id, or null when the route's id is not a task id --
* in which case nothing is ever fetched.
*/
export function provideTaskRun(id: ComputedRef<number | null>): TaskRun {
const route = useRoute();
const router = useRouter();
const tab = ref(initialTab(route.query));
const requestedAttempt = ref<number | null>(initialAttempt(route.query));
const taskList = ref<TaskRecord[] | null | undefined>(undefined);
const attempts = ref<AttemptsState | null | undefined>(undefined);
const missing = ref(false);
const events = ref<TaskEvent[] | null | undefined>(undefined);
const filters = ref<LogFilters>({ ...EMPTY_LOG_FILTERS });
const logs = ref<Cache<LogState>>(new Map());
const changes = ref<Cache<ChangesState>>(new Map());
const debug = ref<Cache<DebugState>>(new Map());
const retryBusy = ref(false);
const retryError = ref<RetryError | null>(null);
const refreshToken = ref(0);
const started = new Set<string>();
const task = computed<TaskRecord | null>(() =>
Array.isArray(taskList.value)
? taskList.value.find((t) => String(t.id) === String(id.value)) || null
: null,
);
const currentAttempt = computed<number | null>(() =>
Number(attempts.value?.current_attempt) > 0 ? Number(attempts.value?.current_attempt) : null,
);
// The wire spells "the task's current attempt" as 0, which is not an attempt
// number: a task with no run at all must not address attempt 0.
const attemptNumber = computed<number | null>(() => requestedAttempt.value ?? currentAttempt.value);
const selectedAttempt = computed(() =>
(attempts.value?.attempts || []).find((a) => Number(a.attempt) === Number(attemptNumber.value)),
);
const stageNames = computed(() => [
...new Set((selectedAttempt.value?.stages || []).map((stage) => stage.name).filter(Boolean) as string[]),
]);
const retryMeta = computed(() => actionFor("retry"));
const canRetry = computed(() => Boolean(retryMeta.value && (task.value?.actions || []).includes("retry")));
const logKey = computed(() =>
id.value == null || attemptNumber.value == null ? null : logCacheKey(id.value, attemptNumber.value, filters.value),
);
const changeKey = computed(() => (id.value == null ? null : attemptKey(id.value, attemptNumber.value)));
const debugKey = changeKey;
const logState = computed<LogState | null | undefined>(() =>
logKey.value == null ? undefined : logs.value.get(logKey.value),
);
const changesState = computed<ChangesState | null | undefined>(() =>
changeKey.value == null ? undefined : changes.value.get(changeKey.value),
);
const debugState = computed<DebugState | null | undefined>(() =>
debugKey.value == null ? undefined : debug.value.get(debugKey.value),
);
function keyedLoad<T>(
cacheKey: string,
fetcher: () => Promise<T>,
cache: Ref<Cache<T>>,
{ force = false }: { force?: boolean } = {},
): void {
if (started.has(cacheKey) && !force) return;
started.add(cacheKey);
cache.value = new Map(cache.value).set(cacheKey, undefined);
fetcher()
.then((res) => {
cache.value = new Map(cache.value).set(cacheKey, res);
})
.catch(() => {
cache.value = new Map(cache.value).set(cacheKey, null);
});
}
function loadTaskList(): void {
if (id.value == null) return;
taskList.value = undefined;
api
.tasks<TaskRecord[]>()
.then((res) => {
taskList.value = res;
})
.catch(() => {
taskList.value = null;
});
}
function loadAttempts(): void {
if (id.value == null) return;
attempts.value = undefined;
missing.value = false;
api
.taskAttempts<AttemptsState>(String(id.value))
.then((res) => {
attempts.value = res;
})
.catch((err) => {
if ((err as { status?: number })?.status === 404) missing.value = true;
attempts.value = null;
});
}
function loadEvents(): void {
if (id.value == null) return;
events.value = undefined;
api
.task<TaskEvent[]>(String(id.value))
.then((res) => {
events.value = res || [];
})
.catch(() => {
events.value = null;
});
}
function loadLogs(attempt: number, opts?: { force?: boolean }): void {
if (id.value == null) return;
const current = filters.value;
keyedLoad(
logCacheKey(id.value, attempt, current),
() =>
api.taskLogs<LogState>(String(id.value), {
attempt: attempt || undefined,
level: current.level,
stage: current.stage,
limit: 500,
}),
logs,
opts,
);
}
function loadChanges(attempt: number, opts?: { force?: boolean }): void {
if (id.value == null) return;
keyedLoad(
attemptKey(id.value, attempt),
() => api.taskChanges<ChangesState>(String(id.value), { attempt }),
changes,
opts,
);
}
function loadDebug(attempt: number, opts?: { force?: boolean }): void {
if (id.value == null) return;
keyedLoad(
attemptKey(id.value, attempt),
() => api.taskDebug<DebugState>(String(id.value), { attempt }),
debug,
opts,
);
}
/** Drop every cache so a manual refresh cannot show a stale capture or log
* beside fresh attempt history. */
function dropCaches(): void {
started.clear();
logs.value = new Map();
changes.value = new Map();
debug.value = new Map();
}
function refreshAll(): void {
dropCaches();
loadTaskList();
loadAttempts();
loadEvents();
refreshToken.value += 1;
}
async function performRetry(): Promise<void> {
if (id.value == null) return;
retryError.value = null;
retryBusy.value = true;
try {
await api.taskAction<void>(String(id.value), "retry");
// A new attempt starts here. Everything cached belongs to the attempt
// that just ended, so it is dropped rather than shown against the new
// run: the attempt history, the events, every cached log, capture and
// debug payload. The new attempt then becomes the selected run without a
// reload.
dropCaches();
requestedAttempt.value = null;
loadTaskList();
loadAttempts();
loadEvents();
refreshToken.value += 1;
} catch (err) {
retryError.value = classifyActionError(err);
} finally {
retryBusy.value = false;
}
}
onMounted(() => {
// The page loads once for the task it was opened for; the route remounts it
// when that changes (App.vue keys the outlet on the path).
if (id.value == null) return;
loadTaskList();
loadAttempts();
loadEvents();
});
watch([tab, attemptNumber, filters, refreshToken], () => {
const attempt = attemptNumber.value;
if (attempt == null) return;
// Only the visible tab's lazy payload is fetched: the debug envelope
// repeats the whole event list, so fetching it on every page load would
// duplicate a large body for nothing.
if (tab.value === "log") loadLogs(attempt);
else if (tab.value === "changes") loadChanges(attempt);
else if (tab.value === "debug") loadDebug(attempt);
});
watch([tab, attemptNumber], () => {
if (id.value == null) return;
// The open tab and the pinned attempt are written back with router.replace
// rather than a hash assignment or a push: replace adds no history entry,
// so a tab click does not remount and refetch the page, while the address
// bar still holds the full state for a copy, a bookmark or a reload.
void router.replace({ query: runQuery(tab.value, attemptNumber.value) });
});
const run = reactive({
tab,
attempts,
taskList,
events,
missing,
filters,
retryBusy,
retryError,
task,
attemptNumber,
currentAttempt,
stageNames,
retryKind: computed(() => retryMeta.value?.kind || ""),
canRetry,
logState,
changesState,
debugState,
setTab(next: string | number) {
tab.value = String(next);
},
selectAttempt(attempt: number) {
requestedAttempt.value = attempt;
},
setFilters(next: LogFilters) {
filters.value = { ...next };
},
refreshAll,
performRetry,
loadAttempts,
loadEvents,
loadTaskList,
loadLogs,
loadChanges,
loadDebug,
});
provide(TASK_RUN, run as TaskRun);
return run as TaskRun;
}
/** The run state provided by the nearest TaskDetailPage. */
export function useTaskRun(): TaskRun {
const run = inject(TASK_RUN);
if (!run) throw new Error("useTaskRun() must be called under a TaskDetailPage");
return run;
}