Files
archie/ui/src/tasks/use-task-run.ts
T
sam 493eb43944 fix(ui/topbar): replace Jump to with a command palette, drop filler chrome (#1650)
* fix(ui/topbar): replace Jump to with a command palette, drop filler chrome

Jump to opens a shadcn-vue Command dialog that finds pages, tasks and
workflows by name. The connection indicator shows only when the stream is
lost, the dead documentation link is gone, and the profile menu label has
no stray whitespace.

* fix(ui): trim stray whitespace from template text and drop em dashes from copy

Element text that started or ended with a line break rendered with leading
and trailing spaces. Also removes the unused 'soon' nav state and the nav
group components no route reaches.

* fix(ui): drop the space a hidden spinner left before button text

* fix(ui/status): one dense Status page, full-width settings, problems-only apply status

Status drops its tabs and the duplicate health card; services list only
what is wrong. Settings pages use the full width, the resizable sidebar
handle is gone, and apply status shows only processes that have not
applied a change. PageHeader puts the title and actions on one line.

* refactor(ui): use shadcn ToggleGroup and Badge, drop SegmentedControl and StatusPill

Status badges show only when a state needs attention: no Running, Enabled,
Active, Listening or live pills next to healthy rows. Removes the unused
pagination, radio-group and scroll-area components.

* fix(ui/history): use the shadcn Table with fixed columns so nothing is clipped

* fix(ui/workflows): apply ?workflow= only once the workflow is listed

Selecting it before the definitions loaded opened an empty canvas.

* refactor(ui/workflows): use shadcn Input, NativeSelect, Checkbox and Button in editors

Replaces hand-rolled inputs, selects, the repository mode switch and icon
buttons in the workflow editor, bind dialog, harness page, sources panel
and review gate. Adds the upstream shadcn-vue NativeSelect.

* style(ui): rounded-rectangle controls instead of pills

Halves the radius scale so inputs, selects and buttons stop reading as
pills, and badges and chips lose their full rounding.

* fix(ui/alerts): centre the bell's failed state and stop it contradicting Needs you

* fix(ui/tasks): one header line, aligned columns, no placeholder issue numbers

Tasks puts its filters beside the title and drops the stat tiles the
dashboard already shows. Sort headers align with their cells, chat tasks
no longer show their synthetic issue number, and Logs and the task
not-found page use the shared header.

* fix(ui/dashboard): shared header and cards, empty cards stay silent

Needs you uses the shadcn Card and drops its duplicate Open button; quality
gates and token outlook render only when there is something to show; the
throughput strip moves into the dashboard, its only user.

* refactor(ui/stores): one Pinia store per feature

Splits the site-wide control-plane store and the module-level refs into
settings, workflows, tasks, events, org and session stores. Identity
requests move into lib/api. Drops store fields nothing read: per-resource
stream state, the states map and loadApplyStatus.

* fix(ui/org): one header for the org area, sections drop their repeated titles

The org name is the page title with the admin's org switcher and New org
beside it; Members and Workspaces tables sit in cards like other pages.

* fix(ui/events): shadcn Tabs for the capture, map and bind steps

Replaces the numbered step strip with line tabs that carry each step's
count; the Listening pill is gone and Capture off shows only when it is.

* fix(ui/workflows): confirm a workflow delete in an AlertDialog, not window.confirm

* style(ui/settings): denser setting rows
2026-10-12 04:40:21 +11:00

398 lines
12 KiB
TypeScript

/**
* 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 { useLiveResource } from "@/stores/session";
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 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 (cache.value.has(cacheKey) && cache.value.get(cacheKey) !== null && !force) return;
cache.value = new Map(cache.value).set(cacheKey, undefined);
// A read that never settles would pin the panel's loading line forever:
// after a quiet minute the read is declared broken so the retry button
// can appear. A late response after the timeout is discarded by the race.
const timeout = new Promise<never>((_, reject) => {
setTimeout(() => {
reject(new Error("read timed out"));
}, 30_000);
});
Promise.race([fetcher(), timeout])
.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;
// Keep the current gate mounted so a refresh preserves its selection.
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 {
logs.value = new Map();
changes.value = new Map();
debug.value = new Map();
}
function refreshAll(): void {
dropCaches();
loadTaskList();
loadAttempts();
loadEvents();
refreshToken.value += 1;
}
useLiveResource("tasks", refreshAll, 500);
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();
});
// A stage filter is a command scoped to the attempt it was made on: the rail
// set it against that attempt's stage list. A different attempt presents a
// different list, so the stage filter resets on an attempt switch and the
// rail can never highlight a stage the operator did not select here. The
// level filter is attempt-agnostic and survives.
watch(attemptNumber, () => {
if (filters.value.stage) filters.value = { ...filters.value, stage: "" };
});
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);
}, { immediate: true });
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;
}