Files
archie/ui/src/logs/state.ts
T
sam 3bf64933b0 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

190 lines
6.5 KiB
TypeScript

import { computed, onMounted, onUnmounted, reactive, ref, watch } from "vue";
import { api } from "@/lib/api";
import { useSessionStore } from "@/stores/session";
import type { LogEntry } from "@/lib/log";
import type { StatusKind } from "@/lib/status";
import type { StreamState } from "@/lib/stream-state";
import {
entryKey,
matchesFilters,
mergeEntries,
type LogFilters,
} from "./log-entries";
import { logsEmptyDetail, logsEmptyTitle } from "./logs-empty";
/**
* The log page's shared state.
*
* The filters, the stream's state and the list itself are read by different
* components, so it lives in a module rather than being threaded down through a
* chain of props.
*/
/** One page of the durable log, as GET /api/logs answers it. */
interface LogHistory {
entries?: LogEntry[];
components?: string[];
services?:string[];
errors?:Record<string,string>;
file?: string;
truncated?: boolean;
/** The process serving the request keeps no durable history. */
disabled?: boolean;
}
export const filters = reactive<LogFilters>({
level: "",
service:"",
component: "",
q: "",
});
/** The components the filter can name: those the server found, plus any the
* live stream has shown since. */
export const serviceOptions=ref<string[]>([]);
export const serviceErrors=ref<Record<string,string>>({});
export const componentOptions = ref<string[]>([]);
export const paused = ref(false);
export const loading = ref(true);
export const readError = ref<string | null>(null);
export const streamState = ref<StreamState | "connecting">("connecting");
const historyEntries = ref<LogEntry[]>([]);
const durableUnavailable = ref(false);
const truncated = ref(false);
const logFile = ref("");
// Live entries are held in a plain Map so a line the stream repeats is stored
// once, and the tick is what makes that mutation visible to `entries` below --
// a Map is not something a computed can depend on by being read.
const liveEntries = new Map<string, LogEntry>();
const liveTick = ref(0);
export const entries = computed(() => {
void liveTick.value;
return mergeEntries(historyEntries.value, liveEntries, filters);
});
/** What the list is showing. Every string here is a statement about this
* process: a failed read, a read in flight, a deployment with no durable
* history, or the file the lines came from. */
export const meta = computed(() => {
if (readError.value) return "Cannot read logs";
if (loading.value) return "Refreshing…";
if (durableUnavailable.value) return "Live only";
if (truncated.value)
return "Showing recent matches; older lines are omitted";
return logFile.value || "Recent service logs; refreshed every 5 seconds";
});
/** The stream's state as a badge kind. Never `ok` for a stream that is still
* connecting, and never `warn` for one that has given up: the two are
* different answers, and stream-state.ts is what tells them apart. */
export const streamKind = computed<StatusKind>(() => {
if (streamState.value === "live") return "ok";
return streamState.value === "unavailable" ? "danger" : "warn";
});
/** Which of the nothing-to-show situations the list is in. */
export const emptyTitle = computed(() =>
logsEmptyTitle(durableUnavailable.value, streamState.value),
);
export const emptyDetail = computed(() =>
logsEmptyDetail(durableUnavailable.value, streamState.value),
);
let generation=0;
export async function loadLogs(): Promise<void> {
const current=++generation;
loading.value = true;
readError.value = null;
try {
const res = await api.logs<LogHistory>({
service:filters.service,
level: filters.level,
component: filters.component,
q: filters.q,
limit: 500,
});
if(current!==generation)return;
serviceOptions.value=[...new Set([...serviceOptions.value,...(res.services??[])])].sort();
serviceErrors.value=res.errors??{};
componentOptions.value = res.components ?? [];
durableUnavailable.value = !!res.disabled;
truncated.value = !!res.truncated;
logFile.value = res.file ?? "";
historyEntries.value = res.entries ?? [];
} catch (err) {
if(current!==generation)return;
// The server's own message is the only part of a failure an operator can
// act on, so it is what the list says instead of the lines.
readError.value = (err as Error).message || String(err);
} finally {
if(current===generation)loading.value = false;
}
}
function handleEntry(raw: unknown): void {
// Paused drops what arrives rather than buffering it: the list is a view of
// the stream, and resuming continues from where the stream is now instead of
// replaying the pause.
if (paused.value) return;
const entry = raw as LogEntry;
if (!matchesFilters(entry, filters)) return;
liveEntries.set(entryKey(entry), entry);
const component = entry.fields?.component;
if (
typeof component === "string" &&
component &&
!componentOptions.value.includes(component)
) {
componentOptions.value = [...componentOptions.value, component];
}
liveTick.value += 1;
}
let refresh:ReturnType<typeof setInterval>|undefined;
let unsubscribe: (() => void) | undefined;
/** Owns the initial read, the re-reads a filter change causes, and the live
* stream, for the page's lifetime. */
export function useLogs(): void {
const live = useSessionStore();
onMounted(() => {
// A mount opens a new stream against a fresh read, so the tail starts
// unpaused, connecting, and without the lines the previous visit's stream
// left behind. The filters are not reset: they are what the operator last
// asked to see, and the read below answers them again.
paused.value = false;
streamState.value = "connecting";
liveEntries.clear();
liveTick.value += 1;
void loadLogs();
refresh=setInterval(()=>{if(!paused.value)void loadLogs()},5000);
unsubscribe = live.subscribe("logs", handleEntry);
streamState.value = live.streamState;
});
onUnmounted(() => {
clearInterval(refresh);
generation++;
unsubscribe?.();
unsubscribe = undefined;
});
watch(() => live.streamState, (state) => {
streamState.value = state;
});
// A process without a LogFeed cannot deliver live entries.
const stopStatus = live.subscribe("logs-status", (data) => {
if (!(data as { available: boolean }).available) streamState.value = "unavailable";
});
onUnmounted(stopStatus);
// Every filter is a server-side one -- the request carries it -- so a change
// to any of them is a new read, not a re-filter of what is already here.
watch(filters, () => void loadLogs());
}