Files
archie/ui/src/stores/session.ts
T
sam 4876a5d50b
Quality / check (push) Successful in 10m26s
deploy / gate (push) Successful in 5m43s
deploy / archied-image (push) Successful in 2m43s
deploy / agent-image (push) Successful in 11s
deploy / dist-zip (push) Skipped
feat(webui): org-scoped schedules for non-system orgs (#1639 #1051 #49)
2026-10-31 14:25:24 +11:00

164 lines
5.5 KiB
TypeScript

import { defineStore } from "pinia";
import {
computed,
onUnmounted,
reactive,
ref,
watch,
} from "vue";
import { api, setAuthenticationStateHandler, subscribeEvents, type StreamFrame } from "../lib/api.ts";
import type { CapabilitySections } from "../lib/capabilities.ts";
import { reconnectDelay, type StreamState } from "../lib/stream-state.ts";
import {
resourcesForEvent,
type LiveEvent,
type LiveResource,
} from "./live-events.ts";
/** The browser's session with the server: the live event stream, and which
* sections this composition can back. */
export const useSessionStore = defineStore("session", () => {
/**
* The server's capability map. Null means nothing has been reported (an
* older server, a failed read), and every surface stays visible: a page that
* says "unavailable" is recoverable, one that silently vanished is not.
*/
const sections = ref<CapabilitySections | null>(null);
/** Asked once, after the shell is up: the nav paints immediately and loses
* what this process cannot back a moment later. A failed read hides nothing.
* Later callers await the same read, so a store deciding whether to issue an
* instance-only call never races the answer. */
let pendingCapabilities: Promise<void> | null = null;
function loadCapabilities(): Promise<void> {
if (sections.value) return Promise.resolve();
pendingCapabilities ??= api
.capabilities<{ sections?: CapabilitySections } | null>()
.then((response) => {
sections.value = response?.sections ?? null;
})
.catch(() => {
// Offline or an older server: every section stays visible.
})
.finally(() => {
pendingCapabilities = null;
});
return pendingCapabilities;
}
/** True while the caller acts in the system org, or the server has not said
* otherwise. Instance-only surfaces (apply status, the instance's identity
* list) are read only for it: another org's reads of them answer 404, so
* pages skip them and show an unavailable state instead. */
const systemOrg = computed(() => sections.value?.settings !== false);
const streamState = ref<StreamState | "connecting">("connecting");
const connectionRevision = ref(0);
const activity = ref<LiveEvent[]>([]);
const revisions = reactive<Record<LiveResource, number>>({
tasks: 0,
captures: 0,
curators: 0,
skills: 0,
updates: 0,
chat: 0,
});
let unsubscribe: (() => void) | undefined;
let cursor = "";
let logsReaders = 0;
const listeners = new Map<string, Set<(data: unknown) => void>>();
function receive(raw: unknown): void {
const event = raw as LiveEvent;
activity.value = [event, ...activity.value].slice(0, 50);
for (const resource of resourcesForEvent(event)) revisions[resource] += 1;
}
function handleFrame(frame: StreamFrame, lastEventId: string): void {
if (lastEventId) cursor = lastEventId;
if (frame.topic === "tasks") receive(frame.data);
for (const listener of listeners.get(frame.topic) ?? []) listener(frame.data);
}
// The browser retries a dropped stream itself, but a non-200 answer (the
// backend restarting behind a proxy) closes it for good; reopen it then, or
// the page reads "Disconnected" until a reload.
let retryTimer: ReturnType<typeof setTimeout> | undefined;
let retryAttempt = 0;
function connect(): void {
clearTimeout(retryTimer);
unsubscribe?.();
streamState.value = "connecting";
unsubscribe = subscribeEvents(handleFrame, (state) => {
streamState.value = state;
if (state === "live") {
retryAttempt = 0;
connectionRevision.value += 1;
} else if (state === "unavailable") {
retryTimer = setTimeout(connect, reconnectDelay(retryAttempt++));
}
}, cursor, logsReaders > 0);
}
function initialize(): void {
if (unsubscribe) return;
// An expired session reloads the document: the server answers a page
// request without a session by sending the browser to sign in.
setAuthenticationStateHandler((required) => {
if (required) window.location.reload();
});
connect();
}
/** Subscriptions are local callbacks, not browser connections. Only Logs
* changes the upstream topic set and intentionally reconnects the stream. */
function subscribe(topic: string, listener: (data: unknown) => void): () => void {
const callbacks = listeners.get(topic) ?? new Set<(data: unknown) => void>();
callbacks.add(listener);
listeners.set(topic, callbacks);
if (topic === "logs" && ++logsReaders === 1) connect();
return () => {
callbacks.delete(listener);
if (callbacks.size === 0) listeners.delete(topic);
if (topic === "logs" && --logsReaders === 0) connect();
};
}
return {
sections,
systemOrg,
loadCapabilities,
activity,
connectionRevision,
revisions,
streamState,
initialize,
receive,
subscribe,
};
});
/** Re-read one mounted projection when SSE says its backend resource changed. */
export function useLiveResource(
resource: LiveResource | null,
load: () => void,
debounceMs = 100,
): void {
const live = useSessionStore();
let timer: ReturnType<typeof setTimeout> | undefined;
const revision = () =>
resource === null
? live.connectionRevision
: [live.revisions[resource], live.connectionRevision];
const stop = watch(revision, () => {
clearTimeout(timer);
timer = setTimeout(load, debounceMs);
});
onUnmounted(() => {
clearTimeout(timer);
stop();
});
}