chore(ui): delete the binary's separate SPA in ui/src/archie
The Vue dashboard now serves the binary, so archie.html, ui/src/archie and its client test go. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
55 files changed
-7538
No files matched your search
@@ -1,44 +0,0 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Archie</title>
|
||||
<script>
|
||||
// Set before the first paint so a reload does not flash the wrong
|
||||
// palette or layout. Kept in sync with the appearance Pinia store;
|
||||
// blocked site data falls back to the OS theme, comfortable spacing and
|
||||
// the system motion preference.
|
||||
(function () {
|
||||
var theme = "dark";
|
||||
try {
|
||||
theme = matchMedia("(prefers-color-scheme: dark)").matches
|
||||
? "dark"
|
||||
: "light";
|
||||
} catch (e) {
|
||||
/* dark stands */
|
||||
}
|
||||
try {
|
||||
var storedTheme = localStorage.getItem("archie.theme");
|
||||
if (storedTheme === "light" || storedTheme === "dark") {
|
||||
theme = storedTheme;
|
||||
}
|
||||
if (localStorage.getItem("archie.density") === "compact") {
|
||||
document.documentElement.dataset.density = "compact";
|
||||
}
|
||||
if (localStorage.getItem("archie.motion") === "reduced") {
|
||||
document.documentElement.dataset.motion = "reduced";
|
||||
}
|
||||
} catch (e) {
|
||||
/* default stands */
|
||||
}
|
||||
document.documentElement.dataset.theme = theme;
|
||||
})();
|
||||
</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/archie/main.ts"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,146 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
|
||||
import { MetadataList } from "@/components/ui/metadata-list";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import type { ActionTrail, ApprovalRequest, Effect, Verdict } from "./api";
|
||||
|
||||
const props = defineProps<{ action: ActionTrail }>();
|
||||
|
||||
type Tone = "ok" | "warn" | "danger" | "info" | "secondary";
|
||||
|
||||
const decision = computed(() => props.action.decision);
|
||||
const target = computed(() => `${decision.value.action.target.Kind}:${decision.value.action.target.ID}`);
|
||||
|
||||
const approvalTone: Record<ApprovalRequest["state"], Tone> = {
|
||||
pending: "warn",
|
||||
approved: "ok",
|
||||
denied: "danger",
|
||||
expired: "secondary",
|
||||
};
|
||||
const effectTone: Record<Effect["state"], Tone> = { ran: "ok", failed: "danger", unknown: "warn" };
|
||||
const effectLabel: Record<Effect["state"], string> = { ran: "Ran", failed: "Failed", unknown: "Outcome unknown" };
|
||||
|
||||
const approvalRows = computed(() => {
|
||||
const a = props.action.approval;
|
||||
if (!a?.answered_by) return [];
|
||||
return [
|
||||
{ label: "Answered by", value: a.answered_by },
|
||||
{ label: "Via", value: a.answered_via ?? "" },
|
||||
];
|
||||
});
|
||||
|
||||
const json = (v: unknown) => JSON.stringify(v, null, 2);
|
||||
const body = (v: unknown) => (typeof v === "string" ? v : json(v));
|
||||
const ceilingTone = (v: Verdict): Tone => (v.failed ? "warn" : "secondary");
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col gap-3 rounded-md border p-3 text-label">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<span class="font-medium">{{ decision.action.connector }} {{ decision.action.name }}</span>
|
||||
<span class="text-caption text-muted-foreground">{{ target }}</span>
|
||||
<Badge :variant="decision.reason ? 'danger' : 'secondary'">{{ decision.level }}</Badge>
|
||||
<Badge v-if="decision.refused_by" variant="danger">{{ decision.refused_by }}</Badge>
|
||||
<Badge v-if="decision.change_request" variant="warn">Change request: {{ decision.change_request_rule }}</Badge>
|
||||
<Timestamp :at="decision.at" class="ml-auto text-caption" />
|
||||
</div>
|
||||
<p v-if="decision.action.effect.Summary" class="text-muted-foreground">{{ decision.action.effect.Summary }}</p>
|
||||
<CodeBlock size="sm">
|
||||
<CodeBlockContent wrap class="max-h-40">{{ json(decision.action.input) }}</CodeBlockContent>
|
||||
</CodeBlock>
|
||||
|
||||
<details v-if="decision.calls?.length" class="text-caption">
|
||||
<summary class="cursor-pointer text-muted-foreground">Connector calls</summary>
|
||||
<div class="mt-1 flex flex-col gap-2">
|
||||
<div v-for="(c, i) in decision.calls" :key="i" class="flex flex-col gap-1 border-l pl-2">
|
||||
<span class="font-medium">{{ c.connector }} {{ c.method }}</span>
|
||||
<span class="text-muted-foreground">Request</span>
|
||||
<CodeBlock size="sm">
|
||||
<CodeBlockContent wrap class="max-h-40">{{ json(c.request) }}</CodeBlockContent>
|
||||
</CodeBlock>
|
||||
<template v-if="c.response">
|
||||
<span class="text-muted-foreground">Response</span>
|
||||
<CodeBlock size="sm">
|
||||
<CodeBlockContent wrap class="max-h-40">{{ json(c.response) }}</CodeBlockContent>
|
||||
</CodeBlock>
|
||||
</template>
|
||||
<span v-if="c.error" class="text-destructive">{{ c.error }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<ul class="flex flex-col gap-1.5">
|
||||
<li v-for="v in decision.verdicts" :key="v.guard" class="flex flex-col gap-0.5">
|
||||
<span class="flex items-center gap-2">
|
||||
<span>{{ v.guard }}</span>
|
||||
<Badge :variant="ceilingTone(v)">{{ v.ceiling }}</Badge>
|
||||
<Badge v-if="v.advisory" variant="outline">advisory</Badge>
|
||||
</span>
|
||||
<span v-if="v.failed" class="text-caption text-destructive">{{ v.failed }}</span>
|
||||
<span v-for="f in v.findings" :key="f.text" class="text-caption text-muted-foreground">
|
||||
{{ f.text }}<template v-if="f.evidence">: {{ f.evidence }}</template>
|
||||
</span>
|
||||
<span v-for="b in v.blind_spots" :key="b" class="text-caption text-muted-foreground">Blind spot: {{ b }}</span>
|
||||
<div v-for="(j, i) in v.judges" :key="i" class="flex flex-col gap-0.5 border-l pl-2">
|
||||
<span class="flex flex-wrap items-center gap-2 text-caption">
|
||||
<span class="font-medium">{{ j.model || 'Judge' }}</span>
|
||||
<Badge v-if="j.answer" variant="secondary">{{ j.answer }}</Badge>
|
||||
<span v-if="j.confidence" class="text-muted-foreground">Confidence {{ j.confidence.toFixed(2) }}</span>
|
||||
<Badge :variant="j.trusted ? 'secondary' : 'outline'">{{ j.trusted ? 'trusted' : 'advisory' }}</Badge>
|
||||
</span>
|
||||
<span v-if="j.reason" class="text-caption text-muted-foreground">{{ j.reason }}</span>
|
||||
<span v-if="!j.trusted && j.advisory_reason" class="text-caption text-muted-foreground">{{ j.advisory_reason }}</span>
|
||||
<span v-if="j.eval_date" class="text-caption text-muted-foreground">Eval {{ j.eval_date }}</span>
|
||||
<span v-if="j.basis_digest" class="text-caption text-muted-foreground">Basis {{ j.basis_digest.slice(0, 12) }}</span>
|
||||
<span v-if="j.result_id" class="text-caption text-muted-foreground">Result {{ j.result_id }}</span>
|
||||
<details v-if="j.basis || j.answers || j.request || j.response" class="text-caption text-muted-foreground">
|
||||
<summary>Judge record</summary>
|
||||
<span v-if="j.endpoint_path" class="block">
|
||||
{{ j.endpoint_path }}<template v-if="j.http_status"> · HTTP {{ j.http_status }}</template><template v-if="j.latency_ms !== undefined"> · {{ j.latency_ms }} ms</template>
|
||||
</span>
|
||||
<span v-if="j.basis" class="block">Basis</span>
|
||||
<pre v-if="j.basis" class="whitespace-pre-wrap">{{ j.basis }}</pre>
|
||||
<span v-if="j.request" class="block">Request body</span>
|
||||
<pre v-if="j.request" class="whitespace-pre-wrap">{{ body(j.request) }}</pre>
|
||||
<span v-if="j.response" class="block">Response body</span>
|
||||
<pre v-if="j.response" class="whitespace-pre-wrap">{{ body(j.response) }}</pre>
|
||||
<span v-if="j.answers" class="block">Answers</span>
|
||||
<pre v-if="j.answers" class="whitespace-pre-wrap">{{ json(j.answers) }}</pre>
|
||||
</details>
|
||||
</div>
|
||||
</li>
|
||||
</ul>
|
||||
<p v-if="decision.reason" class="text-destructive">{{ decision.reason }}</p>
|
||||
|
||||
<div v-if="action.approval" class="flex flex-col gap-2 border-t pt-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="font-medium">Approval</span>
|
||||
<Badge :variant="approvalTone[action.approval.state]">{{ action.approval.state }}</Badge>
|
||||
<Timestamp :at="action.approval.answered_at ?? action.approval.requested_at" class="ml-auto text-caption" />
|
||||
</div>
|
||||
<MetadataList v-if="approvalRows.length" :rows="approvalRows" />
|
||||
<p class="whitespace-pre-wrap text-muted-foreground">{{ action.approval.summary }}</p>
|
||||
</div>
|
||||
|
||||
<div v-if="action.rejudged" class="flex items-center gap-2 text-caption text-muted-foreground">
|
||||
<span>Judged again</span>
|
||||
<Badge variant="secondary">{{ action.rejudged.level }}</Badge>
|
||||
<span v-if="action.rejudged.reason">{{ action.rejudged.reason }}</span>
|
||||
</div>
|
||||
|
||||
<div v-if="action.effect" class="flex flex-col gap-2 border-t pt-3">
|
||||
<div class="flex items-center gap-2">
|
||||
<span class="font-medium">Effect</span>
|
||||
<Badge :variant="effectTone[action.effect.state]">{{ effectLabel[action.effect.state] }}</Badge>
|
||||
<Timestamp :at="action.effect.at" class="ml-auto text-caption" />
|
||||
</div>
|
||||
<p v-if="action.effect.error" class="text-destructive">{{ action.effect.error }}</p>
|
||||
<CodeBlock v-if="action.effect.output" size="sm">
|
||||
<CodeBlockContent wrap class="max-h-64">{{ action.effect.output }}</CodeBlockContent>
|
||||
</CodeBlock>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,163 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref } from "vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { SettingRow } from "@/components/ui/setting-row";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import {
|
||||
listAgentModels,
|
||||
listCredentials,
|
||||
saveAgentModel,
|
||||
testAgentModel,
|
||||
Unauthorized,
|
||||
type AgentModel,
|
||||
type CredentialView,
|
||||
} from "./api";
|
||||
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
|
||||
const none = "none";
|
||||
const blankModel = (): AgentModel => ({ class: "openai", base_url: "", model: "", api_key_credential: "" });
|
||||
const models = reactive(new Map<string, AgentModel>([["default", blankModel()]]));
|
||||
const alias = ref("default");
|
||||
const newAlias = ref("");
|
||||
const model = computed(() => models.get(alias.value)!);
|
||||
const credentials = ref<CredentialView[]>([]);
|
||||
const loading = ref(true);
|
||||
const loadError = ref("");
|
||||
const error = ref("");
|
||||
const answer = ref("");
|
||||
const saved = ref("");
|
||||
const testing = ref(false);
|
||||
const saving = ref(false);
|
||||
const controller = new AbortController();
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
loadError.value = "";
|
||||
try {
|
||||
const [current, creds] = await Promise.all([
|
||||
listAgentModels(controller.signal),
|
||||
listCredentials(controller.signal),
|
||||
]);
|
||||
credentials.value = creds;
|
||||
for (const [name, configured] of Object.entries(current)) models.set(name, configured);
|
||||
} catch (err) {
|
||||
fail(err, loadError);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function selectAlias(name: string) {
|
||||
alias.value = name;
|
||||
error.value = answer.value = saved.value = "";
|
||||
}
|
||||
|
||||
function addAlias() {
|
||||
const name = newAlias.value.trim();
|
||||
if (!name) return;
|
||||
if (!models.has(name)) models.set(name, blankModel());
|
||||
selectAlias(name);
|
||||
newAlias.value = "";
|
||||
}
|
||||
|
||||
async function test() {
|
||||
testing.value = true;
|
||||
error.value = "";
|
||||
answer.value = "";
|
||||
saved.value = "";
|
||||
try {
|
||||
const result = await testAgentModel(payload());
|
||||
answer.value = result.answer;
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
testing.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
saving.value = true;
|
||||
error.value = "";
|
||||
saved.value = "";
|
||||
try {
|
||||
models.set(alias.value, await saveAgentModel(alias.value, payload()));
|
||||
saved.value = "Saved.";
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function payload(): AgentModel {
|
||||
return {
|
||||
class: model.value.class.trim(),
|
||||
base_url: model.value.base_url.trim(),
|
||||
model: model.value.model.trim(),
|
||||
api_key_credential: model.value.api_key_credential === none ? "" : model.value.api_key_credential,
|
||||
};
|
||||
}
|
||||
|
||||
function fail(err: unknown, target = error) {
|
||||
if (controller.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
target.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Section title="Agent models">
|
||||
<Spinner v-if="loading" />
|
||||
<ReadError v-else-if="loadError" :message="loadError" retry-label="Retry" @retry="load" />
|
||||
<template v-else>
|
||||
<SettingRow label="Model alias" for="model-alias">
|
||||
<Select :model-value="alias" :disabled="saving || testing" @update:model-value="(name) => selectAlias(String(name))">
|
||||
<SelectTrigger id="model-alias" class="w-full sm:w-64"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="name in [...models.keys()].sort()" :key="name" :value="name">{{ name }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
<SettingRow label="New alias" for="new-model-alias">
|
||||
<div class="flex flex-wrap gap-2">
|
||||
<Input id="new-model-alias" v-model="newAlias" placeholder="fast" class="w-48" />
|
||||
<Button size="sm" variant="outline" :disabled="saving || testing || !newAlias.trim()" @click="addAlias">Add alias</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
<SettingRow label="Provider class" for="agent-class" hint="The provider family, such as openai, anthropic or ollama.">
|
||||
<Input id="agent-class" v-model="model.class" placeholder="openai" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Base URL" for="agent-base-url" hint="Leave blank to use the provider's default URL, if available.">
|
||||
<Input id="agent-base-url" v-model="model.base_url" placeholder="https://…" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Model" for="agent-model">
|
||||
<Input id="agent-model" v-model="model.model" />
|
||||
</SettingRow>
|
||||
<SettingRow label="API key" for="agent-credential">
|
||||
<Select :model-value="model.api_key_credential || none" @update:model-value="(v) => (model.api_key_credential = String(v))">
|
||||
<SelectTrigger id="agent-credential" class="w-full sm:w-64"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem :value="none">No key</SelectItem>
|
||||
<SelectItem v-for="c in credentials.filter((x) => x.kind === 'bearer')" :key="c.name" :value="c.name">{{ c.name }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
<div class="mt-2 flex flex-wrap items-center gap-2">
|
||||
<Button size="sm" :disabled="saving || !model.class.trim() || !model.model.trim()" @click="save">Save</Button>
|
||||
<Button variant="outline" size="sm" :disabled="testing || !model.class.trim() || !model.model.trim()" @click="test">Test</Button>
|
||||
<span v-if="saved" class="text-caption text-muted-foreground">{{ saved }}</span>
|
||||
</div>
|
||||
<p v-if="answer" class="mt-2 text-label">Test response: <span class="font-mono">{{ answer }}</span></p>
|
||||
<p v-if="error" class="mt-2 text-caption text-danger">{{ error }}</p>
|
||||
</template>
|
||||
</Section>
|
||||
</template>
|
||||
@@ -1,93 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch } from "vue";
|
||||
import { RouterLink, RouterView, useRoute } from "vue-router";
|
||||
import { Toaster } from "vue-sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { TooltipProvider } from "@/components/ui/tooltip";
|
||||
import { clearToken, invalidTokenMessage, isValidToken, setToken, token } from "./api";
|
||||
import ChatDock from "./chat/ChatDock.vue";
|
||||
import ChatTopbarButton from "./chat/ChatTopbarButton.vue";
|
||||
import { unauthorized } from "./chat/state";
|
||||
|
||||
/**
|
||||
* The shell: the admin token gate, then the pages, with the chat docked to
|
||||
* every page but the composer, which is the chat itself. The token is the
|
||||
* bootstrap credential until identities exist.
|
||||
*/
|
||||
const route = useRoute();
|
||||
const savedToken = token();
|
||||
const invalidSavedToken = savedToken !== "" && !isValidToken(savedToken);
|
||||
if (invalidSavedToken) clearToken();
|
||||
const signedIn = ref(savedToken !== "" && !invalidSavedToken);
|
||||
const draft = ref("");
|
||||
const signInError = ref(invalidSavedToken ? invalidTokenMessage : "");
|
||||
|
||||
function signIn() {
|
||||
const value = draft.value.trim();
|
||||
if (!value) return;
|
||||
if (!setToken(value)) {
|
||||
signInError.value = invalidTokenMessage;
|
||||
return;
|
||||
}
|
||||
signInError.value = "";
|
||||
draft.value = "";
|
||||
signedIn.value = true;
|
||||
}
|
||||
|
||||
function signOut() {
|
||||
clearToken();
|
||||
signedIn.value = false;
|
||||
}
|
||||
|
||||
watch(unauthorized, (refused) => {
|
||||
if (!refused) return;
|
||||
unauthorized.value = false;
|
||||
signOut();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<TooltipProvider :delay-duration="350">
|
||||
<div class="mx-auto flex min-h-dvh max-w-4xl flex-col gap-4 p-4 [padding-left:max(1rem,var(--chat-pin-l,0px))] [padding-right:max(1rem,var(--chat-pin-r,0px))]">
|
||||
<header class="flex items-center gap-4">
|
||||
<span class="text-title font-semibold">Archie</span>
|
||||
<nav v-if="signedIn" class="flex flex-1 flex-wrap items-center gap-x-3 gap-y-1 text-label">
|
||||
<RouterLink to="/composer" active-class="text-foreground" class="text-muted-foreground">Composer</RouterLink>
|
||||
<RouterLink to="/runs" active-class="text-foreground" class="text-muted-foreground">Runs</RouterLink>
|
||||
<RouterLink to="/unmatched" active-class="text-foreground" class="text-muted-foreground">Unmatched</RouterLink>
|
||||
<RouterLink to="/events" active-class="text-foreground" class="text-muted-foreground">Events</RouterLink>
|
||||
<RouterLink to="/classes" active-class="text-foreground" class="text-muted-foreground">Classes</RouterLink>
|
||||
<RouterLink to="/people" active-class="text-foreground" class="text-muted-foreground">People</RouterLink>
|
||||
<RouterLink to="/controls" active-class="text-foreground" class="text-muted-foreground">Controls</RouterLink>
|
||||
<RouterLink to="/extensions" active-class="text-foreground" class="text-muted-foreground">Extensions</RouterLink>
|
||||
<RouterLink to="/sources" active-class="text-foreground" class="text-muted-foreground">Sources</RouterLink>
|
||||
<RouterLink to="/triggers" active-class="text-foreground" class="text-muted-foreground">Triggers</RouterLink>
|
||||
<RouterLink to="/credentials" active-class="text-foreground" class="text-muted-foreground">Credentials</RouterLink>
|
||||
<RouterLink to="/settings" active-class="text-foreground" class="text-muted-foreground">Settings</RouterLink>
|
||||
<span class="ml-auto flex items-center gap-1">
|
||||
<ChatTopbarButton v-if="route.name !== 'composer'" />
|
||||
<Button variant="ghost" size="xs" @click="signOut">Sign out</Button>
|
||||
</span>
|
||||
</nav>
|
||||
</header>
|
||||
<form v-if="!signedIn" class="max-w-md" @submit.prevent="signIn">
|
||||
<Section title="Admin token">
|
||||
<div class="flex gap-2">
|
||||
<Input v-model="draft" type="password" autocomplete="off" aria-label="Admin token" />
|
||||
<Button type="submit">Sign in</Button>
|
||||
</div>
|
||||
<p v-if="signInError" role="alert" class="mt-2 text-label text-destructive">{{ signInError }}</p>
|
||||
</Section>
|
||||
</form>
|
||||
<RouterView v-else v-slot="{ Component }">
|
||||
<component :is="Component" @unauthorized="signOut" />
|
||||
</RouterView>
|
||||
<div aria-hidden="true" class="h-[var(--chat-dock-clear,0px)] flex-none" />
|
||||
</div>
|
||||
<ChatDock v-if="signedIn && route.name !== 'composer'" />
|
||||
<Toaster position="bottom-right" rich-colors close-button />
|
||||
</TooltipProvider>
|
||||
</template>
|
||||
@@ -1,207 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { MetadataList } from "@/components/ui/metadata-list";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import { type ClassDetail, classDetail, resetClass, Unauthorized } from "./api";
|
||||
import { className, levelLabel } from "./state";
|
||||
|
||||
const autonomyRows = computed(() => {
|
||||
const d = detail.value;
|
||||
if (!d) return [];
|
||||
const rows: { label: string; value?: string; at?: string }[] = [
|
||||
{ label: "Approvals in a row", value: String(d.count) },
|
||||
d.tightened_at
|
||||
? { label: "Last tightened", value: d.tightened_because, at: d.tightened_at }
|
||||
: { label: "Last tightened", value: "Never" },
|
||||
];
|
||||
const raise = d.raises.find((r) => r.state === "pending");
|
||||
if (raise) {
|
||||
rows.push({ label: "Raise waiting", value: `${levelLabel(raise.from)} to ${levelLabel(raise.to)}, answer by`, at: raise.deadline });
|
||||
}
|
||||
return rows;
|
||||
});
|
||||
|
||||
/** One action class: its level, and every decision made in it. */
|
||||
const props = defineProps<{ id: string }>();
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
const router = useRouter();
|
||||
|
||||
const detail = ref<ClassDetail>();
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
const confirming = ref(false);
|
||||
const resetting = ref(false);
|
||||
let controller = new AbortController();
|
||||
|
||||
async function load() {
|
||||
controller.abort();
|
||||
controller = new AbortController();
|
||||
const signal = controller.signal;
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
const got = await classDetail(props.id, signal);
|
||||
if (!signal.aborted) detail.value = got;
|
||||
} catch (err) {
|
||||
fail(err, signal);
|
||||
} finally {
|
||||
if (!signal.aborted) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function reset() {
|
||||
resetting.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
await resetClass(props.id);
|
||||
await load();
|
||||
} catch (err) {
|
||||
fail(err, controller.signal);
|
||||
} finally {
|
||||
resetting.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function fail(err: unknown, signal: AbortSignal) {
|
||||
if (signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
watch(() => props.id, load, { immediate: true });
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<Spinner v-if="loading && !detail" />
|
||||
<ReadError v-else-if="error && !detail" :message="error" retry-label="Retry" @retry="load" />
|
||||
<template v-else-if="detail">
|
||||
<PageHeader :title="className(detail)">
|
||||
<Badge variant="outline">{{ levelLabel(detail.level) }}</Badge>
|
||||
<Button variant="outline" size="sm" :disabled="resetting || detail.level === detail.default" @click="confirming = true">
|
||||
Reset to {{ levelLabel(detail.default).toLowerCase() }}
|
||||
</Button>
|
||||
</PageHeader>
|
||||
<ReadError v-if="error" :message="error" retry-label="Retry" @retry="load" />
|
||||
<Section title="Autonomy">
|
||||
<MetadataList :rows="autonomyRows">
|
||||
<template #value="{ row }">
|
||||
<template v-if="row.at">
|
||||
<Timestamp :at="row.at" /><template v-if="row.value">, {{ row.value }}</template>
|
||||
</template>
|
||||
<template v-else>{{ row.value }}</template>
|
||||
</template>
|
||||
</MetadataList>
|
||||
</Section>
|
||||
<Section v-if="detail.raises.length > 0" title="Raises" class="mt-4">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>From</TableHead>
|
||||
<TableHead>To</TableHead>
|
||||
<TableHead>State</TableHead>
|
||||
<TableHead>Answered by</TableHead>
|
||||
<TableHead>Approvals</TableHead>
|
||||
<TableHead>Proposed</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="r in detail.raises" :key="r.id">
|
||||
<TableCell>{{ levelLabel(r.from) }}</TableCell>
|
||||
<TableCell>{{ levelLabel(r.to) }}</TableCell>
|
||||
<TableCell>{{ r.state }}</TableCell>
|
||||
<TableCell>{{ r.answered_by }}</TableCell>
|
||||
<TableCell>{{ r.evidence.map((e) => e.by).join(", ") }}</TableCell>
|
||||
<TableCell><Timestamp :at="r.proposed_at" /></TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Section>
|
||||
<Section title="History" class="mt-4">
|
||||
<Empty v-if="detail.history.length === 0">
|
||||
<EmptyHeader><EmptyTitle>No decisions yet</EmptyTitle></EmptyHeader>
|
||||
</Empty>
|
||||
<Table v-else>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Target</TableHead>
|
||||
<TableHead>Level</TableHead>
|
||||
<TableHead>Approval</TableHead>
|
||||
<TableHead>When</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow
|
||||
v-for="h in detail.history"
|
||||
:key="h.decision_id"
|
||||
class="cursor-pointer"
|
||||
tabindex="0"
|
||||
@click="router.push({ name: 'run', params: { id: h.run_id } })"
|
||||
@keydown.enter="router.push({ name: 'run', params: { id: h.run_id } })"
|
||||
>
|
||||
<TableCell>{{ h.target }}</TableCell>
|
||||
<TableCell>{{ h.refused_by ? `Refused by ${h.refused_by}` : levelLabel(h.level) }}</TableCell>
|
||||
<TableCell>{{ h.approval }}<template v-if="h.answered_by"> by {{ h.answered_by }}</template></TableCell>
|
||||
<TableCell><Timestamp :at="h.at" /></TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Section>
|
||||
<Section v-if="detail.resets.length > 0" title="Resets" class="mt-4">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>From</TableHead>
|
||||
<TableHead>To</TableHead>
|
||||
<TableHead>By</TableHead>
|
||||
<TableHead>When</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="r in detail.resets" :key="r.at">
|
||||
<TableCell>{{ levelLabel(r.from) }}</TableCell>
|
||||
<TableCell>{{ levelLabel(r.to) }}</TableCell>
|
||||
<TableCell>{{ r.by }}</TableCell>
|
||||
<TableCell><Timestamp :at="r.at" /></TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</Section>
|
||||
<AlertDialog :open="confirming" @update:open="(v: boolean) => (confirming = v)">
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Reset class?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{{ className(detail) }} returns to {{ levelLabel(detail.default).toLowerCase() }}. Its history stays.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction @click="reset">Reset</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,76 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import { type ActionClass, listClasses, Unauthorized } from "./api";
|
||||
import { levelLabel } from "./state";
|
||||
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
const router = useRouter();
|
||||
|
||||
const classes = ref<ActionClass[]>([]);
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
const controller = new AbortController();
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
classes.value = await listClasses(controller.signal);
|
||||
} catch (err) {
|
||||
if (controller.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
const open = (id: string) => router.push({ name: "class", params: { id } });
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader title="Classes" />
|
||||
<Spinner v-if="loading" />
|
||||
<ReadError v-else-if="error" :message="error" retry-label="Retry" @retry="load" />
|
||||
<Empty v-else-if="classes.length === 0">
|
||||
<EmptyHeader><EmptyTitle>No action classes yet</EmptyTitle></EmptyHeader>
|
||||
</Empty>
|
||||
<Table v-else>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Action</TableHead>
|
||||
<TableHead>Target</TableHead>
|
||||
<TableHead>Environment</TableHead>
|
||||
<TableHead>Level</TableHead>
|
||||
<TableHead>Decisions</TableHead>
|
||||
<TableHead>Approvals in a row</TableHead>
|
||||
<TableHead>Last</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="c in classes" :key="c.id" class="cursor-pointer" tabindex="0" @click="open(c.id)" @keydown.enter="open(c.id)">
|
||||
<TableCell>{{ c.connector }} {{ c.action }}</TableCell>
|
||||
<TableCell>{{ c.target_kind }}</TableCell>
|
||||
<TableCell>{{ c.environment }}</TableCell>
|
||||
<TableCell><Badge variant="outline">{{ levelLabel(c.level) }}</Badge></TableCell>
|
||||
<TableCell>{{ c.decisions }}</TableCell>
|
||||
<TableCell>{{ c.count }}</TableCell>
|
||||
<TableCell><Timestamp v-if="c.last_decided_at" :at="c.last_decided_at" /></TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,25 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import ChatBar from "./chat/ChatBar.vue";
|
||||
import ChatComposer from "./chat/ChatComposer.vue";
|
||||
import ChatPending from "./chat/ChatPending.vue";
|
||||
import ChatTranscript from "./chat/ChatTranscript.vue";
|
||||
import { useChat } from "./chat/state";
|
||||
|
||||
/**
|
||||
* The composer: the chat with Archie at full size, the same conversation the
|
||||
* dock shows on every other page.
|
||||
*/
|
||||
useChat();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section
|
||||
aria-label="Chat with Archie"
|
||||
class="flex h-[calc(100dvh-6rem)] min-h-96 min-w-0 flex-col rounded-lg border border-border-strong bg-popover"
|
||||
>
|
||||
<ChatBar />
|
||||
<ChatTranscript />
|
||||
<ChatPending />
|
||||
<ChatComposer :open="true" />
|
||||
</section>
|
||||
</template>
|
||||
@@ -1,137 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, reactive, ref } from "vue";
|
||||
import { RouterLink } from "vue-router";
|
||||
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import { getPolicies, listJudges, savePolicies, Unauthorized, type JudgeControl, type PolicyKind, type PolicySet } from "./api";
|
||||
|
||||
/** Controls: Cedar hard rules and change-request rules, and the judge each guard asks. */
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
|
||||
interface Editor {
|
||||
kind: PolicyKind;
|
||||
title: string;
|
||||
current?: PolicySet;
|
||||
body: string;
|
||||
saving: boolean;
|
||||
error: string;
|
||||
}
|
||||
|
||||
const editors = reactive<Editor[]>([
|
||||
{ kind: "hard-rules", title: "Hard rules", body: "", saving: false, error: "" },
|
||||
{ kind: "change-request", title: "Change-request rules", body: "", saving: false, error: "" },
|
||||
]);
|
||||
const judges = ref<JudgeControl[]>([]);
|
||||
const loading = ref(true);
|
||||
const loadError = ref("");
|
||||
const controller = new AbortController();
|
||||
|
||||
const judgeLabels: Record<string, string> = {
|
||||
judge_api: "Judge API",
|
||||
judge_model: "Model",
|
||||
judge_base_url: "Endpoint",
|
||||
judge_api_key_ref: "API key credential",
|
||||
policy: "Policy",
|
||||
};
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
loadError.value = "";
|
||||
try {
|
||||
const sets = await Promise.all(editors.map((e) => getPolicies(e.kind, controller.signal)));
|
||||
editors.forEach((e, i) => {
|
||||
e.current = sets[i];
|
||||
e.body = sets[i].body;
|
||||
});
|
||||
judges.value = await listJudges(controller.signal);
|
||||
} catch (err) {
|
||||
fail(err, (m) => (loadError.value = m));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function save(e: Editor) {
|
||||
e.saving = true;
|
||||
e.error = "";
|
||||
try {
|
||||
e.current = await savePolicies(e.kind, e.body);
|
||||
e.body = e.current.body;
|
||||
} catch (err) {
|
||||
fail(err, (m) => (e.error = m));
|
||||
} finally {
|
||||
e.saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
function fail(err: unknown, show: (message: string) => void) {
|
||||
if (controller.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
show(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader title="Controls" />
|
||||
<Spinner v-if="loading" />
|
||||
<ReadError v-else-if="loadError" :message="loadError" retry-label="Retry" @retry="load" />
|
||||
<template v-else>
|
||||
<Section v-for="e in editors" :key="e.kind" :title="e.title">
|
||||
<Textarea v-model="e.body" :aria-label="e.title" rows="12" class="font-mono" spellcheck="false" />
|
||||
<p v-if="e.error" class="mt-2 text-caption text-danger">{{ e.error }}</p>
|
||||
<div class="mt-2 flex items-center gap-3">
|
||||
<Button :disabled="e.saving || e.body === e.current?.body" @click="save(e)">Save</Button>
|
||||
<span v-if="e.current" class="text-caption text-muted-foreground">
|
||||
Version {{ e.current.version }}, <Timestamp :at="e.current.created_at" /> by {{ e.current.created_by }}
|
||||
</span>
|
||||
</div>
|
||||
</Section>
|
||||
|
||||
<Section title="Judges">
|
||||
<Empty v-if="!judges.length">
|
||||
<EmptyHeader><EmptyTitle>No guard is running</EmptyTitle></EmptyHeader>
|
||||
</Empty>
|
||||
<div v-else class="flex flex-col gap-4">
|
||||
<div v-for="judge in judges" :key="judge.name" class="rounded-md border border-border p-3">
|
||||
<div class="mb-2 flex flex-wrap items-center gap-2">
|
||||
<span class="font-medium">{{ judge.name }}</span>
|
||||
<Badge :variant="judge.advisory ? 'warn' : 'ok'">{{ judge.advisory ? "Advisory" : "Sets a ceiling" }}</Badge>
|
||||
<span v-if="judge.version" class="text-caption text-fg-subtle">Version {{ judge.version }}</span>
|
||||
<RouterLink :to="{ name: 'extensions' }" class="ms-auto text-caption text-link underline-offset-4 hover:underline">Edit settings</RouterLink>
|
||||
</div>
|
||||
<dl class="grid grid-cols-[minmax(6.5rem,max-content)_minmax(0,1fr)] gap-x-3 gap-y-2 text-caption">
|
||||
<template v-for="s in judge.settings_schema" :key="s.key">
|
||||
<dt class="leading-5 text-fg-subtle">{{ judgeLabels[s.key] ?? s.label }}</dt>
|
||||
<dd class="min-w-0 leading-5 [overflow-wrap:anywhere] font-mono">{{ judge.settings[s.key] || "Not set" }}</dd>
|
||||
</template>
|
||||
<dt class="leading-5 text-fg-subtle">Standing</dt>
|
||||
<dd class="min-w-0 leading-5">
|
||||
<span v-if="judge.latest">
|
||||
<Badge :variant="judge.latest.trusted ? 'ok' : 'warn'">{{ judge.latest.trusted ? "Trusted" : "Advisory" }}</Badge>
|
||||
<span class="ms-2 text-fg-subtle">{{ judge.latest.advisory_reason }}</span>
|
||||
</span>
|
||||
<span v-else class="text-fg-subtle">No judgement recorded yet</span>
|
||||
</dd>
|
||||
<dt class="leading-5 text-fg-subtle">Eval date</dt>
|
||||
<dd class="min-w-0 leading-5 font-mono">{{ judge.latest?.eval_date || "—" }}</dd>
|
||||
<dt class="leading-5 text-fg-subtle">Last judged</dt>
|
||||
<dd class="min-w-0 leading-5"><Timestamp v-if="judge.latest" :at="judge.latest.at" /><span v-else class="text-fg-subtle">—</span></dd>
|
||||
</dl>
|
||||
</div>
|
||||
</div>
|
||||
</Section>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,211 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, reactive, ref } from "vue";
|
||||
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { SettingRow } from "@/components/ui/setting-row";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { listCredentials, saveCredential, Unauthorized, type CredentialField, type CredentialView } from "./api";
|
||||
|
||||
/**
|
||||
* The API returns field sources, not saved secret values. Enter those values
|
||||
* again when replacing a credential.
|
||||
*/
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
|
||||
type Kind = CredentialView["kind"];
|
||||
|
||||
const fieldsOf: Record<Kind, { required: string[]; optional: string[] }> = {
|
||||
machine: { required: ["username", "private_key"], optional: ["private_key_passphrase"] },
|
||||
age: { required: ["identity"], optional: [] },
|
||||
basic: { required: ["username", "password"], optional: [] },
|
||||
bearer: { required: ["token"], optional: [] },
|
||||
};
|
||||
|
||||
const labelOf: Record<string, string> = {
|
||||
username: "Username",
|
||||
private_key: "Private key",
|
||||
private_key_passphrase: "Private key passphrase",
|
||||
identity: "Age identity",
|
||||
password: "Password",
|
||||
token: "Token",
|
||||
};
|
||||
|
||||
interface Field {
|
||||
value: string;
|
||||
engine: string;
|
||||
key: string;
|
||||
}
|
||||
|
||||
interface Form {
|
||||
name: string;
|
||||
kind: Kind;
|
||||
fields: Record<string, Field>;
|
||||
}
|
||||
|
||||
const blank = (kind: Kind = "bearer"): Form => ({
|
||||
name: "",
|
||||
kind,
|
||||
fields: Object.fromEntries([...fieldsOf[kind].required, ...fieldsOf[kind].optional].map((f) => [f, { value: "", engine: "", key: "" }])),
|
||||
});
|
||||
|
||||
const credentials = ref<CredentialView[]>([]);
|
||||
const form = reactive<Form>(blank());
|
||||
const editing = ref(false);
|
||||
const original = ref("");
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
const saved = ref("");
|
||||
const saving = ref(false);
|
||||
const controller = new AbortController();
|
||||
|
||||
const columns: DataTableColumn<CredentialView>[] = [
|
||||
{ id: "name", label: "Name", fixed: true },
|
||||
{ id: "kind", label: "Kind" },
|
||||
{ id: "fields", label: "Fields" },
|
||||
];
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
credentials.value = await listCredentials(controller.signal);
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function chooseKind(kind: Kind) {
|
||||
form.kind = kind;
|
||||
form.fields = blank(kind).fields;
|
||||
}
|
||||
|
||||
function start(name?: string) {
|
||||
error.value = "";
|
||||
saved.value = "";
|
||||
const found = name ? credentials.value.find((c) => c.name === name) : undefined;
|
||||
original.value = name ?? "";
|
||||
Object.assign(form, found ? fromView(found) : blank());
|
||||
editing.value = true;
|
||||
}
|
||||
|
||||
function fromView(c: CredentialView): Form {
|
||||
const out = blank(c.kind);
|
||||
out.name = c.name;
|
||||
for (const [name, origin] of Object.entries(c.fields)) {
|
||||
out.fields[name] ??= { value: "", engine: "", key: "" };
|
||||
if (origin.includes(":")) {
|
||||
const [engine, key] = origin.split(":");
|
||||
out.fields[name].engine = engine;
|
||||
out.fields[name].key = key;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function save() {
|
||||
saving.value = true;
|
||||
error.value = "";
|
||||
saved.value = "";
|
||||
try {
|
||||
const fields: Record<string, CredentialField> = {};
|
||||
for (const name of [...fieldsOf[form.kind].required, ...fieldsOf[form.kind].optional]) {
|
||||
const f = form.fields[name];
|
||||
if (!f) continue;
|
||||
if (f.value) fields[name] = { value: f.value };
|
||||
else if (f.engine && f.key) fields[name] = { engine: f.engine, key: f.key };
|
||||
}
|
||||
await saveCredential(form.name.trim(), form.kind, fields);
|
||||
saved.value = "Saved.";
|
||||
editing.value = false;
|
||||
Object.assign(form, blank());
|
||||
await load();
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function fail(err: unknown) {
|
||||
if (controller.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader title="Credentials">
|
||||
<Button variant="outline" @click="start()">Add credential</Button>
|
||||
</PageHeader>
|
||||
<Spinner v-if="loading" />
|
||||
<ReadError v-else-if="error && !credentials.length && !editing" :message="error" retry-label="Retry" @retry="load" />
|
||||
<template v-else>
|
||||
<Section v-if="editing" :title="form.name ? `Edit ${form.name}` : 'New credential'">
|
||||
<form class="flex flex-col gap-3" @submit.prevent="save">
|
||||
<SettingRow label="Name" for="credential-name">
|
||||
<Input id="credential-name" v-model="form.name" :disabled="original !== ''" placeholder="lowercase-name" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Kind" for="credential-kind">
|
||||
<Select :model-value="form.kind" @update:model-value="(v) => chooseKind(v as Kind)">
|
||||
<SelectTrigger id="credential-kind" class="w-full sm:w-64"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="bearer">Bearer token</SelectItem>
|
||||
<SelectItem value="basic">Username and password</SelectItem>
|
||||
<SelectItem value="machine">SSH machine</SelectItem>
|
||||
<SelectItem value="age">Age identity</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
<SettingRow
|
||||
v-for="(field, name) in form.fields"
|
||||
:key="name"
|
||||
:label="labelOf[name] ?? name"
|
||||
:hint="fieldsOf[form.kind].optional.includes(name) ? 'Optional.' : 'Required.'"
|
||||
>
|
||||
<div class="flex flex-col gap-2">
|
||||
<Input v-model="field.value" type="password" autocomplete="off" :aria-label="labelOf[name] ?? name" placeholder="New value" />
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<Input v-model="field.engine" placeholder="Secret engine" class="w-40" :aria-label="`${name} engine`" />
|
||||
<Input v-model="field.key" placeholder="Key" class="w-40" :aria-label="`${name} key`" />
|
||||
</div>
|
||||
</div>
|
||||
</SettingRow>
|
||||
<p class="text-caption text-fg-subtle">A value is write only. Enter it, or name the engine and key that resolve it.</p>
|
||||
<p v-if="error" class="text-caption text-danger">{{ error }}</p>
|
||||
<div class="flex items-center gap-2">
|
||||
<Button type="submit" :disabled="saving || !form.name.trim()">Save</Button>
|
||||
<Button type="button" variant="ghost" @click="editing = false">Cancel</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Section>
|
||||
|
||||
<Empty v-if="!credentials.length">
|
||||
<EmptyHeader><EmptyTitle>No credentials yet</EmptyTitle></EmptyHeader>
|
||||
</Empty>
|
||||
<DataTable v-else :columns="columns" :rows="credentials" :row-key="(c) => c.name" storage-key="credentials">
|
||||
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span></template>
|
||||
<template #cell-kind="{ row }">{{ row.kind }}</template>
|
||||
<template #cell-fields="{ row }">
|
||||
<span class="font-mono text-caption">{{ Object.entries(row.fields).map(([f, origin]) => `${f}: ${origin}`).join(", ") }}</span>
|
||||
</template>
|
||||
<template #actions="{ row }">
|
||||
<Button variant="ghost" size="sm" @click="start(row.name)">Edit</Button>
|
||||
</template>
|
||||
</DataTable>
|
||||
<p v-if="saved" class="mt-2 text-caption text-muted-foreground">{{ saved }}</p>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,158 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { RouterLink } from "vue-router";
|
||||
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { SettingRow } from "@/components/ui/setting-row";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import { getEvent, listEvents, listSources, Unauthorized, type EventDetail, type EventRow } from "./api";
|
||||
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
|
||||
const rows = ref<EventRow[]>([]);
|
||||
const sources = ref<string[]>([]);
|
||||
const selected = ref<EventDetail | null>(null);
|
||||
const loading = ref(true);
|
||||
const loadingDetail = ref(false);
|
||||
const error = ref("");
|
||||
const detailError = ref("");
|
||||
const source = ref("all");
|
||||
const type = ref("");
|
||||
const matched = ref("all");
|
||||
const controller = new AbortController();
|
||||
|
||||
const columns: DataTableColumn<EventRow>[] = [
|
||||
{ id: "received", label: "Received", fixed: true },
|
||||
{ id: "source", label: "Source" },
|
||||
{ id: "type", label: "Type" },
|
||||
{ id: "matched", label: "Matched" },
|
||||
];
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
const [events, heard] = await Promise.all([
|
||||
listEvents(
|
||||
{
|
||||
source: source.value === "all" ? undefined : source.value,
|
||||
type: type.value.trim() || undefined,
|
||||
matched: matched.value === "all" ? undefined : matched.value === "true",
|
||||
limit: 100,
|
||||
},
|
||||
controller.signal,
|
||||
),
|
||||
sources.value.length ? Promise.resolve(sources.value) : listSources(controller.signal).then((s) => s.map((x) => x.name)),
|
||||
]);
|
||||
rows.value = events;
|
||||
sources.value = heard;
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function open(row: EventRow) {
|
||||
selected.value = null;
|
||||
detailError.value = "";
|
||||
loadingDetail.value = true;
|
||||
try {
|
||||
selected.value = await getEvent(row.id, controller.signal);
|
||||
} catch (err) {
|
||||
fail(err, (message) => (detailError.value = message));
|
||||
} finally {
|
||||
loadingDetail.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function fail(err: unknown, show: (message: string) => void = (m) => (error.value = m)) {
|
||||
if (controller.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
show(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader title="Events" />
|
||||
<Section title="Filters">
|
||||
<SettingRow label="Source" for="event-source">
|
||||
<Select v-model="source" @update:model-value="load">
|
||||
<SelectTrigger id="event-source" class="w-full sm:w-64"><SelectValue placeholder="All sources" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">All sources</SelectItem>
|
||||
<SelectItem v-for="s in sources" :key="s" :value="s">{{ s }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
<SettingRow label="Type" for="event-type">
|
||||
<Input id="event-type" v-model="type" placeholder="All event types" @change="load" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Trigger" for="event-matched">
|
||||
<Select v-model="matched" @update:model-value="load">
|
||||
<SelectTrigger id="event-matched" class="w-full sm:w-64"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="all">Matched and unmatched</SelectItem>
|
||||
<SelectItem value="true">Matched a trigger</SelectItem>
|
||||
<SelectItem value="false">Unmatched</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
</Section>
|
||||
<Spinner v-if="loading" />
|
||||
<ReadError v-else-if="error && !rows.length" :message="error" retry-label="Retry" @retry="load" />
|
||||
<Empty v-else-if="!rows.length">
|
||||
<EmptyHeader><EmptyTitle>No events match these filters</EmptyTitle></EmptyHeader>
|
||||
</Empty>
|
||||
<DataTable v-else :columns="columns" :rows="rows" :row-key="(row) => row.id" storage-key="events">
|
||||
<template #cell-received="{ row }"><Timestamp :at="row.received_at" /></template>
|
||||
<template #cell-source="{ row }">{{ row.source }}</template>
|
||||
<template #cell-type="{ row }"><span class="font-mono text-caption">{{ row.type }}</span></template>
|
||||
<template #cell-matched="{ row }">
|
||||
<Badge :variant="row.matched ? 'ok' : 'idle'">{{ row.matched ? "Matched" : "Unmatched" }}</Badge>
|
||||
</template>
|
||||
<template #actions="{ row }">
|
||||
<Button variant="ghost" size="sm" @click.stop="open(row)">Open</Button>
|
||||
</template>
|
||||
</DataTable>
|
||||
|
||||
<Section v-if="loadingDetail" title="Event"><Spinner /></Section>
|
||||
<Section v-else-if="selected" :title="selected.type" class="mt-4">
|
||||
<template #action>
|
||||
<Button variant="ghost" size="xs" @click="selected = null">Close</Button>
|
||||
</template>
|
||||
<SettingRow label="Received"><Timestamp :at="selected.received_at" /></SettingRow>
|
||||
<SettingRow label="Source"><span class="text-label">{{ selected.source }}</span></SettingRow>
|
||||
<SettingRow label="Occurred" v-if="selected.occurred_at"><Timestamp :at="selected.occurred_at" /></SettingRow>
|
||||
<SettingRow label="Payload">
|
||||
<Textarea :model-value="JSON.stringify(selected.body, null, 2)" readonly rows="12" class="font-mono" spellcheck="false" aria-label="Event payload" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Runs">
|
||||
<div v-if="selected.runs.length" class="flex flex-col gap-1">
|
||||
<RouterLink
|
||||
v-for="run in selected.runs"
|
||||
:key="run.run_id"
|
||||
:to="{ name: 'run', params: { id: run.run_id } }"
|
||||
class="text-label text-link underline-offset-4 hover:underline"
|
||||
>{{ run.trigger }} → {{ run.run_id }}</RouterLink>
|
||||
</div>
|
||||
<span v-else class="text-label text-fg-subtle">No trigger started a run</span>
|
||||
</SettingRow>
|
||||
<p v-if="detailError" class="text-caption text-danger">{{ detailError }}</p>
|
||||
</Section>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,413 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, reactive, ref } from "vue";
|
||||
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DataTable, type DataTableColumn } from "@/components/ui/data-table";
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { MoreMenu } from "@/components/ui/more-menu";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { SettingRow } from "@/components/ui/setting-row";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
acceptExtension,
|
||||
listCredentials,
|
||||
listExtensions,
|
||||
removeExtension,
|
||||
Unauthorized,
|
||||
type CredentialView,
|
||||
type Extension,
|
||||
type ExtensionContract,
|
||||
} from "./api";
|
||||
|
||||
/**
|
||||
* The UI configures credential slots by name without reading secret values.
|
||||
*/
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
|
||||
const contracts: { id: ExtensionContract; title: string; add: string }[] = [
|
||||
{ id: "connector", title: "Connectors", add: "Accept connector" },
|
||||
{ id: "guard", title: "Guards", add: "Accept guard" },
|
||||
{ id: "secretengine", title: "Secret engines", add: "Accept secret engine" },
|
||||
{ id: "mcp", title: "MCP servers", add: "Accept MCP server" },
|
||||
];
|
||||
|
||||
const rows = reactive<Record<ExtensionContract, Extension[]>>({
|
||||
connector: [],
|
||||
guard: [],
|
||||
secretengine: [],
|
||||
mcp: [],
|
||||
});
|
||||
const credentials = ref<CredentialView[]>([]);
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
const errorAt = ref("");
|
||||
const saved = ref("");
|
||||
const controller = new AbortController();
|
||||
|
||||
interface Slot {
|
||||
slot: string;
|
||||
credential: string;
|
||||
}
|
||||
|
||||
interface Form {
|
||||
name: string;
|
||||
path: string;
|
||||
sha256: string;
|
||||
url: string;
|
||||
args: string;
|
||||
egress: string;
|
||||
env: string;
|
||||
tools: string;
|
||||
settings: Record<string, string>;
|
||||
settingPairs: Paired[];
|
||||
slots: Slot[];
|
||||
}
|
||||
|
||||
interface Paired {
|
||||
key: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
const blank = (): Form => ({
|
||||
name: "", path: "", sha256: "", url: "", args: "", egress: "", env: "", tools: "",
|
||||
settings: {}, settingPairs: [], slots: [],
|
||||
});
|
||||
const adding = reactive<Record<ExtensionContract, boolean>>({
|
||||
connector: false,
|
||||
guard: false,
|
||||
secretengine: false,
|
||||
mcp: false,
|
||||
});
|
||||
const forms = reactive<Record<ExtensionContract, Form>>({
|
||||
connector: blank(),
|
||||
guard: blank(),
|
||||
secretengine: blank(),
|
||||
mcp: blank(),
|
||||
});
|
||||
const editing = ref("");
|
||||
const edit = reactive<Form>(blank());
|
||||
const saving = ref(false);
|
||||
|
||||
const columns: DataTableColumn<Extension>[] = [
|
||||
{ id: "name", label: "Name", fixed: true },
|
||||
{ id: "state", label: "State" },
|
||||
{ id: "version", label: "Version" },
|
||||
{ id: "digest", label: "Digest" },
|
||||
];
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
const [connector, guard, secretengine, mcp, creds] = await Promise.all([
|
||||
listExtensions("connector", controller.signal),
|
||||
listExtensions("guard", controller.signal),
|
||||
listExtensions("secretengine", controller.signal),
|
||||
listExtensions("mcp", controller.signal),
|
||||
listCredentials(controller.signal),
|
||||
]);
|
||||
rows.connector = connector;
|
||||
rows.guard = guard;
|
||||
rows.secretengine = secretengine;
|
||||
rows.mcp = mcp;
|
||||
credentials.value = creds;
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function lists(text: string): string[] {
|
||||
return text
|
||||
.split(",")
|
||||
.map((x) => x.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function slotsOf(form: Form): Record<string, string> {
|
||||
return Object.fromEntries(form.slots.filter((s) => s.slot.trim()).map((s) => [s.slot.trim(), s.credential]));
|
||||
}
|
||||
|
||||
function toolsOf(form: Form): unknown[] | undefined {
|
||||
if (!form.tools.trim()) return undefined;
|
||||
return JSON.parse(form.tools) as unknown[];
|
||||
}
|
||||
|
||||
function bodyOf(contract: ExtensionContract, form: Form) {
|
||||
const pairs = Object.fromEntries(form.settingPairs.filter((p) => p.key.trim()).map((p) => [p.key.trim(), p.value]));
|
||||
const base = {
|
||||
path: form.path.trim() || undefined,
|
||||
sha256: form.sha256.trim() || undefined,
|
||||
url: form.url.trim() || undefined,
|
||||
args: lists(form.args),
|
||||
egress: lists(form.egress),
|
||||
env: lists(form.env),
|
||||
settings: { ...pairs, ...form.settings },
|
||||
credentials: slotsOf(form),
|
||||
};
|
||||
if (contract === "mcp") return { ...base, tools: toolsOf(form) };
|
||||
return base;
|
||||
}
|
||||
|
||||
async function accept(contract: ExtensionContract) {
|
||||
const form = forms[contract];
|
||||
saving.value = true;
|
||||
errorAt.value = contract;
|
||||
error.value = "";
|
||||
saved.value = "";
|
||||
try {
|
||||
await acceptExtension(contract, form.name.trim(), bodyOf(contract, form));
|
||||
forms[contract] = blank();
|
||||
adding[contract] = false;
|
||||
saved.value = "Accepted.";
|
||||
await load();
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function startEdit(x: Extension) {
|
||||
errorAt.value = x.name;
|
||||
error.value = "";
|
||||
saved.value = "";
|
||||
editing.value = editing.value === x.name ? "" : x.name;
|
||||
Object.assign(edit, {
|
||||
name: x.name,
|
||||
path: x.path ?? "",
|
||||
sha256: x.digest,
|
||||
url: x.url ?? "",
|
||||
args: (x.args ?? []).join(", "),
|
||||
egress: (x.egress ?? []).join(", "),
|
||||
env: (x.env ?? []).join(", "),
|
||||
tools: x.tools ? JSON.stringify(x.tools, null, 2) : "",
|
||||
settings: { ...x.settings },
|
||||
settingPairs: [],
|
||||
slots: Object.entries(x.credentials ?? {}).map(([slot, credential]) => ({ slot, credential })),
|
||||
});
|
||||
}
|
||||
|
||||
async function save(x: Extension) {
|
||||
saving.value = true;
|
||||
errorAt.value = x.name;
|
||||
error.value = "";
|
||||
saved.value = "";
|
||||
try {
|
||||
await acceptExtension(x.contract, x.name, bodyOf(x.contract, edit));
|
||||
saved.value = "Saved.";
|
||||
editing.value = "";
|
||||
await load();
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function remove(x: Extension) {
|
||||
if (!confirm(`Remove ${x.name}? Its process stops and its acceptance is deleted.`)) return;
|
||||
errorAt.value = x.name;
|
||||
error.value = "";
|
||||
try {
|
||||
await removeExtension(x.contract, x.name);
|
||||
await load();
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
}
|
||||
}
|
||||
|
||||
function tone(state: Extension["state"]): "ok" | "warn" | "danger" | "idle" {
|
||||
if (state === "running") return "ok";
|
||||
if (state === "failed") return "danger";
|
||||
return "idle";
|
||||
}
|
||||
|
||||
function fail(err: unknown) {
|
||||
if (controller.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
function setSetting(key: string, value: string) {
|
||||
edit.settings = { ...edit.settings, [key]: value };
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader title="Extensions" />
|
||||
<Spinner v-if="loading" />
|
||||
<ReadError v-else-if="error && !editing && !Object.values(adding).some(Boolean)" :message="error" retry-label="Retry" @retry="load" />
|
||||
<template v-else>
|
||||
<div v-for="c in contracts" :key="c.id">
|
||||
<Section :title="c.title">
|
||||
<template #action>
|
||||
<Button variant="outline" size="xs" @click="adding[c.id] = !adding[c.id]">Add</Button>
|
||||
</template>
|
||||
|
||||
<div v-for="items in [rows[c.id]]" :key="`${c.id}-list`">
|
||||
<Empty v-if="items.length === 0">
|
||||
<EmptyHeader><EmptyTitle>No extensions accepted</EmptyTitle></EmptyHeader>
|
||||
</Empty>
|
||||
<DataTable v-if="items.length" :columns="columns" :rows="items" :row-key="(x) => x.name" :storage-key="`extensions-${c.id}`">
|
||||
<template #cell-name="{ row }"><span class="font-medium">{{ row.name }}</span></template>
|
||||
<template #cell-state="{ row }">
|
||||
<span class="flex items-center gap-2">
|
||||
<Badge :variant="tone(row.state)">{{ row.state }}</Badge>
|
||||
<span v-if="row.error" class="text-caption text-danger">{{ row.error }}</span>
|
||||
</span>
|
||||
</template>
|
||||
<template #cell-version="{ row }">{{ row.version || "—" }}</template>
|
||||
<template #cell-digest="{ row }"><span class="font-mono text-caption" :title="row.digest">{{ row.digest.slice(0, 12) }}</span></template>
|
||||
<template #actions="{ row }">
|
||||
<MoreMenu :label="`Actions for ${row.name}`">
|
||||
<Button variant="ghost" size="sm" class="w-full justify-start text-danger" @click="remove(row)">Remove</Button>
|
||||
</MoreMenu>
|
||||
</template>
|
||||
<template #detail="{ row }">
|
||||
<div class="flex flex-col gap-3">
|
||||
<p v-if="!row.settings_schema.length && !Object.keys(row.credentials ?? {}).length" class="text-caption text-fg-subtle">This package declares no settings.</p>
|
||||
<template v-else-if="editing === row.name">
|
||||
<SettingRow v-for="s in row.settings_schema" :key="s.key" :label="s.label" :hint="s.description" :for="`${row.name}-${s.key}`">
|
||||
<Switch
|
||||
v-if="s.type === 'boolean'"
|
||||
:id="`${row.name}-${s.key}`"
|
||||
:model-value="edit.settings[s.key] === 'true'"
|
||||
@update:model-value="(on) => setSetting(s.key, String(on))"
|
||||
/>
|
||||
<Select
|
||||
v-else-if="s.type === 'select'"
|
||||
:model-value="edit.settings[s.key] ?? ''"
|
||||
@update:model-value="(v) => setSetting(s.key, String(v))"
|
||||
>
|
||||
<SelectTrigger :id="`${row.name}-${s.key}`" class="w-full sm:w-64"><SelectValue placeholder="Choose" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="option in s.options ?? []" :key="option" :value="option">{{ option }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Textarea
|
||||
v-else-if="s.type === 'text'"
|
||||
:id="`${row.name}-${s.key}`"
|
||||
:model-value="edit.settings[s.key] ?? ''"
|
||||
rows="5"
|
||||
spellcheck="false"
|
||||
@update:model-value="(v) => setSetting(s.key, String(v))"
|
||||
/>
|
||||
<Input
|
||||
v-else
|
||||
:id="`${row.name}-${s.key}`"
|
||||
:model-value="edit.settings[s.key] ?? ''"
|
||||
:type="s.type === 'number' ? 'number' : 'text'"
|
||||
:placeholder="s.secret ? 'engine:key' : ''"
|
||||
@update:model-value="(v) => setSetting(s.key, String(v))"
|
||||
/>
|
||||
</SettingRow>
|
||||
<SettingRow label="Credential slots" hint="Assign a credential to each slot.">
|
||||
<div class="flex flex-col gap-2">
|
||||
<div v-for="(slot, index) in edit.slots" :key="index" class="flex flex-wrap items-center gap-2">
|
||||
<Input v-model="slot.slot" placeholder="slot" class="w-40" aria-label="Credential slot" />
|
||||
<Select v-model="slot.credential">
|
||||
<SelectTrigger class="w-48" aria-label="Credential"><SelectValue placeholder="Credential" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="c in credentials" :key="c.name" :value="c.name">{{ c.name }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button variant="ghost" size="xs" @click="edit.slots.splice(index, 1)">Remove</Button>
|
||||
</div>
|
||||
<Button variant="outline" size="xs" class="self-start" @click="edit.slots.push({ slot: '', credential: '' })">Add slot</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<Button size="sm" :disabled="saving" @click="save(row)">Save settings</Button>
|
||||
<Button variant="ghost" size="sm" @click="editing = ''">Cancel</Button>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
<SettingRow v-for="s in row.settings_schema" :key="s.key" :label="s.label" :hint="s.description">
|
||||
<span class="font-mono text-label">{{ row.settings[s.key] || "Not set" }}</span>
|
||||
</SettingRow>
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" size="sm" @click="startEdit(row)">Edit</Button>
|
||||
</div>
|
||||
</template>
|
||||
<p v-if="editing !== row.name && Object.keys(row.credentials ?? {}).length" class="text-caption text-fg-subtle">
|
||||
Credential slots: {{ Object.entries(row.credentials).map(([slot, name]) => `${slot} → ${name}`).join(", ") }}
|
||||
</p>
|
||||
<p v-if="error && errorAt === row.name" class="text-caption text-danger">{{ error }}</p>
|
||||
</div>
|
||||
</template>
|
||||
</DataTable>
|
||||
</div>
|
||||
<div v-if="adding[c.id]" class="mb-4 flex flex-col gap-3 border-b border-border pb-4">
|
||||
<SettingRow label="Name" :for="`${c.id}-name`">
|
||||
<Input :id="`${c.id}-name`" v-model="forms[c.id].name" placeholder="lowercase-name" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Binary" :for="`${c.id}-path`" hint="A path and its SHA-256, or an HTTP endpoint for an MCP server.">
|
||||
<div class="flex flex-col gap-2">
|
||||
<Input :id="`${c.id}-path`" v-model="forms[c.id].path" placeholder="Path" />
|
||||
<Input v-model="forms[c.id].sha256" placeholder="SHA-256" class="font-mono" />
|
||||
<Input v-if="c.id === 'mcp'" v-model="forms[c.id].url" placeholder="https://…" />
|
||||
</div>
|
||||
</SettingRow>
|
||||
<SettingRow label="Egress" :for="`${c.id}-egress`" hint="Comma-separated hosts it may reach. Empty runs it on the host network.">
|
||||
<Input :id="`${c.id}-egress`" v-model="forms[c.id].egress" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Environment" :for="`${c.id}-env`" hint="Comma-separated names of host environment variables the extension may read.">
|
||||
<Input :id="`${c.id}-env`" v-model="forms[c.id].env" />
|
||||
</SettingRow>
|
||||
<SettingRow v-if="c.id === 'mcp'" label="Arguments" :for="`${c.id}-args`">
|
||||
<Input :id="`${c.id}-args`" v-model="forms[c.id].args" />
|
||||
</SettingRow>
|
||||
<SettingRow v-if="c.id === 'mcp'" label="Tools" :for="`${c.id}-tools`" hint="The tools the server may offer, as JSON.">
|
||||
<Textarea :id="`${c.id}-tools`" v-model="forms[c.id].tools" rows="5" class="font-mono" spellcheck="false" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Credential slots">
|
||||
<div class="flex flex-col gap-2">
|
||||
<div v-for="(slot, index) in forms[c.id].slots" :key="index" class="flex flex-wrap items-center gap-2">
|
||||
<Input v-model="slot.slot" placeholder="slot" class="w-40" aria-label="Credential slot" />
|
||||
<Select v-model="slot.credential">
|
||||
<SelectTrigger class="w-48" aria-label="Credential"><SelectValue placeholder="Credential" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="name in credentials.map((x) => x.name)" :key="name" :value="name">{{ name }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Button variant="ghost" size="xs" @click="forms[c.id].slots.splice(index, 1)">Remove</Button>
|
||||
</div>
|
||||
<Button variant="outline" size="xs" class="self-start" @click="forms[c.id].slots.push({ slot: '', credential: '' })">Add slot</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
<SettingRow label="Settings" hint="Use only setting keys declared by the extension.">
|
||||
<div class="flex flex-col gap-2">
|
||||
<div v-for="(pair, index) in forms[c.id].settingPairs" :key="index" class="flex flex-wrap items-center gap-2">
|
||||
<Input v-model="pair.key" placeholder="key" class="w-40" aria-label="Setting key" />
|
||||
<Input v-model="pair.value" placeholder="value" class="w-48" aria-label="Setting value" />
|
||||
<Button variant="ghost" size="xs" @click="forms[c.id].settingPairs.splice(index, 1)">Remove</Button>
|
||||
</div>
|
||||
<Button variant="outline" size="xs" class="self-start" @click="forms[c.id].settingPairs.push({ key: '', value: '' })">Add setting</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
<p v-if="error && errorAt === c.id" class="text-caption text-danger">{{ error }}</p>
|
||||
<div class="flex items-center gap-2">
|
||||
<Button :disabled="saving || !forms[c.id].name.trim()" @click="accept(c.id)">{{ c.add }}</Button>
|
||||
<Button type="button" variant="ghost" @click="adding[c.id] = false">Cancel</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Section>
|
||||
</div>
|
||||
<p v-if="saved" class="text-caption text-muted-foreground">{{ saved }}</p>
|
||||
<p v-if="error && !errorAt" class="text-caption text-danger">{{ error }}</p>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,113 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { SettingRow } from "@/components/ui/setting-row";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { TagsInput, TagsInputInput, TagsInputItem, TagsInputItemDelete, TagsInputItemText } from "@/components/ui/tags-input";
|
||||
import { getPeople, savePeople, Unauthorized, type Person } from "./api";
|
||||
|
||||
/**
|
||||
* A response from a channel must be linked to a person before the server
|
||||
* checks whether that person can respond to the request.
|
||||
*/
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
|
||||
const people = ref<Person[]>([]);
|
||||
const saved = ref("");
|
||||
const loading = ref(true);
|
||||
const saving = ref(false);
|
||||
const error = ref("");
|
||||
const controller = new AbortController();
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
people.value = await getPeople(controller.signal);
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
saving.value = true;
|
||||
error.value = "";
|
||||
saved.value = "";
|
||||
try {
|
||||
await savePeople(people.value);
|
||||
people.value = await getPeople(controller.signal);
|
||||
saved.value = "Saved.";
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function add() {
|
||||
people.value.push({ id: "", name: "", authority: false, identities: [] });
|
||||
}
|
||||
|
||||
function remove(index: number) {
|
||||
people.value.splice(index, 1);
|
||||
}
|
||||
|
||||
function fail(err: unknown) {
|
||||
if (controller.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader title="People" />
|
||||
<Spinner v-if="loading" />
|
||||
<ReadError v-else-if="error && !people.length" :message="error" retry-label="Retry" @retry="load" />
|
||||
<template v-else>
|
||||
<Empty v-if="!people.length">
|
||||
<EmptyHeader>
|
||||
<EmptyTitle>No people configured</EmptyTitle>
|
||||
</EmptyHeader>
|
||||
</Empty>
|
||||
<Section v-for="(person, index) in people" :key="person.id || `new-${index}`">
|
||||
<SettingRow label="Name" :for="`name-${index}`">
|
||||
<div class="flex gap-2">
|
||||
<Input :id="`name-${index}`" v-model="person.name" />
|
||||
<Button variant="ghost" size="xs" @click="remove(index)">Remove</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
<SettingRow label="Identities" :for="`identities-${index}`">
|
||||
<TagsInput v-model="person.identities" class="font-mono">
|
||||
<TagsInputItem v-for="identity in person.identities" :key="identity" :value="identity">
|
||||
<TagsInputItemText />
|
||||
<TagsInputItemDelete />
|
||||
</TagsInputItem>
|
||||
<TagsInputInput :id="`identities-${index}`" placeholder="telegram:1001" />
|
||||
</TagsInput>
|
||||
</SettingRow>
|
||||
<SettingRow label="Authority" :for="`authority-${index}`">
|
||||
<Switch :id="`authority-${index}`" v-model="person.authority" aria-label="Authority" />
|
||||
</SettingRow>
|
||||
</Section>
|
||||
<p v-if="error" class="mb-2 text-caption text-danger">{{ error }}</p>
|
||||
<div class="flex items-center gap-3">
|
||||
<Button variant="outline" @click="add">Add person</Button>
|
||||
<Button :disabled="saving" @click="save">Save</Button>
|
||||
<span v-if="saved" class="text-caption text-muted-foreground">{{ saved }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,181 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Bot, Footprints, Wrench } from "@lucide/vue";
|
||||
import { computed, onBeforeUnmount, ref, watch } from "vue";
|
||||
|
||||
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
|
||||
import { MetadataList } from "@/components/ui/metadata-list";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { StatusDot } from "@/components/ui/status-dot";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import {
|
||||
Trace,
|
||||
TraceCollapsible,
|
||||
TraceCollapsibleContent,
|
||||
TraceCollapsibleTrigger,
|
||||
TraceIcon,
|
||||
TraceLine,
|
||||
TraceTitle,
|
||||
} from "@/components/ui/trace";
|
||||
import ActionTrailView from "./ActionTrailView.vue";
|
||||
import { runTrail, type Trail, type TrailEntry, type Usage, Unauthorized } from "./api";
|
||||
import { runTone } from "./state";
|
||||
|
||||
/** A run's decision trail: what started it, every step in order, and how it ended. */
|
||||
const props = defineProps<{ id: string }>();
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
|
||||
const trail = ref<Trail>();
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
let controller = new AbortController();
|
||||
|
||||
async function load() {
|
||||
controller.abort();
|
||||
controller = new AbortController();
|
||||
const signal = controller.signal;
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
const got = await runTrail(props.id, signal);
|
||||
if (!signal.aborted) trail.value = got;
|
||||
} catch (err) {
|
||||
if (signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
if (!signal.aborted) loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
watch(() => props.id, load, { immediate: true });
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
|
||||
const originRows = computed(() => {
|
||||
const o = trail.value?.origin;
|
||||
if (!o) return [];
|
||||
return [
|
||||
{ label: "Source", value: o.source },
|
||||
{ label: "Event", value: o.type },
|
||||
{ label: "Trigger", value: o.trigger },
|
||||
];
|
||||
});
|
||||
|
||||
const usage = computed(() => trail.value?.run.result?.usage);
|
||||
|
||||
function title(e: TrailEntry): string {
|
||||
switch (e.kind) {
|
||||
case "model":
|
||||
return e.tool_calls?.length ? `Model asked for ${e.tool_calls.map((c) => c.name).join(", ")}` : "Model answered";
|
||||
case "compaction":
|
||||
return "History compacted";
|
||||
case "tool":
|
||||
return e.unknown ? `${e.name}: outcome unknown` : e.error ? `${e.name} failed` : (e.name ?? "Tool");
|
||||
default:
|
||||
return e.name ?? "Step";
|
||||
}
|
||||
}
|
||||
|
||||
const json = (v: unknown) => JSON.stringify(v, null, 2);
|
||||
|
||||
const usageRows = (u: Usage) => [
|
||||
{ label: "Prompt tokens", value: u.prompt_tokens.toLocaleString() },
|
||||
{ label: "Completion tokens", value: u.completion_tokens.toLocaleString() },
|
||||
{ label: "Total tokens", value: u.total_tokens.toLocaleString() },
|
||||
];
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<Spinner v-if="loading && !trail" />
|
||||
<ReadError v-else-if="error" :message="error" retry-label="Retry" @retry="load" />
|
||||
<template v-else-if="trail">
|
||||
<Section :title="trail.run.workflow">
|
||||
<template #action>
|
||||
<span class="flex items-center gap-2 text-caption">
|
||||
<StatusDot :tone="runTone(trail.run.state)" :live="trail.run.state === 'running'" />{{ trail.run.state }}
|
||||
<Timestamp :at="trail.run.created_at" />
|
||||
</span>
|
||||
</template>
|
||||
<p v-if="trail.run.result?.answer" class="whitespace-pre-wrap text-label">{{ trail.run.result.answer }}</p>
|
||||
<p v-if="trail.run.error" class="text-label text-destructive">{{ trail.run.error }}</p>
|
||||
<p v-if="usage" class="mt-2 text-caption text-muted-foreground">
|
||||
{{ usage.total_tokens.toLocaleString() }} tokens, {{ trail.run.result?.tool_calls ?? 0 }} tool calls
|
||||
</p>
|
||||
</Section>
|
||||
<Section v-if="trail.origin" title="Started by">
|
||||
<MetadataList :rows="originRows" />
|
||||
<CodeBlock size="sm" class="mt-2">
|
||||
<CodeBlockContent wrap class="max-h-64">{{ json(trail.origin.fields) }}</CodeBlockContent>
|
||||
</CodeBlock>
|
||||
</Section>
|
||||
<Section v-if="trail.actions.length" title="Actions">
|
||||
<div class="flex flex-col gap-3">
|
||||
<ActionTrailView v-for="a in trail.actions" :key="a.decision.id" :action="a" />
|
||||
</div>
|
||||
</Section>
|
||||
<Section title="Steps">
|
||||
<Trace>
|
||||
<TraceCollapsible v-for="e in trail.entries" :key="e.seq" :default-open="Boolean(e.error || e.unknown)">
|
||||
<TraceCollapsibleTrigger>
|
||||
<TraceLine :status="e.error || e.unknown ? 'error' : undefined">
|
||||
<TraceIcon>
|
||||
<Bot v-if="e.kind === 'model' || e.kind === 'compaction'" />
|
||||
<Wrench v-else-if="e.kind === 'tool'" />
|
||||
<Footprints v-else />
|
||||
</TraceIcon>
|
||||
<TraceTitle class="truncate">{{ title(e) }}</TraceTitle>
|
||||
<span v-if="e.usage" class="text-caption tabular-nums">{{ e.usage.total_tokens.toLocaleString() }} tokens</span>
|
||||
</TraceLine>
|
||||
</TraceCollapsibleTrigger>
|
||||
<TraceCollapsibleContent>
|
||||
<div class="flex flex-col gap-2 text-label">
|
||||
<details v-if="e.request">
|
||||
<summary class="cursor-pointer text-caption text-muted-foreground">Request</summary>
|
||||
<CodeBlock size="sm" class="mt-1">
|
||||
<CodeBlockContent wrap class="max-h-64">{{ json(e.request) }}</CodeBlockContent>
|
||||
</CodeBlock>
|
||||
</details>
|
||||
<details v-if="e.kind === 'model' || e.kind === 'compaction'">
|
||||
<summary class="cursor-pointer text-caption text-muted-foreground">Response</summary>
|
||||
<div class="mt-1 flex flex-col gap-2">
|
||||
<p v-if="e.reasoning" class="whitespace-pre-wrap text-muted-foreground">{{ e.reasoning }}</p>
|
||||
<p v-if="e.text" class="whitespace-pre-wrap">{{ e.text }}</p>
|
||||
<CodeBlock v-for="(c, i) in e.tool_calls" :key="i" size="sm">
|
||||
<CodeBlockContent wrap>{{ c.name }} {{ c.input }}</CodeBlockContent>
|
||||
</CodeBlock>
|
||||
<p v-if="e.finish_reason" class="text-caption text-muted-foreground">
|
||||
Finish reason {{ e.finish_reason }}
|
||||
</p>
|
||||
<MetadataList v-if="e.usage" :rows="usageRows(e.usage)" />
|
||||
<p v-if="e.error" class="text-destructive">{{ e.error }}</p>
|
||||
</div>
|
||||
</details>
|
||||
<template v-else-if="e.kind === 'tool'">
|
||||
<details v-if="e.input">
|
||||
<summary class="cursor-pointer text-caption text-muted-foreground">Request</summary>
|
||||
<CodeBlock size="sm" class="mt-1">
|
||||
<CodeBlockContent wrap class="max-h-64">{{ e.input }}</CodeBlockContent>
|
||||
</CodeBlock>
|
||||
</details>
|
||||
<details v-if="e.output || e.error">
|
||||
<summary class="cursor-pointer text-caption text-muted-foreground">Response</summary>
|
||||
<p v-if="e.error" class="mt-1 text-destructive">{{ e.error }}</p>
|
||||
<CodeBlock v-if="e.output" size="sm" class="mt-1">
|
||||
<CodeBlockContent wrap class="max-h-64">{{ e.output }}</CodeBlockContent>
|
||||
</CodeBlock>
|
||||
</details>
|
||||
</template>
|
||||
<CodeBlock v-if="e.kind === 'step' && e.value !== undefined" size="sm">
|
||||
<CodeBlockContent wrap class="max-h-64">{{ json(e.value) }}</CodeBlockContent>
|
||||
</CodeBlock>
|
||||
<p v-if="e.error && e.kind === 'step'" class="text-destructive">{{ e.error }}</p>
|
||||
</div>
|
||||
</TraceCollapsibleContent>
|
||||
</TraceCollapsible>
|
||||
</Trace>
|
||||
</Section>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,73 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||
import { useRouter } from "vue-router";
|
||||
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { StatusDot } from "@/components/ui/status-dot";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import { listRuns, type Run, Unauthorized } from "./api";
|
||||
import { runTone } from "./state";
|
||||
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
const router = useRouter();
|
||||
|
||||
const runs = ref<Run[]>([]);
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
const controller = new AbortController();
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
runs.value = await listRuns(controller.signal);
|
||||
} catch (err) {
|
||||
if (controller.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<Spinner v-if="loading" />
|
||||
<ReadError v-else-if="error" :message="error" retry-label="Retry" @retry="load" />
|
||||
<Empty v-else-if="runs.length === 0">
|
||||
<EmptyHeader><EmptyTitle>No runs yet</EmptyTitle></EmptyHeader>
|
||||
</Empty>
|
||||
<Table v-else>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Workflow</TableHead>
|
||||
<TableHead>State</TableHead>
|
||||
<TableHead>Started</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow
|
||||
v-for="r in runs"
|
||||
:key="r.id"
|
||||
class="cursor-pointer"
|
||||
tabindex="0"
|
||||
@click="router.push({ name: 'run', params: { id: r.id } })"
|
||||
@keydown.enter="router.push({ name: 'run', params: { id: r.id } })"
|
||||
>
|
||||
<TableCell>{{ r.workflow }}</TableCell>
|
||||
<TableCell>
|
||||
<span class="flex items-center gap-2"><StatusDot :tone="runTone(r.state)" :live="r.state === 'running'" />{{ r.state }}</span>
|
||||
</TableCell>
|
||||
<TableCell><Timestamp :at="r.created_at" /></TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,295 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { DurationInput } from "@/components/ui/duration-input";
|
||||
import { NumberField, NumberFieldContent, NumberFieldDecrement, NumberFieldIncrement, NumberFieldInput } from "@/components/ui/number-field";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { SettingRow } from "@/components/ui/setting-row";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { getPeople, getSettings, saveSettings, Unauthorized, type Blackout, type EscalationStep, type Person } from "./api";
|
||||
import AgentModelEditor from "./AgentModelEditor.vue";
|
||||
import SystemSettings from "./SystemSettings.vue";
|
||||
|
||||
/**
|
||||
* Organisation settings: what Archie does when nobody has decided otherwise.
|
||||
* The approval deadline is a Go duration, edited in the same form it is stored.
|
||||
*/
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
|
||||
const deadline = ref("24h");
|
||||
const raiseAfter = ref(3);
|
||||
const frozen = ref(false);
|
||||
const threshold = ref(5);
|
||||
const attempts = ref(20);
|
||||
const actionsPerRun = ref(10);
|
||||
const actionsPerDay = ref(100);
|
||||
const zone = ref("");
|
||||
const hoursStart = ref("");
|
||||
const hoursEnd = ref("");
|
||||
const days = ref<string[]>([]);
|
||||
const weekdays = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
|
||||
/** A blackout as the form edits it: local date-times, which the API takes as instants. */
|
||||
interface BlackoutRow {
|
||||
from: string;
|
||||
to: string;
|
||||
reason: string;
|
||||
}
|
||||
const blackouts = ref<BlackoutRow[]>([]);
|
||||
const people = ref<Person[]>([]);
|
||||
const none = "none";
|
||||
const owner = ref(none);
|
||||
const escalation = ref<EscalationStep[]>([]);
|
||||
const saved = ref("");
|
||||
const loading = ref(true);
|
||||
const saving = ref(false);
|
||||
const error = ref("");
|
||||
const controller = new AbortController();
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
const [set, everyone] = await Promise.all([getSettings(controller.signal), getPeople(controller.signal)]);
|
||||
people.value = everyone;
|
||||
deadline.value = set.approval_deadline;
|
||||
raiseAfter.value = set.raise_after;
|
||||
frozen.value = set.frozen;
|
||||
threshold.value = set.recurrence_threshold;
|
||||
attempts.value = set.attempts_per_run;
|
||||
actionsPerRun.value = set.actions_per_run;
|
||||
actionsPerDay.value = set.actions_per_day;
|
||||
zone.value = set.timing.zone;
|
||||
hoursStart.value = set.timing.start;
|
||||
hoursEnd.value = set.timing.end;
|
||||
days.value = set.timing.days;
|
||||
blackouts.value = set.timing.blackouts.map((b) => ({ from: toLocal(b.from), to: toLocal(b.to), reason: b.reason }));
|
||||
owner.value = set.default_owner || none;
|
||||
escalation.value = set.escalation;
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function save() {
|
||||
saving.value = true;
|
||||
error.value = "";
|
||||
saved.value = "";
|
||||
try {
|
||||
await saveSettings({
|
||||
approval_deadline: deadline.value,
|
||||
raise_after: raiseAfter.value,
|
||||
frozen: frozen.value,
|
||||
recurrence_threshold: threshold.value,
|
||||
attempts_per_run: attempts.value,
|
||||
default_owner: owner.value === none ? "" : owner.value,
|
||||
escalation: escalation.value,
|
||||
actions_per_run: actionsPerRun.value,
|
||||
actions_per_day: actionsPerDay.value,
|
||||
timing: {
|
||||
zone: zone.value,
|
||||
start: hoursStart.value,
|
||||
end: hoursEnd.value,
|
||||
days: days.value,
|
||||
blackouts: blackouts.value.map((b): Blackout => ({ from: toInstant(b.from), to: toInstant(b.to), reason: b.reason })),
|
||||
},
|
||||
});
|
||||
saved.value = "Saved.";
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** An instant as the local "2026-01-02T15:04" a datetime-local input takes. */
|
||||
function toLocal(instant: string): string {
|
||||
const d = new Date(instant);
|
||||
const pad = (n: number) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
}
|
||||
|
||||
function toInstant(local: string): string {
|
||||
const d = new Date(local);
|
||||
return Number.isNaN(d.getTime()) ? "" : d.toISOString();
|
||||
}
|
||||
|
||||
function toggleDay(day: string) {
|
||||
days.value = days.value.includes(day) ? days.value.filter((d) => d !== day) : [...days.value, day];
|
||||
}
|
||||
|
||||
const addable = () => people.value.filter((p) => !escalation.value.some((st) => st.person === p.id));
|
||||
const nameOf = (id: string) => people.value.find((p) => p.id === id)?.name ?? id;
|
||||
|
||||
function move(index: number, by: number) {
|
||||
const next = [...escalation.value];
|
||||
const [id] = next.splice(index, 1);
|
||||
next.splice(index + by, 0, id);
|
||||
escalation.value = next;
|
||||
}
|
||||
|
||||
function fail(err: unknown) {
|
||||
if (controller.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader title="Settings" />
|
||||
<Spinner v-if="loading" />
|
||||
<ReadError v-else-if="error" :message="error" retry-label="Retry" @retry="load" />
|
||||
<Section v-else>
|
||||
<SettingRow label="Approval deadline" for="approval-deadline">
|
||||
<DurationInput id="approval-deadline" v-model="deadline" />
|
||||
</SettingRow>
|
||||
<p class="text-caption text-muted-foreground">
|
||||
How long a request waits on the default owner before it moves to the first person on the escalation path.
|
||||
</p>
|
||||
<SettingRow label="Approvals to propose a raise" for="raise-after">
|
||||
<NumberField v-model="raiseAfter" :min="1" :max="100" class="w-32">
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput id="raise-after" class="font-mono" />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</SettingRow>
|
||||
<p class="text-caption text-muted-foreground">
|
||||
Approvals in a row, since a class was last tightened, before Archie proposes raising it one level.
|
||||
</p>
|
||||
<SettingRow label="Recurrence threshold" for="recurrence-threshold">
|
||||
<NumberField v-model="threshold" :min="2" :max="100" class="w-32">
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput id="recurrence-threshold" class="font-mono" />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</SettingRow>
|
||||
<p class="text-caption text-muted-foreground">
|
||||
Incidents with the same cause on one target, whatever their outcome, before Archie proposes a root-cause fix.
|
||||
</p>
|
||||
<SettingRow label="Attempts per run" for="attempts-per-run">
|
||||
<NumberField v-model="attempts" :min="2" :max="200" class="w-32">
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput id="attempts-per-run" class="font-mono" />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</SettingRow>
|
||||
<p class="text-caption text-muted-foreground">Steps an agent may take in one run before it stops.</p>
|
||||
<SettingRow label="Actions per run" for="actions-per-run">
|
||||
<NumberField v-model="actionsPerRun" :min="1" :max="10000" class="w-32">
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput id="actions-per-run" class="font-mono" />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</SettingRow>
|
||||
<SettingRow label="Actions per day" for="actions-per-day">
|
||||
<NumberField v-model="actionsPerDay" :min="1" :max="10000" class="w-32">
|
||||
<NumberFieldContent>
|
||||
<NumberFieldDecrement />
|
||||
<NumberFieldInput id="actions-per-day" class="font-mono" />
|
||||
<NumberFieldIncrement />
|
||||
</NumberFieldContent>
|
||||
</NumberField>
|
||||
</SettingRow>
|
||||
<p class="text-caption text-muted-foreground">
|
||||
Actions that change something, per run and over any 24 hours. Past either, the next one waits for approval.
|
||||
</p>
|
||||
<SettingRow label="Business hours" for="hours-start">
|
||||
<div class="flex items-center gap-2">
|
||||
<Input id="hours-start" v-model="hoursStart" type="time" class="w-32" aria-label="Business hours start" />
|
||||
<Input v-model="hoursEnd" type="time" class="w-32" aria-label="Business hours end" />
|
||||
<Input v-model="zone" class="w-48" placeholder="Zone, such as Australia/Sydney" aria-label="Time zone" />
|
||||
</div>
|
||||
</SettingRow>
|
||||
<SettingRow label="Business days">
|
||||
<div class="flex gap-1">
|
||||
<Button
|
||||
v-for="day in weekdays"
|
||||
:key="day"
|
||||
:variant="days.includes(day) ? 'default' : 'outline'"
|
||||
size="xs"
|
||||
:aria-pressed="days.includes(day)"
|
||||
@click="toggleDay(day)"
|
||||
>
|
||||
{{ day }}
|
||||
</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
<p class="text-caption text-muted-foreground">
|
||||
Outside these, actions that change something wait for approval. Leave the times empty for every hour, and no days for every day.
|
||||
</p>
|
||||
<SettingRow label="Blackouts">
|
||||
<div class="flex flex-col gap-2">
|
||||
<div v-for="(b, index) in blackouts" :key="index" class="flex items-center gap-2">
|
||||
<Input v-model="b.from" type="datetime-local" class="w-56" aria-label="Blackout start" />
|
||||
<Input v-model="b.to" type="datetime-local" class="w-56" aria-label="Blackout end" />
|
||||
<Input v-model="b.reason" class="w-48" placeholder="Reason" aria-label="Blackout reason" />
|
||||
<Button variant="ghost" size="xs" @click="blackouts.splice(index, 1)">Remove</Button>
|
||||
</div>
|
||||
<Button variant="outline" size="xs" class="self-start" @click="blackouts.push({ from: '', to: '', reason: '' })">Add blackout</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
<SettingRow label="Default owner" for="default-owner">
|
||||
<Select v-model="owner">
|
||||
<SelectTrigger id="default-owner" class="w-64"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem :value="none">No one</SelectItem>
|
||||
<SelectItem v-for="p in people" :key="p.id" :value="p.id">{{ p.name }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
<SettingRow label="Escalation path">
|
||||
<div class="flex flex-col gap-2">
|
||||
<div v-for="(step, index) in escalation" :key="step.person" class="flex items-center gap-2">
|
||||
<span class="text-label">{{ index + 1 }}. {{ nameOf(step.person) }}</span>
|
||||
<DurationInput v-model="step.deadline" />
|
||||
<Button variant="ghost" size="xs" :disabled="index === 0" aria-label="Move up" @click="move(index, -1)">Up</Button>
|
||||
<Button variant="ghost" size="xs" :disabled="index === escalation.length - 1" aria-label="Move down" @click="move(index, 1)">Down</Button>
|
||||
<Button variant="ghost" size="xs" @click="escalation = escalation.filter((x) => x.person !== step.person)">Remove</Button>
|
||||
</div>
|
||||
<Select v-if="addable().length" model-value="" @update:model-value="(id) => escalation.push({ person: String(id), deadline: deadline })">
|
||||
<SelectTrigger class="w-64" aria-label="Add to escalation path"><SelectValue placeholder="Add person" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="p in addable()" :key="p.id" :value="p.id">{{ p.name }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</SettingRow>
|
||||
<p class="text-caption text-muted-foreground">
|
||||
A request goes to the default owner first. When a step's deadline passes unanswered it moves to the next person, and when the last one passes nothing runs. People on the path answer once it reaches them; an action that needs authority skips anyone without it.
|
||||
</p>
|
||||
<SettingRow label="Freeze" for="frozen" tone="danger">
|
||||
<Switch id="frozen" v-model="frozen" aria-label="Freeze" />
|
||||
</SettingRow>
|
||||
<p class="text-caption text-muted-foreground">
|
||||
Every action that changes something waits for approval. Class levels stay as they are.
|
||||
</p>
|
||||
<div class="mt-3 flex items-center gap-3">
|
||||
<Button :disabled="saving" @click="save">Save</Button>
|
||||
<span v-if="saved" class="text-caption text-muted-foreground">{{ saved }}</span>
|
||||
</div>
|
||||
</Section>
|
||||
<template v-if="!loading && !error">
|
||||
<AgentModelEditor @unauthorized="emit('unauthorized')" />
|
||||
<SystemSettings @unauthorized="emit('unauthorized')" />
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,184 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, reactive, ref } from "vue";
|
||||
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { SettingRow } from "@/components/ui/setting-row";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { TagsInput, TagsInputInput, TagsInputItem, TagsInputItemDelete, TagsInputItemText } from "@/components/ui/tags-input";
|
||||
import { listExtensions, listSources, putKeyFields, putSource, Unauthorized, type Extension, type SourceView } from "./api";
|
||||
|
||||
/**
|
||||
* The API returns a source token only when it is issued or rotated.
|
||||
*/
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
|
||||
const sources = ref<SourceView[]>([]);
|
||||
const connectors = ref<Extension[]>([]);
|
||||
const keyFields = reactive<Record<string, string[]>>({});
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
const saved = ref("");
|
||||
const name = ref("");
|
||||
const connector = ref("");
|
||||
const issued = ref<{ source: string; token: string; url: string } | null>(null);
|
||||
const copied = ref("");
|
||||
const saving = ref(false);
|
||||
const controller = new AbortController();
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
const [found, running] = await Promise.all([listSources(controller.signal), listExtensions("connector", controller.signal)]);
|
||||
sources.value = found;
|
||||
connectors.value = running.filter((c) => c.state === "running");
|
||||
for (const src of found) keyFields[src.name] = [...src.key_fields];
|
||||
if (!connector.value && connectors.value.length) connector.value = connectors.value[0].name;
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function add() {
|
||||
saving.value = true;
|
||||
error.value = "";
|
||||
issued.value = null;
|
||||
try {
|
||||
issued.value = await putSource(name.value.trim(), connector.value);
|
||||
name.value = "";
|
||||
await load();
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function rotate(src: SourceView) {
|
||||
saving.value = true;
|
||||
error.value = "";
|
||||
issued.value = null;
|
||||
try {
|
||||
issued.value = await putSource(src.name, src.connector);
|
||||
await load();
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveKeyFields(src: SourceView) {
|
||||
saving.value = true;
|
||||
error.value = "";
|
||||
saved.value = "";
|
||||
try {
|
||||
const out = await putKeyFields(src.name, keyFields[src.name] ?? []);
|
||||
keyFields[src.name] = out.key_fields;
|
||||
saved.value = "Saved.";
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function copy(token: string) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(token);
|
||||
copied.value = token;
|
||||
} catch {
|
||||
copied.value = "";
|
||||
}
|
||||
}
|
||||
|
||||
function fail(err: unknown) {
|
||||
if (controller.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader title="Sources" />
|
||||
<Spinner v-if="loading" />
|
||||
<ReadError v-else-if="error && !sources.length" :message="error" retry-label="Retry" @retry="load" />
|
||||
<template v-else>
|
||||
<Section title="New source">
|
||||
<form class="flex flex-col gap-3" @submit.prevent="add">
|
||||
<SettingRow label="Name" for="source-name">
|
||||
<Input id="source-name" v-model="name" placeholder="lowercase-name" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Connector" for="source-connector">
|
||||
<Select v-model="connector">
|
||||
<SelectTrigger id="source-connector" class="w-full sm:w-64"><SelectValue placeholder="Choose a running connector" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="c in connectors" :key="c.name" :value="c.name">{{ c.name }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
<p class="text-caption text-fg-subtle">
|
||||
Every delivery must carry the source's token as a bearer token. A new source gets one, shown once.
|
||||
</p>
|
||||
<p v-if="!connectors.length" class="text-caption text-warn">No connector is running, so a new source has nothing to parse its events.</p>
|
||||
<div class="flex items-center gap-2">
|
||||
<Button type="submit" :disabled="saving || !name.trim() || !connector">Add source</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Section>
|
||||
|
||||
<Section v-if="issued" title="Token" description="Copy the token now. You won't be able to retrieve it later.">
|
||||
<div class="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<Input :model-value="issued.token" readonly class="font-mono" aria-label="Source token" />
|
||||
<div class="flex items-center gap-2">
|
||||
<Button variant="outline" @click="copy(issued.token)">{{ copied === issued.token ? "Copied" : "Copy" }}</Button>
|
||||
<Button variant="ghost" @click="issued = null">Done</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p class="mt-2 text-caption text-fg-subtle">Deliver to <span class="font-mono">{{ issued.url }}</span></p>
|
||||
</Section>
|
||||
|
||||
<Empty v-if="!sources.length">
|
||||
<EmptyHeader><EmptyTitle>No sources yet</EmptyTitle></EmptyHeader>
|
||||
</Empty>
|
||||
<Section v-for="src in sources" :key="src.name" :title="src.name">
|
||||
<template #action>
|
||||
<div class="flex items-center gap-2">
|
||||
<Badge :variant="src.token_set ? 'ok' : 'idle'">{{ src.token_set ? "Token set" : "No token" }}</Badge>
|
||||
<Button variant="ghost" size="xs" @click="rotate(src)">Rotate token</Button>
|
||||
</div>
|
||||
</template>
|
||||
<SettingRow label="Connector">
|
||||
<span class="text-label">{{ src.connector }}</span>
|
||||
</SettingRow>
|
||||
<SettingRow label="Key fields" hint="Events with matching values for these fields are grouped together. Leave blank to use the connector's defaults.">
|
||||
<TagsInput v-model="keyFields[src.name]" class="font-mono">
|
||||
<TagsInputItem v-for="path in keyFields[src.name]" :key="path" :value="path">
|
||||
<TagsInputItemText />
|
||||
<TagsInputItemDelete />
|
||||
</TagsInputItem>
|
||||
<TagsInputInput :aria-label="`Add a key field to ${src.name}`" placeholder="resource.id" />
|
||||
</TagsInput>
|
||||
</SettingRow>
|
||||
<div class="mt-2 flex items-center gap-3">
|
||||
<Button size="sm" :disabled="saving" @click="saveKeyFields(src)">Save</Button>
|
||||
<p v-if="error" class="text-caption text-danger">{{ error }}</p>
|
||||
</div>
|
||||
</Section>
|
||||
<p v-if="saved" class="text-caption text-muted-foreground">{{ saved }}</p>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,103 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from "vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { MetadataList } from "@/components/ui/metadata-list";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { getBootstrap, rotateAdminToken, Unauthorized, type BootstrapView } from "./api";
|
||||
|
||||
/**
|
||||
* Bootstrap settings are loaded before the database is available. The only
|
||||
* bootstrap setting this page can change is the admin token.
|
||||
*/
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
|
||||
const bootstrap = ref<BootstrapView | null>(null);
|
||||
const issued = ref("");
|
||||
const copied = ref(false);
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
const saving = ref(false);
|
||||
const controller = new AbortController();
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
bootstrap.value = await getBootstrap(controller.signal);
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function rotate() {
|
||||
if (!confirm("Rotate the admin token? Every browser using the old token is signed out.")) return;
|
||||
saving.value = true;
|
||||
error.value = "";
|
||||
issued.value = "";
|
||||
try {
|
||||
const result = await rotateAdminToken();
|
||||
issued.value = result.token;
|
||||
await load();
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function copy() {
|
||||
try {
|
||||
await navigator.clipboard.writeText(issued.value);
|
||||
copied.value = true;
|
||||
} catch {
|
||||
copied.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function fail(err: unknown) {
|
||||
if (controller.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Section title="System" description="To change the settings below, edit the configuration file and restart Archie.">
|
||||
<Spinner v-if="loading" />
|
||||
<ReadError v-else-if="error && !bootstrap" :message="error" retry-label="Retry" @retry="load" />
|
||||
<template v-else-if="bootstrap">
|
||||
<MetadataList
|
||||
:rows="[
|
||||
{ label: 'Listen', value: bootstrap.listen, mono: true },
|
||||
{ label: 'Database host', value: bootstrap.database_host, mono: true },
|
||||
{ label: 'Schemas', value: String(bootstrap.schemas) },
|
||||
{ label: 'Admin token', value: bootstrap.admin_token_set ? `${bootstrap.admin_token_hash_prefix}…` : 'Not set', mono: true },
|
||||
{ label: 'Sealing identity', value: bootstrap.sealing_identity_set ? 'Set' : 'Not set' },
|
||||
]"
|
||||
/>
|
||||
<div class="mt-4 flex flex-col gap-2">
|
||||
<div class="flex flex-wrap items-center gap-2">
|
||||
<Button variant="outline" size="sm" :disabled="saving" @click="rotate">Rotate admin token</Button>
|
||||
<p v-if="error" class="text-caption text-danger">{{ error }}</p>
|
||||
</div>
|
||||
<div v-if="issued" class="flex flex-col gap-2 sm:flex-row sm:items-center">
|
||||
<Input :model-value="issued" readonly class="font-mono" aria-label="New admin token" />
|
||||
<div class="flex items-center gap-2">
|
||||
<Button variant="outline" @click="copy">{{ copied ? "Copied" : "Copy" }}</Button>
|
||||
<Button variant="ghost" @click="issued = ''">Done</Button>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="issued" class="text-caption text-fg-subtle">Copy the token now. You won't be able to retrieve it later.</p>
|
||||
</div>
|
||||
</template>
|
||||
</Section>
|
||||
</template>
|
||||
@@ -1,234 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, reactive, ref } from "vue";
|
||||
|
||||
import PageHeader from "@/base/PageHeader.vue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { SettingRow } from "@/components/ui/setting-row";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { listSources, listTriggers, saveTrigger, Unauthorized, type SourceView, type TriggerView } from "./api";
|
||||
|
||||
/**
|
||||
* Disabling a trigger keeps its configuration but stops it from starting runs.
|
||||
*/
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
|
||||
interface Pair {
|
||||
key: string;
|
||||
value: string;
|
||||
}
|
||||
|
||||
interface Draft {
|
||||
name: string;
|
||||
source: string;
|
||||
eventType: string;
|
||||
workflow: string;
|
||||
every: string;
|
||||
enabled: boolean;
|
||||
filter: Pair[];
|
||||
}
|
||||
|
||||
const blank = (): Draft => ({ name: "", source: "", eventType: "", workflow: "", every: "", enabled: true, filter: [] });
|
||||
|
||||
const triggers = ref<TriggerView[]>([]);
|
||||
const sources = ref<SourceView[]>([]);
|
||||
const drafts = reactive<Record<string, Draft>>({});
|
||||
const adding = ref(false);
|
||||
const draft = ref<Draft>(blank());
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
const saved = ref("");
|
||||
const saving = ref(false);
|
||||
const controller = new AbortController();
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
const [found, heard] = await Promise.all([listTriggers(controller.signal), listSources(controller.signal)]);
|
||||
triggers.value = found;
|
||||
sources.value = heard;
|
||||
for (const t of found) {
|
||||
drafts[t.name] = {
|
||||
name: t.name,
|
||||
source: t.source,
|
||||
eventType: t.event_type,
|
||||
workflow: t.workflow,
|
||||
every: t.every ?? "",
|
||||
enabled: t.enabled,
|
||||
filter: Object.entries(t.filter).map(([key, value]) => ({ key, value })),
|
||||
};
|
||||
}
|
||||
if (!draft.value.source && heard.length) draft.value.source = heard[0].name;
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function filterOf(pairs: Pair[]): Record<string, string> {
|
||||
return Object.fromEntries(pairs.filter((p) => p.key.trim()).map((p) => [p.key.trim(), p.value]));
|
||||
}
|
||||
|
||||
function bodyOf(d: Draft) {
|
||||
return {
|
||||
source: d.source,
|
||||
event_type: d.eventType,
|
||||
workflow: d.workflow.trim(),
|
||||
filter: filterOf(d.filter),
|
||||
disabled: !d.enabled,
|
||||
every: d.every.trim() || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
async function add() {
|
||||
saving.value = true;
|
||||
error.value = "";
|
||||
saved.value = "";
|
||||
try {
|
||||
await saveTrigger(draft.value.name.trim(), bodyOf(draft.value));
|
||||
draft.value = blank();
|
||||
if (sources.value.length) draft.value.source = sources.value[0].name;
|
||||
adding.value = false;
|
||||
saved.value = "Saved.";
|
||||
await load();
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function save(t: TriggerView) {
|
||||
const d = drafts[t.name];
|
||||
if (!d) return;
|
||||
saving.value = true;
|
||||
error.value = "";
|
||||
saved.value = "";
|
||||
try {
|
||||
await saveTrigger(t.name, bodyOf(d));
|
||||
saved.value = "Saved.";
|
||||
await load();
|
||||
} catch (err) {
|
||||
fail(err);
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function toggle(t: TriggerView, on: boolean) {
|
||||
const d = drafts[t.name];
|
||||
if (!d) return;
|
||||
d.enabled = on;
|
||||
await save(t);
|
||||
}
|
||||
|
||||
function fail(err: unknown) {
|
||||
if (controller.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
}
|
||||
|
||||
onMounted(load);
|
||||
onBeforeUnmount(() => controller.abort());
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<PageHeader title="Triggers">
|
||||
<Button variant="outline" @click="adding = !adding">Add trigger</Button>
|
||||
</PageHeader>
|
||||
<Spinner v-if="loading" />
|
||||
<ReadError v-else-if="error && !triggers.length" :message="error" retry-label="Retry" @retry="load" />
|
||||
<template v-else>
|
||||
<Section v-if="adding" title="New trigger">
|
||||
<form class="flex flex-col gap-3" @submit.prevent="add">
|
||||
<SettingRow label="Name" for="trigger-name">
|
||||
<Input id="trigger-name" v-model="draft.name" placeholder="lowercase-name" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Source" for="trigger-source">
|
||||
<Select v-model="draft.source">
|
||||
<SelectTrigger id="trigger-source" class="w-full sm:w-64"><SelectValue placeholder="Choose a source" /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="s in sources" :key="s.name" :value="s.name">{{ s.name }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
<SettingRow label="Event type" for="trigger-event" hint="The event type the source's connector emits, such as alert.firing.">
|
||||
<Input id="trigger-event" v-model="draft.eventType" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Every" for="trigger-every" hint="Set an interval to run on a schedule. Archie sets the source, event type and filter for scheduled triggers.">
|
||||
<Input id="trigger-every" v-model="draft.every" placeholder="1h" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Workflow" for="trigger-workflow">
|
||||
<Input id="trigger-workflow" v-model="draft.workflow" placeholder="investigate" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Filter" hint="An event must match every field and value listed here.">
|
||||
<div class="flex flex-col gap-2">
|
||||
<div v-for="(pair, index) in draft.filter" :key="index" class="flex flex-wrap items-center gap-2">
|
||||
<Input v-model="pair.key" placeholder="field" class="w-40" aria-label="Filter field" />
|
||||
<Input v-model="pair.value" placeholder="value" class="w-40" aria-label="Filter value" />
|
||||
<Button variant="ghost" size="xs" @click="draft.filter.splice(index, 1)">Remove</Button>
|
||||
</div>
|
||||
<Button variant="outline" size="xs" class="self-start" @click="draft.filter.push({ key: '', value: '' })">Add filter</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
<p v-if="error" class="text-caption text-danger">{{ error }}</p>
|
||||
<div class="flex items-center gap-2">
|
||||
<Button type="submit" :disabled="saving || !draft.name.trim() || !draft.workflow.trim()">Save</Button>
|
||||
<Button type="button" variant="ghost" @click="adding = false">Cancel</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Section>
|
||||
|
||||
<Empty v-if="!triggers.length">
|
||||
<EmptyHeader><EmptyTitle>No triggers yet</EmptyTitle></EmptyHeader>
|
||||
</Empty>
|
||||
<Section v-for="t in triggers" :key="t.name" :title="t.name">
|
||||
<template #action>
|
||||
<Switch :model-value="drafts[t.name]?.enabled ?? t.enabled" :aria-label="`Enable ${t.name}`" @update:model-value="(on) => toggle(t, on)" />
|
||||
</template>
|
||||
<template v-if="drafts[t.name]">
|
||||
<SettingRow label="Source" :for="`${t.name}-source`">
|
||||
<Select v-model="drafts[t.name].source">
|
||||
<SelectTrigger :id="`${t.name}-source`" class="w-full sm:w-64"><SelectValue /></SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem v-for="s in sources" :key="s.name" :value="s.name">{{ s.name }}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</SettingRow>
|
||||
<SettingRow label="Event type" :for="`${t.name}-type`">
|
||||
<Input :id="`${t.name}-type`" v-model="drafts[t.name].eventType" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Every" :for="`${t.name}-every`" hint="Leave blank to match events, or set an interval to run on a schedule.">
|
||||
<Input :id="`${t.name}-every`" v-model="drafts[t.name].every" placeholder="1h" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Workflow" :for="`${t.name}-workflow`">
|
||||
<Input :id="`${t.name}-workflow`" v-model="drafts[t.name].workflow" />
|
||||
</SettingRow>
|
||||
<SettingRow label="Filter">
|
||||
<div class="flex flex-col gap-2">
|
||||
<div v-for="(pair, index) in drafts[t.name].filter" :key="index" class="flex flex-wrap items-center gap-2">
|
||||
<Input v-model="pair.key" placeholder="field" class="w-40" aria-label="Filter field" />
|
||||
<Input v-model="pair.value" placeholder="value" class="w-40" aria-label="Filter value" />
|
||||
<Button variant="ghost" size="xs" @click="drafts[t.name].filter.splice(index, 1)">Remove</Button>
|
||||
</div>
|
||||
<Button variant="outline" size="xs" class="self-start" @click="drafts[t.name].filter.push({ key: '', value: '' })">Add filter</Button>
|
||||
</div>
|
||||
</SettingRow>
|
||||
<div class="mt-2 flex items-center gap-3">
|
||||
<Button size="sm" :disabled="saving" @click="save(t)">Save</Button>
|
||||
<p v-if="error" class="text-caption text-danger">{{ error }}</p>
|
||||
</div>
|
||||
</template>
|
||||
</Section>
|
||||
<p v-if="saved" class="text-caption text-muted-foreground">{{ saved }}</p>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,234 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { useIntervalFn } from "@vueuse/core";
|
||||
import { computed, onBeforeUnmount, onMounted, reactive, ref } from "vue";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Empty, EmptyHeader, EmptyTitle } from "@/components/ui/empty";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import { Section } from "@/components/ui/section";
|
||||
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import {
|
||||
createDraft,
|
||||
dryRunDraft,
|
||||
listDrafts,
|
||||
listGroups,
|
||||
publishDraft,
|
||||
saveDraft,
|
||||
Unauthorized,
|
||||
type Draft,
|
||||
type DraftEdit,
|
||||
type DryAction,
|
||||
type EventGroup,
|
||||
} from "./api";
|
||||
import { levelLabel } from "./state";
|
||||
|
||||
const emit = defineEmits<{ unauthorized: [] }>();
|
||||
|
||||
const groups = ref<EventGroup[]>([]);
|
||||
const drafts = ref<Draft[]>([]);
|
||||
const loading = ref(true);
|
||||
const error = ref("");
|
||||
const busy = ref<string | null>(null);
|
||||
const errors = reactive<Record<string, string>>({});
|
||||
const editing = reactive<Record<string, DraftEdit | undefined>>({});
|
||||
const controller = new AbortController();
|
||||
|
||||
const draftOf = (g: EventGroup) => drafts.value.find((d) => d.group_id === g.id);
|
||||
const settling = computed(() => drafts.value.some((d) => d.dry_run && ["queued", "running", "waiting"].includes(d.dry_run.state)));
|
||||
|
||||
async function load() {
|
||||
loading.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
await refresh();
|
||||
} catch (err) {
|
||||
fail(err, (message) => (error.value = message));
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function refresh() {
|
||||
[groups.value, drafts.value] = await Promise.all([listGroups(controller.signal), listDrafts(controller.signal)]);
|
||||
}
|
||||
|
||||
const poll = useIntervalFn(
|
||||
async () => {
|
||||
if (!settling.value) return;
|
||||
try {
|
||||
drafts.value = await listDrafts(controller.signal);
|
||||
} catch (err) {
|
||||
fail(err, (message) => (error.value = message));
|
||||
}
|
||||
},
|
||||
2000,
|
||||
{ immediate: false },
|
||||
);
|
||||
|
||||
function replace(d: Draft) {
|
||||
drafts.value = [d, ...drafts.value.filter((x) => x.id !== d.id)];
|
||||
}
|
||||
|
||||
async function act(g: EventGroup, run: () => Promise<void>) {
|
||||
busy.value = g.id;
|
||||
errors[g.id] = "";
|
||||
try {
|
||||
await run();
|
||||
} catch (err) {
|
||||
fail(err, (message) => (errors[g.id] = message));
|
||||
} finally {
|
||||
busy.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
const draft = (g: EventGroup) => act(g, async () => replace(await createDraft(g.id)));
|
||||
const dryRun = (g: EventGroup, d: Draft) => act(g, async () => replace(await dryRunDraft(d.id)));
|
||||
const publish = (g: EventGroup, d: Draft) =>
|
||||
act(g, async () => {
|
||||
await publishDraft(d.id);
|
||||
await refresh();
|
||||
});
|
||||
|
||||
function edit(d: Draft) {
|
||||
editing[d.group_id] = { name: d.name, workflow: d.workflow, policy_kind: d.policy_kind, policy: d.policy };
|
||||
}
|
||||
|
||||
const save = (g: EventGroup, d: Draft) =>
|
||||
act(g, async () => {
|
||||
const e = editing[g.id];
|
||||
if (!e) return;
|
||||
replace(await saveDraft(d.id, e));
|
||||
editing[g.id] = undefined;
|
||||
});
|
||||
|
||||
function fail(err: unknown, set: (message: string) => void) {
|
||||
if (controller.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) emit("unauthorized");
|
||||
set(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
|
||||
const filterText = (filter: Record<string, string>) =>
|
||||
Object.entries(filter)
|
||||
.map(([k, v]) => `${k}=${v}`)
|
||||
.join(" ");
|
||||
|
||||
const outcomeLabel = (a: DryAction) =>
|
||||
({ ran: "Read-only action ran", would_run: "Would run", would_ask: "Would request approval", refused: "Refused" })[a.outcome];
|
||||
const outcomeTone = (a: DryAction) =>
|
||||
({ ran: "ok", would_run: "info", would_ask: "warn", refused: "danger" })[a.outcome] as "ok" | "info" | "warn" | "danger";
|
||||
const policyKinds = [
|
||||
{ value: "hard_rules", label: "Hard rules" },
|
||||
{ value: "change_request", label: "Change-request rules" },
|
||||
] as const;
|
||||
|
||||
onMounted(() => {
|
||||
void load();
|
||||
poll.resume();
|
||||
});
|
||||
onBeforeUnmount(() => {
|
||||
poll.pause();
|
||||
controller.abort();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<Spinner v-if="loading" />
|
||||
<ReadError v-else-if="error" :message="error" retry-label="Retry" @retry="load" />
|
||||
<Empty v-else-if="groups.length === 0">
|
||||
<EmptyHeader><EmptyTitle>No unmatched events</EmptyTitle></EmptyHeader>
|
||||
</Empty>
|
||||
<template v-else>
|
||||
<Section
|
||||
v-for="g in groups"
|
||||
:key="g.id"
|
||||
:title="`${g.proposed.source} ${g.proposed.event_type}`"
|
||||
:description="filterText(g.proposed.filter)"
|
||||
>
|
||||
<template #action>
|
||||
<span class="text-caption text-muted-foreground">
|
||||
{{ g.count }} events, last <Timestamp :at="g.last_seen" />
|
||||
</span>
|
||||
</template>
|
||||
<p v-if="errors[g.id]" class="mb-2 text-caption text-danger">{{ errors[g.id] }}</p>
|
||||
<Button v-if="!draftOf(g)" size="xs" :disabled="busy === g.id" @click="draft(g)">Draft</Button>
|
||||
<template v-else-if="draftOf(g)">
|
||||
<template v-for="d in [draftOf(g)!]" :key="d.id">
|
||||
<p class="text-label">{{ d.summary }}</p>
|
||||
|
||||
<form v-if="editing[g.id]" class="mt-3 flex flex-col gap-2" @submit.prevent="save(g, d)">
|
||||
<Input v-model="editing[g.id]!.name" aria-label="Name" />
|
||||
<Textarea v-model="editing[g.id]!.workflow" aria-label="Workflow" class="min-h-40 font-mono" />
|
||||
<Select v-model="editing[g.id]!.policy_kind">
|
||||
<SelectTrigger aria-label="Policy kind" class="max-w-56">
|
||||
<SelectValue>{{ policyKinds.find((k) => k.value === editing[g.id]!.policy_kind)?.label }}</SelectValue>
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectItem v-for="k in policyKinds" :key="k.value" :value="k.value">{{ k.label }}</SelectItem>
|
||||
</SelectGroup>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<Textarea v-model="editing[g.id]!.policy" aria-label="Policy" class="min-h-24 font-mono" />
|
||||
<div class="flex gap-2">
|
||||
<Button type="submit" size="xs" :disabled="busy === g.id">Save</Button>
|
||||
<Button type="button" size="xs" variant="ghost" @click="editing[g.id] = undefined">Cancel</Button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div v-if="d.dry_run" class="mt-3">
|
||||
<div class="mb-1 flex items-center gap-2 text-caption text-muted-foreground">
|
||||
Dry run
|
||||
<Badge :variant="d.dry_run.state === 'failed' ? 'danger' : 'secondary'">{{ d.dry_run.state }}</Badge>
|
||||
<Timestamp :at="d.dry_run.at" />
|
||||
</div>
|
||||
<p v-if="d.dry_run.error" class="text-caption text-danger">{{ d.dry_run.error }}</p>
|
||||
<p v-if="d.dry_run.findings" class="mb-2 whitespace-pre-wrap text-label">{{ d.dry_run.findings }}</p>
|
||||
<Table v-if="d.dry_run.actions.length">
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>Action</TableHead>
|
||||
<TableHead>Judgement</TableHead>
|
||||
<TableHead>Result</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
<TableRow v-for="(a, i) in d.dry_run.actions" :key="i">
|
||||
<TableCell>
|
||||
<div>{{ a.action }}</div>
|
||||
<div class="text-caption text-muted-foreground">{{ a.target }}</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<div>{{ levelLabel(a.level) }}</div>
|
||||
<div v-if="a.why" class="text-caption text-muted-foreground">{{ a.why }}</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge :variant="outcomeTone(a)">{{ outcomeLabel(a) }}</Badge>
|
||||
<div v-if="a.ask?.length" class="text-caption text-muted-foreground">{{ a.ask.join(", then ") }}</div>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
</TableBody>
|
||||
</Table>
|
||||
<p v-else-if="d.dry_run.state === 'succeeded'" class="text-caption text-muted-foreground">No actions proposed.</p>
|
||||
<p v-if="d.dry_run.notice" class="mt-2 whitespace-pre-wrap text-caption text-muted-foreground">
|
||||
Would send: {{ d.dry_run.notice.title }}. {{ d.dry_run.notice.body }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="mt-3 flex gap-2">
|
||||
<Button size="xs" variant="outline" :disabled="busy === g.id" @click="dryRun(g, d)">Dry run</Button>
|
||||
<Button size="xs" variant="ghost" :disabled="!!editing[g.id]" @click="edit(d)">Edit</Button>
|
||||
<Button size="xs" :disabled="busy === g.id" @click="publish(g, d)">Publish</Button>
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
</Section>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,807 +0,0 @@
|
||||
// The dashboard keeps the bootstrap admin token in browser session storage.
|
||||
const TOKEN_KEY = "archie.adminToken";
|
||||
export const invalidTokenMessage = "Admin token contains unsupported characters. Paste the token again.";
|
||||
|
||||
export class Unauthorized extends Error {}
|
||||
|
||||
export class InvalidAdminToken extends Error {
|
||||
constructor() {
|
||||
super(invalidTokenMessage);
|
||||
}
|
||||
}
|
||||
|
||||
export const isValidToken = (value: string) => value.length > 0 && /^[\x20-\x7E]+$/.test(value);
|
||||
|
||||
/** A failed HTTP request with its response status. */
|
||||
export class ApiError extends Error {
|
||||
readonly status: number;
|
||||
|
||||
constructor(message: string, status: number) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
export const token = (): string => sessionStorage.getItem(TOKEN_KEY) ?? "";
|
||||
export const setToken = (value: string) => {
|
||||
if (!isValidToken(value)) return false;
|
||||
sessionStorage.setItem(TOKEN_KEY, value);
|
||||
return true;
|
||||
};
|
||||
export const clearToken = () => sessionStorage.removeItem(TOKEN_KEY);
|
||||
|
||||
function authorization(): string {
|
||||
const value = token();
|
||||
if (!isValidToken(value)) {
|
||||
clearToken();
|
||||
throw new InvalidAdminToken();
|
||||
}
|
||||
return `Bearer ${value}`;
|
||||
}
|
||||
|
||||
async function request(path: string, signal?: AbortSignal): Promise<Response> {
|
||||
const res = await fetch(path, { headers: { Authorization: authorization() }, signal });
|
||||
if (res.status === 401) throw new Unauthorized("Sign in with a valid admin token.");
|
||||
if (!res.ok) {
|
||||
const body = (await res.json().catch(() => ({}))) as { error?: string; detail?: string };
|
||||
throw new ApiError(body.detail ?? body.error ?? `${res.status} ${res.statusText}`, res.status);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
async function get<T>(path: string, signal?: AbortSignal): Promise<T> {
|
||||
return (await request(path, signal)).json() as Promise<T>;
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
seq: number;
|
||||
id: string;
|
||||
kind: "notification" | "approval_request" | "approval_answer";
|
||||
run_id?: string;
|
||||
request_id?: string;
|
||||
title: string;
|
||||
body: string;
|
||||
expires_at?: string;
|
||||
created_at: string;
|
||||
/** Delivery attempts of the connector rows carrying this message, one per channel. */
|
||||
attempts?: MessageAttempt[];
|
||||
}
|
||||
|
||||
export interface MessageAttempt {
|
||||
channel: string;
|
||||
attempt: number;
|
||||
at: string;
|
||||
ok: boolean;
|
||||
response?: string;
|
||||
error?: string;
|
||||
duration_ms: number;
|
||||
}
|
||||
|
||||
export interface Usage {
|
||||
prompt_tokens: number;
|
||||
completion_tokens: number;
|
||||
total_tokens: number;
|
||||
cached_tokens?: number;
|
||||
}
|
||||
|
||||
export interface Run {
|
||||
id: string;
|
||||
workflow: string;
|
||||
workflow_version: number;
|
||||
state: "queued" | "running" | "waiting" | "succeeded" | "failed" | "cancelled";
|
||||
attempts: number;
|
||||
error?: string;
|
||||
created_at: string;
|
||||
finished_at?: string;
|
||||
result?: { answer?: string; stop_reason?: string; usage?: Usage; steps?: number; tool_calls?: number };
|
||||
}
|
||||
|
||||
export interface Origin {
|
||||
event_id: string;
|
||||
source: string;
|
||||
type: string;
|
||||
fields: Record<string, unknown>;
|
||||
received_at: string;
|
||||
trigger: string;
|
||||
filter: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface TrailEntry {
|
||||
seq: number;
|
||||
at: string;
|
||||
kind: "model" | "compaction" | "tool" | "step";
|
||||
name?: string;
|
||||
text?: string;
|
||||
reasoning?: string;
|
||||
tool_calls?: { name: string; input: string }[];
|
||||
usage?: Usage;
|
||||
/** The model request exactly as it was sent: messages, tools offered and sampling settings. */
|
||||
request?: unknown;
|
||||
finish_reason?: string;
|
||||
input?: string;
|
||||
output?: string;
|
||||
value?: unknown;
|
||||
error?: string;
|
||||
unknown?: boolean;
|
||||
}
|
||||
|
||||
export interface JudgeRecord {
|
||||
model?: string;
|
||||
result_id?: string;
|
||||
answer?: string;
|
||||
confidence?: number;
|
||||
reason?: string;
|
||||
basis?: string;
|
||||
basis_digest?: string;
|
||||
answers?: unknown;
|
||||
trusted?: boolean;
|
||||
advisory_reason?: string;
|
||||
eval_date?: string;
|
||||
request?: unknown;
|
||||
response?: unknown;
|
||||
endpoint_path?: string;
|
||||
http_status?: number;
|
||||
latency_ms?: number;
|
||||
}
|
||||
|
||||
export interface Verdict {
|
||||
guard: string;
|
||||
ceiling: string;
|
||||
findings?: { text: string; evidence?: string }[];
|
||||
blind_spots?: string[];
|
||||
judges?: JudgeRecord[];
|
||||
advisory?: boolean;
|
||||
failed?: string;
|
||||
}
|
||||
|
||||
export interface ConnectorCall {
|
||||
connector: string;
|
||||
method: string;
|
||||
request: unknown;
|
||||
response?: unknown;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface Decision {
|
||||
id: string;
|
||||
key: string;
|
||||
action: {
|
||||
connector: string;
|
||||
name: string;
|
||||
input: unknown;
|
||||
digest: string;
|
||||
target: { Kind: string; ID: string; Environment: string };
|
||||
effect: { Summary: string };
|
||||
};
|
||||
level: string;
|
||||
verdicts: Verdict[];
|
||||
refused_by?: string;
|
||||
change_request?: boolean;
|
||||
change_request_rule?: string;
|
||||
reason?: string;
|
||||
at: string;
|
||||
/** The connector calls behind the decision: resolve, target facts and invoke. */
|
||||
calls?: ConnectorCall[];
|
||||
}
|
||||
|
||||
export interface ApprovalRequest {
|
||||
id: string;
|
||||
summary: string;
|
||||
state: "pending" | "approved" | "denied" | "expired";
|
||||
deadline: string;
|
||||
requested_at: string;
|
||||
answered_by?: string;
|
||||
answered_via?: string;
|
||||
answered_at?: string;
|
||||
}
|
||||
|
||||
export interface Effect {
|
||||
state: "ran" | "failed" | "unknown";
|
||||
at: string;
|
||||
output?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface ActionTrail {
|
||||
decision: Decision;
|
||||
rejudged?: Decision;
|
||||
approval?: ApprovalRequest;
|
||||
effect?: Effect;
|
||||
}
|
||||
|
||||
export interface Trail {
|
||||
run: Run;
|
||||
origin?: Origin;
|
||||
actions: ActionTrail[];
|
||||
entries: TrailEntry[];
|
||||
}
|
||||
|
||||
export interface Settings {
|
||||
/** A Go duration, such as "24h". */
|
||||
approval_deadline: string;
|
||||
/** Approvals in a row, since a class was last tightened, that earn a proposal to raise it. */
|
||||
raise_after: number;
|
||||
/** Holds every action that changes something at propose and wait. */
|
||||
frozen: boolean;
|
||||
recurrence_threshold: number;
|
||||
/** Steps an agent may take in one run. */
|
||||
attempts_per_run: number;
|
||||
/** Person id, or empty. */
|
||||
default_owner: string;
|
||||
/** The people an unanswered request moves through, in order, each with how long it waits on them. */
|
||||
escalation: EscalationStep[];
|
||||
/** When actions that change something may run without asking. */
|
||||
timing: Timing;
|
||||
/** Changing actions one run may take before the next waits for approval. */
|
||||
actions_per_run: number;
|
||||
/** Changing actions the organisation may take in a day before the next waits. */
|
||||
actions_per_day: number;
|
||||
}
|
||||
|
||||
export interface Timing {
|
||||
/** An IANA zone such as "Australia/Sydney"; empty is UTC. */
|
||||
zone: string;
|
||||
/** "09:00"; empty start and end mean every hour. */
|
||||
start: string;
|
||||
end: string;
|
||||
/** "mon" to "sun"; empty means every day. */
|
||||
days: string[];
|
||||
blackouts: Blackout[];
|
||||
}
|
||||
|
||||
export interface Blackout {
|
||||
/** RFC 3339 instants. */
|
||||
from: string;
|
||||
to: string;
|
||||
reason: string;
|
||||
}
|
||||
|
||||
export interface EscalationStep {
|
||||
/** Person id. */
|
||||
person: string;
|
||||
/** A Go duration, such as "4h". */
|
||||
deadline: string;
|
||||
}
|
||||
|
||||
export const getSettings = (signal?: AbortSignal) => get<Settings>("/api/settings", signal);
|
||||
|
||||
export interface Person {
|
||||
/** Empty for a person not saved yet. */
|
||||
id: string;
|
||||
name: string;
|
||||
/** May approve changes to policy and ceilings. */
|
||||
authority: boolean;
|
||||
/** Channel accounts that are theirs, such as telegram:1001. */
|
||||
identities: string[];
|
||||
}
|
||||
|
||||
export const getPeople = (signal?: AbortSignal) => get<Person[]>("/api/people", signal);
|
||||
|
||||
export const saveSettings = (next: Settings) => put("/api/settings", next);
|
||||
|
||||
export const savePeople = (next: Person[]) => put("/api/people", next);
|
||||
|
||||
async function put(path: string, payload: unknown): Promise<void> {
|
||||
await putJSON(path, payload);
|
||||
}
|
||||
|
||||
async function putJSON<T>(path: string, payload: unknown): Promise<T> {
|
||||
return send<T>("PUT", path, payload);
|
||||
}
|
||||
|
||||
async function send<T>(method: string, path: string, payload?: unknown): Promise<T> {
|
||||
const res = await fetch(path, {
|
||||
method,
|
||||
headers: { Authorization: authorization(), "Content-Type": "application/json" },
|
||||
body: payload === undefined ? undefined : JSON.stringify(payload),
|
||||
});
|
||||
if (res.status === 401) throw new Unauthorized("Sign in with a valid admin token.");
|
||||
if (!res.ok) {
|
||||
const body = (await res.json().catch(() => ({}))) as { error?: string; detail?: string };
|
||||
throw new ApiError(body.detail ?? body.error ?? `${res.status} ${res.statusText}`, res.status);
|
||||
}
|
||||
return (await res.json().catch(() => undefined)) as T;
|
||||
}
|
||||
|
||||
export interface PolicySet {
|
||||
version: number;
|
||||
body: string;
|
||||
created_by: string;
|
||||
created_at: string;
|
||||
versions: { version: number; created_by: string; created_at: string }[];
|
||||
}
|
||||
|
||||
export type PolicyKind = "hard-rules" | "change-request";
|
||||
|
||||
export const getPolicies = (kind: PolicyKind, signal?: AbortSignal) => get<PolicySet>(`/api/policies/${kind}`, signal);
|
||||
|
||||
export const savePolicies = (kind: PolicyKind, body: string) => putJSON<PolicySet>(`/api/policies/${kind}`, { body });
|
||||
|
||||
export const latestMessages = (signal?: AbortSignal) => get<Message[]>("/api/composer/messages", signal);
|
||||
export const messagesAfter = (seq: number, signal?: AbortSignal) =>
|
||||
get<Message[]>(`/api/composer/messages?after=${seq}`, signal);
|
||||
|
||||
export interface PendingApproval {
|
||||
id: string;
|
||||
run_id: string;
|
||||
action: string;
|
||||
summary: string;
|
||||
deadline: string;
|
||||
step_deadline?: string;
|
||||
}
|
||||
|
||||
export const pendingApprovals = (signal?: AbortSignal) => get<PendingApproval[]>("/api/approvals", signal);
|
||||
|
||||
/** Answers an approval request the composer is showing. */
|
||||
export async function answerApproval(id: string, approved: boolean): Promise<void> {
|
||||
const res = await fetch(`/api/approvals/${encodeURIComponent(id)}/answer`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: authorization(), "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ approved }),
|
||||
});
|
||||
if (res.status === 401) throw new Unauthorized("Sign in with a valid admin token.");
|
||||
if (!res.ok) {
|
||||
const body = (await res.json().catch(() => ({}))) as { error?: string; detail?: string };
|
||||
throw new Error(body.detail ?? body.error ?? `${res.status} ${res.statusText}`);
|
||||
}
|
||||
}
|
||||
export type Level = "act_quietly" | "act_and_tell" | "propose_and_wait" | "escalate" | "never";
|
||||
|
||||
export interface ActionClass {
|
||||
id: string;
|
||||
connector: string;
|
||||
action: string;
|
||||
target_kind: string;
|
||||
environment: string;
|
||||
level: Level;
|
||||
default: Level;
|
||||
decisions: number;
|
||||
last_decided_at?: string;
|
||||
reset_at?: string;
|
||||
/** Approvals in a row since the class was last tightened or raised. */
|
||||
count: number;
|
||||
tightened_at?: string;
|
||||
tightened_because?: "denied" | "failed";
|
||||
}
|
||||
|
||||
export interface HistoryEntry {
|
||||
decision_id: string;
|
||||
run_id: string;
|
||||
target: string;
|
||||
level: Level;
|
||||
refused_by?: string;
|
||||
approval?: "pending" | "approved" | "denied" | "expired";
|
||||
answered_by?: string;
|
||||
at: string;
|
||||
}
|
||||
|
||||
export interface Raise {
|
||||
id: string;
|
||||
from: Level;
|
||||
to: Level;
|
||||
state: "pending" | "approved" | "denied" | "expired" | "superseded";
|
||||
deadline: string;
|
||||
proposed_at: string;
|
||||
answered_by?: string;
|
||||
answered_at?: string;
|
||||
evidence: { decision_id: string; by: string; at: string }[];
|
||||
}
|
||||
|
||||
export interface ClassDetail extends ActionClass {
|
||||
raises: Raise[];
|
||||
history: HistoryEntry[];
|
||||
resets: { from: Level; to: Level; by: string; at: string }[];
|
||||
}
|
||||
|
||||
export const listClasses = (signal?: AbortSignal) => get<ActionClass[]>("/api/classes", signal);
|
||||
export const classDetail = (id: string, signal?: AbortSignal) =>
|
||||
get<ClassDetail>(`/api/classes/${encodeURIComponent(id)}`, signal);
|
||||
|
||||
/** Returns an action class to its default level; its history stays. */
|
||||
export async function resetClass(id: string): Promise<void> {
|
||||
const res = await fetch(`/api/classes/${encodeURIComponent(id)}/reset`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: authorization() },
|
||||
});
|
||||
if (res.status === 401) throw new Unauthorized("Sign in with a valid admin token.");
|
||||
if (!res.ok) {
|
||||
const body = (await res.json().catch(() => ({}))) as { error?: string; detail?: string };
|
||||
throw new Error(body.detail ?? body.error ?? `${res.status} ${res.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Unmatched events that share a source, type and key fields, with the trigger they propose. */
|
||||
export interface EventGroup {
|
||||
id: string;
|
||||
count: number;
|
||||
first_seen: string;
|
||||
last_seen: string;
|
||||
proposed: { source: string; event_type: string; filter: Record<string, string>; workflow: string };
|
||||
}
|
||||
|
||||
export const listGroups = (signal?: AbortSignal) => get<EventGroup[]>("/api/groups", signal);
|
||||
|
||||
/** A dry-run decision and its outcome. Only read-only actions can run. */
|
||||
export interface DryAction {
|
||||
action: string;
|
||||
target: string;
|
||||
summary?: string;
|
||||
level: Level;
|
||||
outcome: "ran" | "would_run" | "would_ask" | "refused";
|
||||
why?: string;
|
||||
ask?: string[];
|
||||
}
|
||||
|
||||
export interface DryReport {
|
||||
run_id: string;
|
||||
state: Run["state"];
|
||||
error?: string;
|
||||
findings?: string;
|
||||
actions: DryAction[];
|
||||
notice?: { title: string; body: string };
|
||||
at: string;
|
||||
}
|
||||
|
||||
/** A proposed trigger, workflow and policy, with the latest dry-run report. */
|
||||
export interface Draft {
|
||||
id: string;
|
||||
group_id: string;
|
||||
name: string;
|
||||
trigger: { source: string; event_type: string; filter: Record<string, string> };
|
||||
workflow: string;
|
||||
policy_kind: "hard_rules" | "change_request";
|
||||
policy: string;
|
||||
summary: string;
|
||||
dry_run?: DryReport;
|
||||
dry_event_id?: string;
|
||||
published_at?: string;
|
||||
}
|
||||
|
||||
export interface DraftEdit {
|
||||
name: string;
|
||||
workflow: string;
|
||||
policy_kind: Draft["policy_kind"];
|
||||
policy: string;
|
||||
}
|
||||
|
||||
export const listDrafts = (signal?: AbortSignal) => get<Draft[]>("/api/drafts", signal);
|
||||
export const createDraft = (groupId: string) => send<Draft>("POST", `/api/groups/${encodeURIComponent(groupId)}/draft`);
|
||||
export const saveDraft = (id: string, edit: DraftEdit) => send<Draft>("PUT", `/api/drafts/${encodeURIComponent(id)}`, edit);
|
||||
export const dryRunDraft = (id: string) => send<Draft>("POST", `/api/drafts/${encodeURIComponent(id)}/dry-run`);
|
||||
export const publishDraft = (id: string) => send<Draft>("POST", `/api/drafts/${encodeURIComponent(id)}/publish`);
|
||||
|
||||
export const listRuns =(signal?: AbortSignal) => get<Run[]>("/api/runs", signal);
|
||||
|
||||
/** A setting an extension declares. Its type decides the control the form shows. */
|
||||
export interface SettingDecl {
|
||||
key: string;
|
||||
label: string;
|
||||
description?: string;
|
||||
secret?: boolean;
|
||||
required?: boolean;
|
||||
type?: "string" | "number" | "boolean" | "duration" | "list" | "select" | "text";
|
||||
options?: string[];
|
||||
}
|
||||
|
||||
export type ExtensionContract = "connector" | "secretengine" | "guard" | "mcp";
|
||||
|
||||
const extensionPath: Record<ExtensionContract, string> = {
|
||||
connector: "connectors",
|
||||
secretengine: "secret-engines",
|
||||
guard: "guards",
|
||||
mcp: "mcp-servers",
|
||||
};
|
||||
|
||||
/** An accepted extension's metadata, runtime status and configuration. */
|
||||
export interface Extension {
|
||||
name: string;
|
||||
contract: ExtensionContract;
|
||||
state: "running" | "failed" | "stopped";
|
||||
error?: string;
|
||||
version?: string;
|
||||
digest: string;
|
||||
path?: string;
|
||||
url?: string;
|
||||
args?: string[];
|
||||
egress: string[];
|
||||
env: string[];
|
||||
settings: Record<string, string>;
|
||||
settings_schema: SettingDecl[];
|
||||
credentials: Record<string, string>;
|
||||
tools?: unknown;
|
||||
}
|
||||
|
||||
/** What a credential field is: a stored value, or the engine and key resolving it. */
|
||||
export interface CredentialField {
|
||||
value?: string;
|
||||
engine?: string;
|
||||
key?: string;
|
||||
}
|
||||
|
||||
export interface CredentialView {
|
||||
name: string;
|
||||
kind: "machine" | "age" | "basic" | "bearer";
|
||||
fields: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface AgentModel {
|
||||
class: string;
|
||||
base_url: string;
|
||||
model: string;
|
||||
/** The credential holding the token; the token itself is never returned. */
|
||||
api_key_credential?: string;
|
||||
}
|
||||
|
||||
export interface BootstrapView {
|
||||
listen: string;
|
||||
database_host: string;
|
||||
schemas: number;
|
||||
admin_token_hash_prefix: string;
|
||||
admin_token_set: boolean;
|
||||
sealing_identity_set: boolean;
|
||||
}
|
||||
|
||||
export interface SourceView {
|
||||
name: string;
|
||||
connector: string;
|
||||
key_fields: string[];
|
||||
token_set: boolean;
|
||||
}
|
||||
|
||||
export interface TriggerView {
|
||||
name: string;
|
||||
source: string;
|
||||
event_type: string;
|
||||
filter: Record<string, string>;
|
||||
workflow: string;
|
||||
enabled: boolean;
|
||||
every?: string;
|
||||
}
|
||||
|
||||
export interface EventRow {
|
||||
id: string;
|
||||
source: string;
|
||||
type: string;
|
||||
fields: unknown;
|
||||
linked_to?: string;
|
||||
occurred_at?: string;
|
||||
received_at: string;
|
||||
matched: boolean;
|
||||
dispatched_at?: string;
|
||||
}
|
||||
|
||||
export interface EventDetail extends EventRow {
|
||||
body: unknown;
|
||||
runs: { trigger: string; run_id: string }[];
|
||||
}
|
||||
|
||||
export interface JudgeControl {
|
||||
name: string;
|
||||
version?: string;
|
||||
digest?: string;
|
||||
advisory: boolean;
|
||||
settings: Record<string, string>;
|
||||
settings_schema: SettingDecl[];
|
||||
latest?: {
|
||||
model?: string;
|
||||
trusted: boolean;
|
||||
advisory_reason?: string;
|
||||
eval_date?: string;
|
||||
answer?: string;
|
||||
at: string;
|
||||
};
|
||||
}
|
||||
|
||||
export const listExtensions = (contract: ExtensionContract, signal?: AbortSignal) =>
|
||||
get<Extension[]>(`/api/${extensionPath[contract]}`, signal);
|
||||
|
||||
export interface AcceptRequest {
|
||||
path?: string;
|
||||
sha256?: string;
|
||||
url?: string;
|
||||
args?: string[];
|
||||
egress?: string[];
|
||||
env?: string[];
|
||||
settings?: Record<string, string>;
|
||||
credentials?: Record<string, string>;
|
||||
tools?: unknown[];
|
||||
}
|
||||
|
||||
export const acceptExtension = (contract: ExtensionContract, name: string, body: AcceptRequest) =>
|
||||
send<{ name: string; state: string }>("PUT", `/api/${extensionPath[contract]}/${encodeURIComponent(name)}`, body);
|
||||
|
||||
export const removeExtension = (contract: ExtensionContract, name: string) =>
|
||||
send<{ name: string; state: string }>("DELETE", `/api/${extensionPath[contract]}/${encodeURIComponent(name)}`);
|
||||
|
||||
export const listCredentials = (signal?: AbortSignal) => get<CredentialView[]>("/api/credentials", signal);
|
||||
export const getCredential = (name: string, signal?: AbortSignal) =>
|
||||
get<CredentialView>(`/api/credentials/${encodeURIComponent(name)}`, signal);
|
||||
export const saveCredential = (name: string, kind: CredentialView["kind"], fields: Record<string, CredentialField>) =>
|
||||
send<{ name: string; kind: string; restarted: string[] }>("PUT", `/api/credentials/${encodeURIComponent(name)}`, { kind, fields });
|
||||
|
||||
export const listAgentModels = (signal?: AbortSignal) =>
|
||||
get<Record<string, AgentModel>>("/api/settings/agent-models", signal);
|
||||
export const saveAgentModel = (alias: string, model: AgentModel) =>
|
||||
send<AgentModel>("PUT", `/api/settings/agent-model?${new URLSearchParams({ alias })}`, model);
|
||||
export const testAgentModel = (model: AgentModel) =>
|
||||
send<{ model: string; answer: string }>("POST", "/api/settings/agent-model/test", model);
|
||||
|
||||
export const getBootstrap = (signal?: AbortSignal) => get<BootstrapView>("/api/system/bootstrap", signal);
|
||||
export const rotateAdminToken = () => send<{ token: string }>("POST", "/api/admin/token");
|
||||
|
||||
export const listSources = (signal?: AbortSignal) => get<SourceView[]>("/api/sources", signal);
|
||||
export const putSource = (name: string, connector: string) =>
|
||||
send<{ source: string; token: string; url: string }>("PUT", `/api/sources/${encodeURIComponent(name)}`, { connector });
|
||||
export const putKeyFields = (name: string, paths: string[]) =>
|
||||
send<{ key_fields: string[] }>("PUT", `/api/sources/${encodeURIComponent(name)}/key-fields`, { paths });
|
||||
|
||||
export const listTriggers = (signal?: AbortSignal) => get<TriggerView[]>("/api/triggers", signal);
|
||||
export const saveTrigger = (
|
||||
name: string,
|
||||
trigger: { source: string; event_type: string; filter: Record<string, string>; workflow: string; disabled: boolean; every?: string },
|
||||
) => send<{ trigger: string }>("PUT", `/api/triggers/${encodeURIComponent(name)}`, trigger);
|
||||
|
||||
export async function listEvents(
|
||||
params: { source?: string; type?: string; matched?: boolean; limit?: number },
|
||||
signal?: AbortSignal,
|
||||
): Promise<EventRow[]> {
|
||||
const query = new URLSearchParams();
|
||||
if (params.source) query.set("source", params.source);
|
||||
if (params.type) query.set("type", params.type);
|
||||
if (params.matched !== undefined) query.set("matched", String(params.matched));
|
||||
if (params.limit) query.set("limit", String(params.limit));
|
||||
return get<EventRow[]>(`/api/events?${query.toString()}`, signal);
|
||||
}
|
||||
|
||||
export const getEvent = (id: string, signal?: AbortSignal) =>
|
||||
get<EventDetail>(`/api/events/${encodeURIComponent(id)}`, signal);
|
||||
|
||||
export const listJudges = (signal?: AbortSignal) => get<JudgeControl[]>("/api/controls/judges", signal);
|
||||
export const runTrail = (id: string, signal?: AbortSignal) => get<Trail>(`/api/runs/${encodeURIComponent(id)}`, signal);
|
||||
|
||||
/**
|
||||
* Yields sequence numbers for new messages. Subscribe before fetching missed
|
||||
* messages so updates published during catch-up are queued. If the server
|
||||
* disconnects a slow subscriber, the caller reconnects from its last sequence.
|
||||
*/
|
||||
export async function* composerStream(signal: AbortSignal, onConnected?: () => Promise<void>): AsyncGenerator<number> {
|
||||
const res = await request("/api/composer/stream", signal);
|
||||
if (!res.body) return;
|
||||
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
|
||||
let buffered = "";
|
||||
try {
|
||||
await onConnected?.();
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) return;
|
||||
buffered += value;
|
||||
let end: number;
|
||||
while ((end = buffered.indexOf("\n\n")) >= 0) {
|
||||
const frame = buffered.slice(0, end);
|
||||
buffered = buffered.slice(end + 2);
|
||||
const data = frame.split("\n").find((line) => line.startsWith("data: "));
|
||||
if (data) yield (JSON.parse(data.slice(6)) as { seq: number }).seq;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
void reader.cancel().catch(() => undefined);
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
|
||||
/** One conversation, as GET /api/chat/sessions lists it. */
|
||||
export interface ChatSession {
|
||||
session_id: string;
|
||||
title: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
export interface ChatSessions {
|
||||
sessions: ChatSession[];
|
||||
active_model: string;
|
||||
model_error?: string;
|
||||
}
|
||||
|
||||
/** A tool the agent called and what came of it. */
|
||||
export interface ChatToolCall {
|
||||
id: string;
|
||||
name: string;
|
||||
parameters: string;
|
||||
text: string;
|
||||
failed?: boolean;
|
||||
duration_ms: number;
|
||||
text_offset: number;
|
||||
}
|
||||
|
||||
/** An action judgement held and put to people. */
|
||||
export interface ChatApproval {
|
||||
request_id: string;
|
||||
action: string;
|
||||
summary: string;
|
||||
level: string;
|
||||
deadline: string;
|
||||
}
|
||||
|
||||
/** What became of a held action once its approval was answered. */
|
||||
export interface ChatActionDone {
|
||||
request_id: string;
|
||||
state: "succeeded" | "failed" | "unknown" | "denied" | "expired";
|
||||
result?: string;
|
||||
}
|
||||
|
||||
export interface ChatNavigation {
|
||||
path: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
/** One message and Archie's reply, with what the turn did. */
|
||||
export interface ChatTurn {
|
||||
id: string;
|
||||
session_id: string;
|
||||
seq: number;
|
||||
state: "queued" | "running" | "succeeded" | "failed" | "cancelled";
|
||||
text: string;
|
||||
page?: string;
|
||||
page_label?: string;
|
||||
reply: string;
|
||||
reasoning?: string;
|
||||
error?: string;
|
||||
tool_calls: ChatToolCall[];
|
||||
approvals: ChatApproval[];
|
||||
actions: ChatActionDone[];
|
||||
navigate: ChatNavigation[];
|
||||
created_at: string;
|
||||
finished_at?: string;
|
||||
}
|
||||
|
||||
/** One recorded event of a turn, as its stream sends it. */
|
||||
export type ChatEvent = { seq: number } & (
|
||||
| { type: "reasoning" | "delta" | "done" | "error" | "cancelled"; text: string }
|
||||
| ({ type: "tool" } & ChatToolCall)
|
||||
| ({ type: "navigate" } & ChatNavigation)
|
||||
| ({ type: "approval" } & ChatApproval)
|
||||
| ({ type: "action" } & ChatActionDone)
|
||||
);
|
||||
|
||||
const sessionPath = (id: string) => `/api/chat/sessions/${encodeURIComponent(id)}`;
|
||||
const turnPath = (id: string) => `/api/chat/turns/${encodeURIComponent(id)}`;
|
||||
|
||||
export const chatSessions = (signal?: AbortSignal) => get<ChatSessions>("/api/chat/sessions", signal);
|
||||
export const createChatSession = () => send<ChatSession>("POST", "/api/chat/sessions");
|
||||
export const renameChatSession = (id: string, title: string) => send<ChatSession>("PATCH", sessionPath(id), { title });
|
||||
export const deleteChatSession = (id: string) => send<void>("DELETE", sessionPath(id));
|
||||
export const chatTurns = (id: string, signal?: AbortSignal) => get<ChatTurn[]>(`${sessionPath(id)}/turns`, signal);
|
||||
export const chatTurn = (id: string, signal?: AbortSignal) => get<ChatTurn>(turnPath(id), signal);
|
||||
export const sendChatTurn = (sessionID: string, text: string, page?: { page: string; page_label: string }) =>
|
||||
send<ChatTurn>("POST", `${sessionPath(sessionID)}/turns`, { text, ...page });
|
||||
export const cancelChatTurn = (id: string) => send<ChatTurn>("POST", `${turnPath(id)}/cancel`);
|
||||
|
||||
/**
|
||||
* Yields a turn's recorded events after the cursor until the turn ends. The
|
||||
* stream ends after a done, error or cancelled event; a dropped connection
|
||||
* ends it early, and the caller reconnects from the last seq it saw.
|
||||
*/
|
||||
export async function* chatTurnEvents(id: string, after: number, signal: AbortSignal): AsyncGenerator<ChatEvent> {
|
||||
const res = await request(`${turnPath(id)}/events?after=${after}`, signal);
|
||||
if (!res.body) return;
|
||||
const reader = res.body.pipeThrough(new TextDecoderStream()).getReader();
|
||||
let buffered = "";
|
||||
try {
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) return;
|
||||
buffered += value;
|
||||
let end: number;
|
||||
while ((end = buffered.indexOf("\n\n")) >= 0) {
|
||||
const frame = buffered.slice(0, end);
|
||||
buffered = buffered.slice(end + 2);
|
||||
const data = frame.split("\n").find((line) => line.startsWith("data: "));
|
||||
if (data) yield JSON.parse(data.slice(6)) as ChatEvent;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
void reader.cancel().catch(() => undefined);
|
||||
reader.releaseLock();
|
||||
}
|
||||
}
|
||||
@@ -1,94 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ArrowUpRight, MessageSquare, ShieldAlert } from "@lucide/vue";
|
||||
import { computed, onMounted, ref } from "vue";
|
||||
import { RouterLink } from "vue-router";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Item, ItemActions, ItemContent, ItemDescription, ItemMedia, ItemTitle } from "@/components/ui/item";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import type { ChatActionDone } from "../api";
|
||||
import { answer, approvals, conversationOf, currentSession, selectSession } from "./state";
|
||||
|
||||
/**
|
||||
* An action judgement held for a person, with Approve and Deny while it waits.
|
||||
* This card is the only way to answer it from the chat: a reply in the
|
||||
* conversation is never an approval. Once answered it says what became of the
|
||||
* action.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
requestId: string;
|
||||
action: string;
|
||||
summary: string;
|
||||
/** The run that asked, when a run did rather than this conversation. */
|
||||
runId?: string;
|
||||
outcome?: ChatActionDone;
|
||||
}>();
|
||||
|
||||
// Resolved before a link shows, so a card never offers a run that isn't one.
|
||||
const origin = ref<{ session: string | null } | null>(null);
|
||||
onMounted(async () => {
|
||||
if (props.runId) origin.value = { session: await conversationOf(props.runId) };
|
||||
});
|
||||
|
||||
const pending = computed(() => approvals.value.find((a) => a.id === props.requestId));
|
||||
const answering = ref(false);
|
||||
const error = ref("");
|
||||
|
||||
const outcomeLabel: Record<ChatActionDone["state"], string> = {
|
||||
succeeded: "Ran",
|
||||
failed: "Didn't run",
|
||||
unknown: "Outcome unknown",
|
||||
denied: "Denied",
|
||||
expired: "Expired",
|
||||
};
|
||||
|
||||
async function decide(approved: boolean): Promise<void> {
|
||||
if (answering.value) return;
|
||||
answering.value = true;
|
||||
error.value = "";
|
||||
try {
|
||||
await answer(props.requestId, approved);
|
||||
} catch (err) {
|
||||
error.value = err instanceof Error ? err.message : String(err);
|
||||
} finally {
|
||||
answering.value = false;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Item variant="outline" size="sm" class="mt-2 items-start" role="group" :aria-label="`Approval for ${action}`">
|
||||
<ItemMedia variant="icon" class="text-warn"><ShieldAlert aria-hidden="true" /></ItemMedia>
|
||||
<ItemContent class="min-w-0">
|
||||
<ItemTitle class="w-auto break-words">{{ action }}</ItemTitle>
|
||||
<ItemDescription class="line-clamp-none whitespace-pre-wrap break-words">{{ summary }}</ItemDescription>
|
||||
<span v-if="pending" class="text-caption text-muted-foreground">
|
||||
Respond by <Timestamp :at="pending.step_deadline || pending.deadline" absolute />
|
||||
</span>
|
||||
<p v-if="outcome?.result" class="mt-1 whitespace-pre-wrap break-words font-mono text-caption">{{ outcome.result }}</p>
|
||||
<p v-if="error" role="alert" class="text-caption text-destructive">{{ error }}</p>
|
||||
<ItemActions class="mt-1 flex-wrap justify-start">
|
||||
<template v-if="pending">
|
||||
<Button size="sm" :disabled="answering" @click="decide(true)">Approve</Button>
|
||||
<Button size="sm" variant="outline" :disabled="answering" @click="decide(false)">Deny</Button>
|
||||
</template>
|
||||
<Badge v-else-if="outcome" :variant="outcome.state === 'succeeded' ? 'secondary' : 'warn'">{{ outcomeLabel[outcome.state] }}</Badge>
|
||||
<Badge v-else variant="secondary">Answered</Badge>
|
||||
<Button
|
||||
v-if="origin?.session && origin.session !== currentSession"
|
||||
variant="link"
|
||||
size="sm"
|
||||
@click="selectSession(origin.session)"
|
||||
>
|
||||
<MessageSquare aria-hidden="true" data-icon="inline-start" />Open conversation
|
||||
</Button>
|
||||
<Button v-else-if="runId && origin && !origin.session" variant="link" size="sm" as-child>
|
||||
<RouterLink :to="{ name: 'run', params: { id: runId } }" :aria-label="`View run for ${action}`"
|
||||
>View run <ArrowUpRight aria-hidden="true" data-icon="inline-end"
|
||||
/></RouterLink>
|
||||
</Button>
|
||||
</ItemActions>
|
||||
</ItemContent>
|
||||
</Item>
|
||||
</template>
|
||||
@@ -1,59 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { Menu, SquarePen } from "@lucide/vue";
|
||||
import { computed, ref } from "vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import ChatSessionActions from "./ChatSessionActions.vue";
|
||||
import ChatSessionList from "./ChatSessionList.vue";
|
||||
import { sessionTitle } from "./session";
|
||||
import { currentSession, newChat, sessions, useEscapeLayer } from "./state";
|
||||
|
||||
/**
|
||||
* One row for everything that is not the conversation: the drawer of
|
||||
* conversations, which one is open, and icon controls on the right. The dock
|
||||
* fills the slots: `start` before the drawer button, `actions` before the more
|
||||
* menu, and `end` last.
|
||||
*/
|
||||
const drawer = ref(false);
|
||||
useEscapeLayer(drawer);
|
||||
|
||||
const title = computed(() => {
|
||||
const open = sessions.value.find((s) => s.session_id === currentSession.value);
|
||||
return open ? sessionTitle(open) : "New chat";
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex items-center gap-0.5 px-2 py-1.5">
|
||||
<slot name="start" />
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="flex-none"
|
||||
aria-label="Conversations"
|
||||
:aria-expanded="drawer"
|
||||
@click="drawer = true"
|
||||
>
|
||||
<Menu />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Conversations</TooltipContent>
|
||||
</Tooltip>
|
||||
<span class="min-w-0 flex-1 truncate px-1 text-label font-medium" :title="title">{{ title }}</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="ghost" size="icon-sm" class="flex-none" aria-label="New chat" @click="newChat">
|
||||
<SquarePen />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>New chat</TooltipContent>
|
||||
</Tooltip>
|
||||
<slot name="actions" />
|
||||
<ChatSessionActions />
|
||||
<slot name="end" />
|
||||
<ChatSessionList v-if="drawer" @close="drawer = false" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,118 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { computed } from "vue";
|
||||
|
||||
import { Bubble, BubbleContent } from "@/components/ui/bubble";
|
||||
import { Trace } from "@/components/ui/trace";
|
||||
import { CodeBlockCopyButton } from "@/components/ui/code-block";
|
||||
import { Message, MessageContent, MessageFooter } from "@/components/ui/message";
|
||||
import ChatMarkdown from "./ChatMarkdown.vue";
|
||||
import ChatThinking from "./ChatThinking.vue";
|
||||
import ChatToolCall from "./ChatToolCall.vue";
|
||||
import ChatToolGroup from "./ChatToolGroup.vue";
|
||||
import type { ChatToolCall as ToolCall } from "./state";
|
||||
|
||||
/**
|
||||
* One message, from either side of the conversation. There is no speaker
|
||||
* label: which side of the panel it sits on, and its fill, are what say who is
|
||||
* talking. A trailing action arrives through the slot, so the retry the
|
||||
* transcript offers belongs to the bubble rather than beside it. A finished
|
||||
* reply carries a copy action beneath it.
|
||||
*/
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
text: string;
|
||||
tools?: ToolCall[];
|
||||
/** The page the operator asked from. */
|
||||
page?: string;
|
||||
assistant?: boolean;
|
||||
/** The turn is still arriving: a tool call with no outcome is running. */
|
||||
streaming?: boolean;
|
||||
/** The live turn's thinking so far, rendered as a collapsible trace. */
|
||||
reasoning?: string;
|
||||
/** The live turn is still arriving and has not reasoned yet. */
|
||||
thinkingPending?: boolean;
|
||||
/** The text says why the turn failed rather than answering. */
|
||||
error?: boolean;
|
||||
}>(),
|
||||
{ tools: () => [], page: "", assistant: false, streaming: false, reasoning: "", thinkingPending: false },
|
||||
);
|
||||
|
||||
// The reply in the order it happened: text up to each call's offset, then the
|
||||
// call. Consecutive calls at one point fold into one line; a navigation chip
|
||||
// is an action for the operator, so it always stands alone. A call recorded
|
||||
// without an offset sits at the start.
|
||||
type Segment = { text: string } | { tools: ToolCall[] };
|
||||
const segments = computed(() => {
|
||||
const chars = Array.from(props.text);
|
||||
const out: Segment[] = [];
|
||||
let at = 0;
|
||||
let open = false;
|
||||
for (const tool of props.tools) {
|
||||
const offset = Math.min(Math.max(tool.text_offset ?? 0, at), chars.length);
|
||||
if (offset > at) {
|
||||
out.push({ text: chars.slice(at, offset).join("") });
|
||||
at = offset;
|
||||
open = false;
|
||||
}
|
||||
const last = out[out.length - 1];
|
||||
if (!tool.path && open && last && "tools" in last) last.tools.push(tool);
|
||||
else {
|
||||
out.push({ tools: [tool] });
|
||||
open = !tool.path;
|
||||
}
|
||||
}
|
||||
if (at < chars.length) out.push({ text: chars.slice(at).join("") });
|
||||
return out;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Message :align="assistant ? 'start' : 'end'">
|
||||
<MessageContent>
|
||||
<Bubble :variant="assistant ? 'muted' : 'tinted'" class="max-w-[min(78ch,92%)]">
|
||||
<BubbleContent class="[overflow-wrap:anywhere]">
|
||||
<template v-if="assistant">
|
||||
<ChatThinking
|
||||
v-if="reasoning || thinkingPending"
|
||||
:text="reasoning"
|
||||
:pending="thinkingPending"
|
||||
:collapsed="!streaming"
|
||||
/>
|
||||
<template v-if="error">
|
||||
<Trace v-if="tools.length" class="mb-2">
|
||||
<ChatToolGroup v-if="tools.length > 1" :tools="tools" :streaming="false" />
|
||||
<ChatToolCall v-else :tool="tools[0]" :streaming="false" />
|
||||
</Trace>
|
||||
<Alert variant="destructive" class="text-label"><AlertDescription>{{ text }}</AlertDescription></Alert>
|
||||
</template>
|
||||
<template v-for="(segment, i) in segments" v-else :key="i">
|
||||
<ChatMarkdown v-if="'text' in segment" :text="segment.text" />
|
||||
<Trace v-else class="my-2">
|
||||
<ChatToolGroup
|
||||
v-if="segment.tools.length > 1"
|
||||
:tools="segment.tools"
|
||||
:streaming="streaming && i === segments.length - 1"
|
||||
/>
|
||||
<ChatToolCall
|
||||
v-else
|
||||
:tool="segment.tools[0]"
|
||||
:streaming="streaming && i === segments.length - 1"
|
||||
/>
|
||||
</Trace>
|
||||
</template>
|
||||
</template>
|
||||
<div v-else class="whitespace-pre-wrap">{{ text }}</div>
|
||||
<p v-if="!assistant && page" class="mt-1 text-caption opacity-70">{{ page }}</p>
|
||||
<slot />
|
||||
</BubbleContent>
|
||||
</Bubble>
|
||||
<MessageFooter
|
||||
v-if="assistant && !streaming && text"
|
||||
class="px-0 transition-opacity focus-within:opacity-100 [@media(hover:hover)]:opacity-0 [@media(hover:hover)]:group-hover/message:opacity-100"
|
||||
>
|
||||
<CodeBlockCopyButton :value="text" />
|
||||
</MessageFooter>
|
||||
</MessageContent>
|
||||
</Message>
|
||||
</template>
|
||||
@@ -1,241 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { nextTick, ref, watch } from "vue";
|
||||
|
||||
import { Clock, Pencil, X } from "@lucide/vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { isExactCommand, replaceToken } from "./commands";
|
||||
import ChatSlashPalette from "./ChatSlashPalette.vue";
|
||||
import ChatSuggestions from "./ChatSuggestions.vue";
|
||||
import {
|
||||
closeCommandMenu,
|
||||
commandMatches,
|
||||
commandSelection,
|
||||
commandSpecs,
|
||||
clearPageTag,
|
||||
pageTag,
|
||||
placeholderHint,
|
||||
messages,
|
||||
composerText,
|
||||
editQueued,
|
||||
menuTrigger,
|
||||
isCommandMenuOpen,
|
||||
isSending,
|
||||
moveCommandSelection,
|
||||
queuedMessages,
|
||||
removeQueued,
|
||||
sendMessage,
|
||||
stopTurn,
|
||||
syncCommandMenu,
|
||||
} from "./state";
|
||||
|
||||
/**
|
||||
* The composer: the text, the palette that completes a slash command, and the
|
||||
* actions. It stays writeable while a turn is in flight: a message sent then
|
||||
* waits behind it (Queue), and Stop is an addition to the row, never a
|
||||
* replacement for Send.
|
||||
*
|
||||
* The textarea is stripped back to bare text inside the shell that carries the
|
||||
* border and the fill. It grows with what is typed and stops at `max-h-40`, so
|
||||
* a long draft scrolls rather than eating the transcript above it.
|
||||
*/
|
||||
// Flat drops the field's own border and fill when the card around it already
|
||||
// draws them, so the collapsed dock reads as one surface rather than a box in a box.
|
||||
const props = defineProps<{ open: boolean; flat?: boolean }>();
|
||||
|
||||
const field = ref<{ $el: HTMLTextAreaElement } | null>(null);
|
||||
|
||||
function focus(): void {
|
||||
field.value?.$el?.focus();
|
||||
}
|
||||
|
||||
defineExpose({ focus });
|
||||
|
||||
// The panel stays mounted so the session survives navigation, so opening it is
|
||||
// a prop change rather than a mount: focus the composer on that edge.
|
||||
watch(
|
||||
() => props.open,
|
||||
(open) => {
|
||||
if (open) void nextTick(focus);
|
||||
},
|
||||
);
|
||||
|
||||
// A finished turn leaves the caret in the composer, where the next message is
|
||||
// typed, rather than on the button that sent the last one.
|
||||
watch(isSending, (sending, wasSending) => {
|
||||
if (wasSending && !sending) void nextTick(focus);
|
||||
});
|
||||
|
||||
function onInput(event: Event): void {
|
||||
const input = event.target as HTMLTextAreaElement;
|
||||
composerText.value = input.value;
|
||||
syncCommandMenu(input.value, input.selectionStart ?? input.value.length);
|
||||
}
|
||||
|
||||
function choose(index: number): void {
|
||||
const item = commandMatches.value[index];
|
||||
const input = field.value?.$el;
|
||||
if (!item || !input) return;
|
||||
const caret = input.selectionStart ?? input.value.length;
|
||||
// Completing replaces the token the caret sits in, which is decided by the
|
||||
// same rule that found the matches.
|
||||
const edit = replaceToken(input.value, caret, item.label);
|
||||
composerText.value = edit.text;
|
||||
closeCommandMenu();
|
||||
void nextTick(() => {
|
||||
input.focus();
|
||||
input.setSelectionRange(edit.cursor, edit.cursor);
|
||||
});
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
// Safari may end composition before delivering its confirming Enter.
|
||||
if (event.key === "Enter" && (event.isComposing || event.keyCode === 229)) return;
|
||||
const plain = !event.shiftKey && !event.ctrlKey && !event.metaKey;
|
||||
if (isCommandMenuOpen.value) {
|
||||
// A command typed in full is sent rather than completed, so Enter never
|
||||
// re-enters the command the palette was offering.
|
||||
if (
|
||||
event.key === "Enter" &&
|
||||
plain &&
|
||||
menuTrigger.value === "/" &&
|
||||
isExactCommand(commandSpecs.value, composerText.value)
|
||||
) {
|
||||
event.preventDefault();
|
||||
closeCommandMenu();
|
||||
void sendMessage();
|
||||
return;
|
||||
}
|
||||
if (event.key === "ArrowDown") {
|
||||
event.preventDefault();
|
||||
moveCommandSelection(1);
|
||||
return;
|
||||
}
|
||||
if (event.key === "ArrowUp") {
|
||||
event.preventDefault();
|
||||
moveCommandSelection(-1);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
commandMatches.value.length &&
|
||||
((event.key === "Enter" && plain) || (event.key === "Tab" && !event.shiftKey))
|
||||
) {
|
||||
event.preventDefault();
|
||||
choose(commandSelection.value);
|
||||
return;
|
||||
}
|
||||
if (event.key === "Escape") {
|
||||
// Consumed here: dismissing the palette must not also close the panel.
|
||||
event.preventDefault();
|
||||
closeCommandMenu();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (event.key === "Enter" && !event.shiftKey) {
|
||||
event.preventDefault();
|
||||
void sendMessage();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :class="flat ? 'p-2' : 'border-t p-3'">
|
||||
<ul v-if="queuedMessages.length" aria-label="Queued messages" class="mb-2 flex flex-col gap-1">
|
||||
<li
|
||||
v-for="(queued, index) in queuedMessages"
|
||||
:key="index"
|
||||
class="flex items-center gap-1 rounded-md border border-dashed border-border px-2 py-1 text-label text-fg-muted"
|
||||
>
|
||||
<Clock class="size-3.5 flex-none" aria-hidden="true" />
|
||||
<span class="min-w-0 flex-1 truncate">{{ queued }}</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="ghost" size="icon" class="size-7" aria-label="Edit queued message" @click="editQueued(index)"
|
||||
><Pencil
|
||||
/></Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Edit</TooltipContent>
|
||||
</Tooltip>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="ghost" size="icon" class="size-7" aria-label="Remove queued message" @click="removeQueued(index)"
|
||||
><X
|
||||
/></Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Remove</TooltipContent>
|
||||
</Tooltip>
|
||||
</li>
|
||||
</ul>
|
||||
<ul v-if="!flat && pageTag" aria-label="Message context" class="mb-2 flex flex-wrap gap-1">
|
||||
<li
|
||||
v-if="pageTag"
|
||||
class="flex max-w-full items-center gap-1 rounded-md border border-border bg-muted px-2 py-0.5 text-label"
|
||||
>
|
||||
<span class="truncate">{{ pageTag.label }}</span>
|
||||
<Button variant="ghost" size="icon" class="size-5" aria-label="Remove page context" @click="clearPageTag"
|
||||
><X
|
||||
/></Button>
|
||||
</li>
|
||||
</ul>
|
||||
<!-- An empty conversation lists the prompts itself; once it has messages
|
||||
they sit beside the field so they stay reachable without scrolling up.
|
||||
The minimised bar is the field alone; the page context still goes with
|
||||
the message. -->
|
||||
<ChatSuggestions v-if="!flat && messages.length" />
|
||||
<div
|
||||
:class="
|
||||
cn(
|
||||
'relative flex gap-2 rounded-xl border transition-colors duration-200',
|
||||
// Minimised, the field is one line: the controls centre on it.
|
||||
flat ? 'items-center border-transparent px-2 py-1.5' : 'items-end border-border-strong bg-muted px-3 py-2.5',
|
||||
)
|
||||
"
|
||||
>
|
||||
<div v-if="$slots.start" :class="cn('flex flex-none items-center', !flat && 'mb-1.5')">
|
||||
<slot name="start" />
|
||||
</div>
|
||||
<Textarea
|
||||
ref="field"
|
||||
:model-value="composerText"
|
||||
rows="1"
|
||||
:placeholder="placeholderHint || 'Message Archie'"
|
||||
aria-label="Message Archie"
|
||||
role="combobox"
|
||||
aria-controls="slash-palette"
|
||||
:aria-expanded="isCommandMenuOpen ? 'true' : 'false'"
|
||||
:aria-activedescendant="isCommandMenuOpen && commandMatches.length ? `slash-palette-option-${commandSelection}` : undefined"
|
||||
:class="cn('max-h-40 flex-1 resize-none rounded-none border-0 bg-transparent! px-0 text-label pointer-coarse:text-base shadow-none focus-visible:ring-0', flat ? 'min-h-10 py-2.5 text-base leading-5' : 'min-h-11 py-1')"
|
||||
@input="onInput"
|
||||
@keydown="onKeydown"
|
||||
/>
|
||||
|
||||
<ChatSlashPalette
|
||||
v-if="isCommandMenuOpen"
|
||||
:matches="commandMatches"
|
||||
:selection="commandSelection"
|
||||
label="Commands"
|
||||
@choose="choose"
|
||||
/>
|
||||
|
||||
<!-- Centred on the field's first line, then kept at the bottom as it grows. -->
|
||||
<div :class="cn('flex flex-none items-center gap-2', !flat && 'mb-1.5')">
|
||||
<slot name="actions" />
|
||||
<!-- Only while a turn is arriving: a Stop with nothing to stop is a
|
||||
button that lies about what the panel is doing. -->
|
||||
<Button v-if="isSending" variant="outline" size="sm" @click="stopTurn"
|
||||
>Stop</Button
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
:variant="composerText.trim() ? 'default' : 'secondary'"
|
||||
:disabled="!composerText.trim()"
|
||||
@click="sendMessage()"
|
||||
>{{ isSending ? "Queue" : "Send" }}</Button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,579 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { ChevronDown, ChevronUp, GripVertical, PanelLeft, PanelRight, PictureInPicture2 } from "@lucide/vue";
|
||||
import { useDraggable, useEventListener, useMediaQuery, usePointerSwipe, useStorage, useWindowSize } from "@vueuse/core";
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuRadioGroup,
|
||||
DropdownMenuRadioItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { cn } from "@/lib/utils";
|
||||
import ChatBar from "./ChatBar.vue";
|
||||
import ChatComposer from "./ChatComposer.vue";
|
||||
import ChatPending from "./ChatPending.vue";
|
||||
import ChatTranscript from "./ChatTranscript.vue";
|
||||
import {
|
||||
DOCK_STORAGE_KEY,
|
||||
DRAG_START,
|
||||
MAX_W,
|
||||
MIN_H,
|
||||
MIN_W,
|
||||
RESIZE_DIRS,
|
||||
SWIPE,
|
||||
barPlacement,
|
||||
fitRect,
|
||||
BAR_W,
|
||||
INSET,
|
||||
handleOrientation,
|
||||
handleValue,
|
||||
keyboardCover,
|
||||
keyStep,
|
||||
migrateDockStorage,
|
||||
normalizeLayout,
|
||||
phoneBarBottom,
|
||||
pinnedWidth,
|
||||
resizeRect,
|
||||
snapEdge,
|
||||
type DockLayout,
|
||||
type DockMode,
|
||||
type Rect,
|
||||
type ResizeDir,
|
||||
} from "./ChatDockLayout";
|
||||
import { dockExpanded, escapeOwnedByLayer, isSending, useChat, useEscapeLayer } from "./state";
|
||||
import { setDockOpen, unseenCount } from "./unseen";
|
||||
|
||||
/**
|
||||
* Chat is a window docked to every page, not a route: the operator asks Archie
|
||||
* about the page they are already on, so navigating must not reset it, and it
|
||||
* must not replace the work that prompted the question. The agent is told
|
||||
* which page that is.
|
||||
*
|
||||
* It is the composer alone until the operator focuses it or a turn starts, then
|
||||
* the conversation opens above it. Hiding the conversation leaves the bar where
|
||||
* it was. It is deliberately not a modal: no scrim, no scroll lock, no focus
|
||||
* trap.
|
||||
*
|
||||
* On a desktop-width screen the expanded conversation is a free-floating
|
||||
* window: the header drags it anywhere, all eight edges and corners resize it
|
||||
* (pointer and keyboard), and dragging near a side edge shows the pinned
|
||||
* split, committing on release. The header's position menu picks Left, Float
|
||||
* or Right outright; pinned, the page reflows beside the dock instead of
|
||||
* sitting under it. Ctrl+/ toggles the window, Escape collapses it, and the
|
||||
* collapsed bar stays where it was and drags too. The layout (mode, x, y,
|
||||
* width, height) is remembered per browser under "archie.chat.dock.v2", which
|
||||
* replaces the old edge-pin preference.
|
||||
*
|
||||
* On a phone-width screen the collapsed dock is the full-width bottom bar and
|
||||
* the open conversation a full-screen sheet; both ride above the on-screen
|
||||
* keyboard, which iOS does not resize the page for, and swiping down on the
|
||||
* conversation header hides it. No float or resize handles
|
||||
* exist below the desktop breakpoint.
|
||||
*
|
||||
* The collapsed bar's show button carries the count of replies and run cards
|
||||
* that landed while it was closed.
|
||||
*
|
||||
* It stays mounted, so the session and any turn in flight survive a navigation.
|
||||
* It is mounted outside the page container, so `position: fixed` anchors to the
|
||||
* viewport. The composer page is the same chat full size, so the dock steps
|
||||
* aside there.
|
||||
*/
|
||||
useChat();
|
||||
|
||||
|
||||
const expanded = dockExpanded;
|
||||
watch(expanded, setDockOpen, { immediate: true });
|
||||
|
||||
// The old edge-pin preference moves into the new key before useStorage reads it.
|
||||
migrateDockStorage(localStorage, window.innerWidth, window.innerHeight);
|
||||
const stored = useStorage<DockLayout>(
|
||||
DOCK_STORAGE_KEY,
|
||||
normalizeLayout(null, window.innerWidth, window.innerHeight),
|
||||
localStorage,
|
||||
);
|
||||
|
||||
const desktop = useMediaQuery("(min-width: 768px)");
|
||||
const { width: vw, height: vh } = useWindowSize();
|
||||
const layout = computed<DockLayout>({
|
||||
get: () => normalizeLayout(stored.value, vw.value, vh.value),
|
||||
set: (value) => {
|
||||
stored.value = value;
|
||||
},
|
||||
});
|
||||
const mode = computed<DockMode>(() => (desktop.value ? layout.value.mode : "float"));
|
||||
const pinned = computed(() => desktop.value && expanded.value && mode.value !== "float");
|
||||
const pinW = computed(() => pinnedWidth(layout.value.w, vw.value));
|
||||
const pinMax = computed(() => Math.max(MIN_W, Math.min(MAX_W, vw.value - 480)));
|
||||
|
||||
// The rendered rectangle of the window: full-height at an edge when pinned, the
|
||||
// clamped stored rectangle when floating.
|
||||
const winRect = computed<Rect>(() => {
|
||||
if (!desktop.value) return { x: 0, y: 0, w: vw.value, h: vh.value };
|
||||
if (pinned.value) {
|
||||
return { x: mode.value === "left" ? 0 : vw.value - pinW.value, y: 0, w: pinW.value, h: vh.value };
|
||||
}
|
||||
// Opening the window never narrows it below the minimised bar.
|
||||
const minW = Math.min(BAR_W, vw.value - INSET * 2);
|
||||
return fitRect({ ...layout.value, w: Math.max(layout.value.w, minW) }, vw.value, vh.value);
|
||||
});
|
||||
|
||||
// The part of the layout viewport the on-screen keyboard covers, and the height
|
||||
// left above it. Fixed elements stay anchored to the layout viewport, so without
|
||||
// this the bar sits under the keyboard.
|
||||
const keyboard = ref(0);
|
||||
const visibleHeight = ref(window.innerHeight);
|
||||
// How far the browser has panned the page up to show the focused input.
|
||||
const visibleTop = ref(0);
|
||||
function followViewport(): void {
|
||||
const vv = window.visualViewport;
|
||||
keyboard.value = keyboardCover(window.innerHeight, vv);
|
||||
visibleHeight.value = vv ? vv.height : window.innerHeight;
|
||||
visibleTop.value = vv ? Math.max(0, Math.round(vv.offsetTop)) : 0;
|
||||
}
|
||||
useEventListener(() => window.visualViewport, ["resize", "scroll"], followViewport);
|
||||
const phoneBottom = computed(() => phoneBarBottom(keyboard.value));
|
||||
|
||||
const wrapStyle = computed<Record<string, string> | undefined>((): Record<string, string> | undefined => {
|
||||
// On a phone the open conversation is a full-screen sheet over the part of
|
||||
// the screen the keyboard leaves.
|
||||
if (!desktop.value && expanded.value) return { top: `${visibleTop.value}px`, height: `${visibleHeight.value}px` };
|
||||
if (!desktop.value) return { bottom: phoneBottom.value };
|
||||
if (pinned.value) {
|
||||
return { left: `${winRect.value.x}px`, top: "0px", width: `${pinW.value}px`, height: `${vh.value}px` };
|
||||
}
|
||||
const rect = winRect.value;
|
||||
if (expanded.value) {
|
||||
// A tablet's on-screen keyboard covers the layout viewport's bottom; keep
|
||||
// the window, and so its composer, in the part left above it.
|
||||
const fit = keyboard.value > 0 ? fitRect(rect, vw.value, visibleHeight.value) : rect;
|
||||
const top = keyboard.value > 0 ? fit.y + visibleTop.value : fit.y;
|
||||
return { left: `${fit.x}px`, top: `${top}px`, width: `${fit.w}px`, height: `${fit.h}px` };
|
||||
}
|
||||
const bar = barPlacement(rect, mode.value, vw.value);
|
||||
return { left: `${bar.x}px`, bottom: `${bar.bottom + keyboard.value}px`, width: `${bar.w}px` };
|
||||
});
|
||||
|
||||
// Nothing outside the dock closes it: every navigation control is outside it,
|
||||
// so a click-outside dismissal turned navigation into a collapse and read as a
|
||||
// lost conversation. Hide, swipe down, Escape and Ctrl+/ are the only ways to
|
||||
// collapse.
|
||||
|
||||
watch(isSending, (sending) => {
|
||||
if (sending) expanded.value = true;
|
||||
});
|
||||
|
||||
function onKeydown(event: KeyboardEvent): void {
|
||||
// A focused control (the composer dismissing its palette, or the topbar
|
||||
// search) already handled Escape via preventDefault; collapsing too would
|
||||
// make that menu impossible to dismiss on its own. A popover portalled out
|
||||
// of the bar owns Escape by being open, which the flag reports.
|
||||
if (event.defaultPrevented || event.key !== "Escape" || escapeOwnedByLayer()) return;
|
||||
expanded.value = false;
|
||||
}
|
||||
watch(expanded, (open) => {
|
||||
if (open) document.addEventListener("keydown", onKeydown);
|
||||
else document.removeEventListener("keydown", onKeydown);
|
||||
});
|
||||
onUnmounted(() => document.removeEventListener("keydown", onKeydown));
|
||||
|
||||
function onGlobalKeydown(event: KeyboardEvent): void {
|
||||
if (event.defaultPrevented) return;
|
||||
if ((event.ctrlKey || event.metaKey) && event.key === "/") {
|
||||
event.preventDefault();
|
||||
expanded.value = !expanded.value;
|
||||
}
|
||||
}
|
||||
onMounted(() => document.addEventListener("keydown", onGlobalKeydown));
|
||||
onUnmounted(() => document.removeEventListener("keydown", onGlobalKeydown));
|
||||
|
||||
// The page reserves the collapsed dock's height, read from the rendered bar so
|
||||
// the last line of any page can scroll clear of it. A bar floating clear of the
|
||||
// bottom of the screen reserves nothing.
|
||||
const dock = ref<HTMLElement | null>(null);
|
||||
let observer: ResizeObserver | null = null;
|
||||
function reserve(): void {
|
||||
if (expanded.value || !dock.value) return;
|
||||
const rect = dock.value.getBoundingClientRect();
|
||||
// Only a bar sitting in the bottom quarter of the screen needs the page to
|
||||
// reserve room under it; one floating higher up does not.
|
||||
const clear = rect.bottom >= window.innerHeight * 0.75 ? Math.ceil(window.innerHeight - rect.top) : 0;
|
||||
document.documentElement.style.setProperty("--chat-dock-clear", `${clear}px`);
|
||||
}
|
||||
onMounted(() => {
|
||||
observer = new ResizeObserver(reserve);
|
||||
if (dock.value) observer.observe(dock.value);
|
||||
window.addEventListener("resize", reserve);
|
||||
});
|
||||
onUnmounted(() => {
|
||||
observer?.disconnect();
|
||||
window.removeEventListener("resize", reserve);
|
||||
document.documentElement.style.removeProperty("--chat-dock-clear");
|
||||
});
|
||||
watch([expanded, desktop, () => layout.value.x, () => layout.value.y, () => layout.value.w, mode], () =>
|
||||
nextTick(reserve),
|
||||
);
|
||||
|
||||
// The page makes room for a pinned dock through these two variables.
|
||||
watch([pinned, mode, pinW], () => {
|
||||
const root = document.documentElement.style;
|
||||
root.setProperty("--chat-pin-l", pinned.value && mode.value === "left" ? `${pinW.value}px` : "0px");
|
||||
root.setProperty("--chat-pin-r", pinned.value && mode.value === "right" ? `${pinW.value}px` : "0px");
|
||||
}, { immediate: true });
|
||||
onUnmounted(() => {
|
||||
document.documentElement.style.removeProperty("--chat-pin-l");
|
||||
document.documentElement.style.removeProperty("--chat-pin-r");
|
||||
});
|
||||
|
||||
const MODES: { mode: DockMode; label: string; icon: typeof PanelLeft }[] = [
|
||||
{ mode: "left", label: "Left", icon: PanelLeft },
|
||||
{ mode: "float", label: "Float", icon: PictureInPicture2 },
|
||||
{ mode: "right", label: "Right", icon: PanelRight },
|
||||
];
|
||||
const positionOpen = ref(false);
|
||||
useEscapeLayer(positionOpen);
|
||||
function setMode(next: DockMode): void {
|
||||
if (!desktop.value) return;
|
||||
layout.value = { ...layout.value, mode: next };
|
||||
expanded.value = true;
|
||||
}
|
||||
|
||||
const dragging = ref(false);
|
||||
const snapTarget = ref<"left" | "right" | null>(null);
|
||||
// A resize follows the pointer directly; the position transition would lag it.
|
||||
const resizing = ref(false);
|
||||
const header = ref<HTMLElement | null>(null);
|
||||
const bar = ref<HTMLElement | null>(null);
|
||||
|
||||
// The header drags the open window and the bar drags the minimised one. The
|
||||
// controls inside them keep their own presses, except the move handle.
|
||||
function onDragSurface(target: HTMLElement): boolean {
|
||||
const surface = expanded.value ? header.value : bar.value;
|
||||
if (!surface?.contains(target)) return false;
|
||||
return !target.closest("button, a, input, select, textarea, [role=combobox], [role=separator]") || !!target.closest("[data-move-handle]");
|
||||
}
|
||||
|
||||
// Pointer travel before a press becomes a drag, so a click or a double-click
|
||||
// on a drag surface never moves the dock.
|
||||
let drag: { origin: Rect; x0: number; y0: number; moved: boolean; snap: "left" | "right" | null } | null = null;
|
||||
useDraggable(dock, {
|
||||
disabled: () => !desktop.value,
|
||||
onStart: (_, e) => {
|
||||
if (!e.isPrimary || !onDragSurface(e.target as HTMLElement)) return false;
|
||||
drag = { origin: { ...winRect.value }, x0: e.clientX, y0: e.clientY, moved: false, snap: null };
|
||||
},
|
||||
onMove: (_, e) => {
|
||||
if (!drag) return;
|
||||
const dx = e.clientX - drag.x0;
|
||||
const dy = e.clientY - drag.y0;
|
||||
if (!drag.moved && Math.hypot(dx, dy) < DRAG_START) return;
|
||||
drag.moved = true;
|
||||
dragging.value = true;
|
||||
const next = fitRect({ ...drag.origin, x: drag.origin.x + dx, y: drag.origin.y + dy }, vw.value, vh.value);
|
||||
layout.value = { ...layout.value, mode: "float", x: next.x, y: next.y, w: next.w, h: next.h };
|
||||
drag.snap = expanded.value ? snapEdge(e.clientX, vw.value) : null;
|
||||
snapTarget.value = drag.snap;
|
||||
},
|
||||
onEnd: (_, e) => {
|
||||
if (drag?.moved && e.type === "pointerup" && drag.snap) layout.value = { ...layout.value, mode: drag.snap };
|
||||
drag = null;
|
||||
dragging.value = false;
|
||||
snapTarget.value = null;
|
||||
},
|
||||
});
|
||||
|
||||
// Every resize handle, the pinned divider included, carries data-resize. The
|
||||
// delta is measured from the press and applied to the rectangle as it was then;
|
||||
// applying it to the live rectangle compounded every move.
|
||||
let resize: { dir: ResizeDir | "pin"; origin: Rect; w0: number; x0: number; y0: number } | null = null;
|
||||
useDraggable(dock, {
|
||||
disabled: () => !desktop.value,
|
||||
preventDefault: true,
|
||||
onStart: (_, e) => {
|
||||
const dir = (e.target as HTMLElement).closest<HTMLElement>("[data-resize]")?.dataset.resize as ResizeDir | "pin" | undefined;
|
||||
if (!e.isPrimary || !dir) return false;
|
||||
resize = { dir, origin: resizeOrigin(), w0: pinW.value, x0: e.clientX, y0: e.clientY };
|
||||
resizing.value = true;
|
||||
},
|
||||
onMove: (_, e) => {
|
||||
if (!resize) return;
|
||||
const dx = e.clientX - resize.x0;
|
||||
if (resize.dir === "pin") {
|
||||
layout.value = { ...layout.value, w: clampWidth(resize.w0 + (mode.value === "left" ? dx : -dx)) };
|
||||
return;
|
||||
}
|
||||
applyResize(resize.origin, resize.dir, dx, e.clientY - resize.y0);
|
||||
},
|
||||
onEnd: () => {
|
||||
resize = null;
|
||||
resizing.value = false;
|
||||
},
|
||||
});
|
||||
|
||||
// On a phone the header is a swipe surface, not a drag surface: a downward
|
||||
// flick hides the conversation.
|
||||
usePointerSwipe(header, {
|
||||
threshold: SWIPE,
|
||||
onSwipeEnd: (e, direction) => {
|
||||
if (desktop.value || e.type !== "pointerup" || direction !== "down") return;
|
||||
// The keyboard is for the composer, which is no longer in front of it.
|
||||
(document.activeElement as HTMLElement | null)?.blur();
|
||||
expanded.value = false;
|
||||
},
|
||||
});
|
||||
|
||||
function togglePin(event: MouseEvent): void {
|
||||
if (!desktop.value || !onDragSurface(event.target as HTMLElement)) return;
|
||||
layout.value = { ...layout.value, mode: mode.value === "float" ? "right" : "float" };
|
||||
}
|
||||
|
||||
function moveByKey(event: KeyboardEvent): void {
|
||||
if (!desktop.value || !event.key.startsWith("Arrow")) return;
|
||||
event.preventDefault();
|
||||
const step = keyStep(event.shiftKey);
|
||||
const rect = winRect.value;
|
||||
const next = fitRect(
|
||||
{
|
||||
...rect,
|
||||
x: rect.x + (event.key === "ArrowRight" ? step : event.key === "ArrowLeft" ? -step : 0),
|
||||
y: rect.y + (event.key === "ArrowDown" ? step : event.key === "ArrowUp" ? -step : 0),
|
||||
},
|
||||
vw.value,
|
||||
vh.value,
|
||||
);
|
||||
layout.value = { ...layout.value, mode: "float", x: next.x, y: next.y, w: next.w, h: next.h };
|
||||
}
|
||||
|
||||
const HANDLE_CLASS: Record<ResizeDir, string> = {
|
||||
n: "top-[-3px] left-3.5 right-3.5 h-2 cursor-ns-resize",
|
||||
s: "bottom-[-3px] left-3.5 right-3.5 h-2 cursor-ns-resize",
|
||||
e: "right-[-3px] top-3.5 bottom-3.5 w-2 cursor-ew-resize",
|
||||
w: "left-[-3px] top-3.5 bottom-3.5 w-2 cursor-ew-resize",
|
||||
ne: "top-0 right-0 size-3.5 cursor-nesw-resize",
|
||||
nw: "top-0 left-0 size-3.5 cursor-nwse-resize",
|
||||
se: "bottom-0 right-0 size-4 cursor-nwse-resize",
|
||||
sw: "bottom-0 left-0 size-4 cursor-nesw-resize",
|
||||
};
|
||||
const DIR_LABEL: Record<ResizeDir, string> = {
|
||||
n: "top",
|
||||
s: "bottom",
|
||||
e: "right",
|
||||
w: "left",
|
||||
ne: "top right",
|
||||
nw: "top left",
|
||||
se: "bottom right",
|
||||
sw: "bottom left",
|
||||
};
|
||||
// The minimised bar keeps its height, so only its width edges resize it.
|
||||
const visibleDirs = computed<ResizeDir[]>(() => (expanded.value ? [...RESIZE_DIRS] : ["e", "w"]));
|
||||
|
||||
// The rectangle a resize starts from. Minimised, the bar can sit at an edge
|
||||
// rather than at the stored x, so its rendered x and width are the origin, or
|
||||
// the first move would jump it.
|
||||
function resizeOrigin(): Rect {
|
||||
const rect = winRect.value;
|
||||
if (expanded.value || !dock.value) return rect;
|
||||
const bar = dock.value.getBoundingClientRect();
|
||||
return { ...rect, x: bar.left, w: bar.width };
|
||||
}
|
||||
|
||||
function applyResize(origin: Rect, dir: ResizeDir, dx: number, dy: number): void {
|
||||
const rect = resizeRect(origin, dir, dx, dy, vw.value, vh.value);
|
||||
layout.value = { ...layout.value, mode: "float", x: rect.x, y: rect.y, w: rect.w, h: rect.h };
|
||||
}
|
||||
|
||||
function onHandleKey(dir: ResizeDir, event: KeyboardEvent): void {
|
||||
if (!desktop.value || !event.key.startsWith("Arrow")) return;
|
||||
event.preventDefault();
|
||||
const step = keyStep(event.shiftKey);
|
||||
const dx = event.key === "ArrowRight" ? step : event.key === "ArrowLeft" ? -step : 0;
|
||||
const dy = event.key === "ArrowDown" ? step : event.key === "ArrowUp" ? -step : 0;
|
||||
applyResize(resizeOrigin(), dir, dx, dy);
|
||||
}
|
||||
|
||||
function clampWidth(w: number): number {
|
||||
return Math.min(Math.max(w, MIN_W), pinMax.value);
|
||||
}
|
||||
function onPinKey(event: KeyboardEvent): void {
|
||||
if (!desktop.value) return;
|
||||
const grow = event.key === (mode.value === "right" ? "ArrowLeft" : "ArrowRight");
|
||||
const shrink = event.key === (mode.value === "right" ? "ArrowRight" : "ArrowLeft");
|
||||
if (!grow && !shrink) return;
|
||||
event.preventDefault();
|
||||
layout.value = { ...layout.value, w: clampWidth(layout.value.w + (grow ? 16 : -16)) };
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
v-if="snapTarget"
|
||||
aria-hidden="true"
|
||||
:class="cn('pointer-events-none fixed inset-y-0 z-40 border-primary/40 bg-primary/10', snapTarget === 'left' ? 'left-0 border-r-2' : 'right-0 border-l-2')"
|
||||
:style="{ width: `${pinW}px` }"
|
||||
/>
|
||||
<div
|
||||
:class="cn(
|
||||
'pointer-events-none fixed z-40 transition-[left,top,bottom,width,height] duration-200 ease-out motion-reduce:transition-none',
|
||||
(dragging || resizing) && 'transition-none',
|
||||
!desktop && !expanded && 'inset-x-0 bottom-4 flex justify-center px-3 max-md:bottom-2',
|
||||
!desktop && expanded && 'inset-x-0 flex',
|
||||
// Docked, minimising hides the dock; the topbar button and Ctrl+/ bring
|
||||
// it back. It stays mounted so the session and a turn in flight survive.
|
||||
desktop && mode !== 'float' && !expanded && 'hidden',
|
||||
)"
|
||||
:style="wrapStyle"
|
||||
>
|
||||
<aside
|
||||
ref="dock"
|
||||
aria-label="Chat with Archie"
|
||||
:class="cn(
|
||||
'touch-hit pointer-events-auto relative flex flex-col border-border-strong bg-popover shadow-[var(--shadow-md)]',
|
||||
desktop ? cn('w-full', pinned || expanded ? 'h-full' : '', pinned ? (mode === 'left' ? 'border-r' : 'border-l') : 'rounded-lg border') : expanded ? 'h-full w-full' : 'w-full max-w-xl rounded-lg border',
|
||||
dragging && 'z-50 opacity-90',
|
||||
)"
|
||||
>
|
||||
<template v-if="desktop && !pinned">
|
||||
<div
|
||||
v-for="dir in visibleDirs"
|
||||
:key="dir"
|
||||
role="separator"
|
||||
tabindex="0"
|
||||
aria-label="Resize chat"
|
||||
:title="`Resize from the ${DIR_LABEL[dir]} edge. Arrow keys resize; Shift changes faster.`"
|
||||
:aria-orientation="handleOrientation(dir)"
|
||||
:aria-valuenow="handleValue(dir, winRect)"
|
||||
:aria-valuemin="dir === 'n' || dir === 's' ? MIN_H : MIN_W"
|
||||
:aria-valuemax="dir === 'n' || dir === 's' ? vh : vw"
|
||||
:data-resize="dir"
|
||||
:class="cn('absolute z-10 touch-none hover:bg-primary/30 focus-visible:bg-primary/50', HANDLE_CLASS[dir])"
|
||||
@keydown="onHandleKey(dir, $event)"
|
||||
/>
|
||||
</template>
|
||||
<div
|
||||
v-if="desktop && pinned"
|
||||
role="separator"
|
||||
aria-orientation="vertical"
|
||||
aria-label="Resize chat"
|
||||
tabindex="0"
|
||||
:aria-valuenow="pinW"
|
||||
:aria-valuemin="MIN_W"
|
||||
:aria-valuemax="pinMax"
|
||||
data-resize="pin"
|
||||
class="absolute inset-y-0 z-10 w-1.5 cursor-col-resize touch-none hover:bg-primary/30 focus-visible:bg-primary/50"
|
||||
:class="mode === 'left' ? '-right-0.5' : '-left-0.5'"
|
||||
@keydown="onPinKey"
|
||||
/>
|
||||
<div
|
||||
v-if="expanded"
|
||||
ref="header"
|
||||
:class="cn('touch-none', desktop && 'cursor-grab select-none active:cursor-grabbing')"
|
||||
@dblclick="togglePin"
|
||||
>
|
||||
<ChatBar>
|
||||
<template v-if="desktop" #start>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="flex-none cursor-grab touch-none active:cursor-grabbing"
|
||||
data-move-handle
|
||||
aria-label="Move chat"
|
||||
title="Drag to move. Arrow keys move; Shift moves further."
|
||||
@keydown="moveByKey"
|
||||
>
|
||||
<GripVertical />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Move chat</TooltipContent>
|
||||
</Tooltip>
|
||||
</template>
|
||||
<template v-if="desktop" #actions>
|
||||
<DropdownMenu v-model:open="positionOpen">
|
||||
<!-- No Tooltip around the trigger: nested in TooltipTrigger the menu
|
||||
loses its anchor and opens off-screen, as MoreMenu found. -->
|
||||
<DropdownMenuTrigger as-child>
|
||||
<Button variant="ghost" size="icon-sm" class="flex-none" aria-label="Chat position" title="Position">
|
||||
<component :is="MODES.find((m) => m.mode === mode)?.icon ?? PictureInPicture2" />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" class="min-w-36">
|
||||
<DropdownMenuRadioGroup :model-value="mode" @update:model-value="setMode($event as DockMode)">
|
||||
<DropdownMenuRadioItem v-for="m in MODES" :key="m.mode" :value="m.mode">
|
||||
<component :is="m.icon" />{{ m.label }}
|
||||
</DropdownMenuRadioItem>
|
||||
</DropdownMenuRadioGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</template>
|
||||
<template #end>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="flex-none"
|
||||
aria-label="Hide conversation"
|
||||
@click="expanded = false"
|
||||
>
|
||||
<ChevronDown />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Hide conversation</TooltipContent>
|
||||
</Tooltip>
|
||||
</template>
|
||||
</ChatBar>
|
||||
</div>
|
||||
<div
|
||||
v-if="expanded"
|
||||
class="flex min-h-0 flex-1 flex-col"
|
||||
>
|
||||
<ChatTranscript />
|
||||
<ChatPending />
|
||||
</div>
|
||||
<div ref="bar" class="touch-none" @focusin="expanded = true">
|
||||
<ChatComposer :open="false" :flat="!expanded">
|
||||
<template v-if="!expanded && desktop" #start>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="cursor-grab touch-none active:cursor-grabbing"
|
||||
data-move-handle
|
||||
aria-label="Move chat"
|
||||
title="Drag to move. Arrow keys move; Shift moves further."
|
||||
@keydown="moveByKey"
|
||||
>
|
||||
<GripVertical />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Move chat</TooltipContent>
|
||||
</Tooltip>
|
||||
</template>
|
||||
<template v-if="!expanded" #actions>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
:class="cn(unseenCount && 'w-auto gap-1 px-2')"
|
||||
:aria-label="unseenCount ? `Show conversation, ${unseenCount} new` : 'Show conversation'"
|
||||
@click="expanded = true"
|
||||
>
|
||||
<ChevronUp />
|
||||
<Badge v-if="unseenCount" variant="default" aria-hidden="true">{{ unseenCount }}</Badge>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Show conversation</TooltipContent>
|
||||
</Tooltip>
|
||||
</template>
|
||||
</ChatComposer>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,197 +0,0 @@
|
||||
/**
|
||||
* Geometry and persistence for the chat dock window. The dock floats freely on
|
||||
* desktop-width screens: the header drags it anywhere, eight edges and corners
|
||||
* resize it, and dragging near a side edge offers the pinned split, which
|
||||
* reflows the page. On phone-width screens it stays a full-width bottom bar,
|
||||
* riding above the on-screen keyboard. Pure functions live here so the
|
||||
* placement rules are testable without a DOM; ChatDock.vue owns the pointer
|
||||
* and keyboard events.
|
||||
*/
|
||||
|
||||
export type DockMode = "left" | "float" | "right";
|
||||
|
||||
export interface Rect {
|
||||
x: number;
|
||||
y: number;
|
||||
w: number;
|
||||
h: number;
|
||||
}
|
||||
|
||||
export interface DockLayout extends Rect {
|
||||
mode: DockMode;
|
||||
}
|
||||
|
||||
export const DOCK_STORAGE_KEY = "archie.chat.dock.v2";
|
||||
export const LEGACY_DOCK_STORAGE_KEY = "archie.chat.dock";
|
||||
|
||||
export const MIN_W = 320;
|
||||
export const MIN_H = 280;
|
||||
export const MAX_W = 720;
|
||||
/** The minimised bar is at least this wide, screen permitting. */
|
||||
export const BAR_W = 640;
|
||||
/** Margin kept between a floating window and the viewport edge. */
|
||||
export const INSET = 8;
|
||||
/** Pointer distance from a side edge that offers the snap preview. */
|
||||
const EDGE = 64;
|
||||
/** Pointer travel before a press on a drag surface becomes a drag. */
|
||||
export const DRAG_START = 4;
|
||||
const KEY_STEP = 10;
|
||||
const KEY_STEP_FAST = 40;
|
||||
|
||||
export const RESIZE_DIRS = ["n", "s", "e", "w", "ne", "nw", "se", "sw"] as const;
|
||||
export type ResizeDir = (typeof RESIZE_DIRS)[number];
|
||||
|
||||
function clamp(value: number, min: number, max: number): number {
|
||||
return Math.min(Math.max(value, min), Math.max(min, max));
|
||||
}
|
||||
|
||||
export function defaultLayout(vw: number, vh: number): DockLayout {
|
||||
const w = Math.min(440, Math.max(MIN_W, vw - INSET * 2));
|
||||
const h = Math.min(560, Math.max(MIN_H, vh - INSET * 2));
|
||||
return { mode: "float", x: Math.max(INSET, vw - w - 24), y: Math.max(INSET, vh - h - 24), w, h };
|
||||
}
|
||||
|
||||
/** Largest width a floating window may take in this viewport. */
|
||||
export function windowWidth(w: number, vw: number): number {
|
||||
return clamp(w, MIN_W, Math.max(MIN_W, Math.min(MAX_W, vw - INSET * 2)));
|
||||
}
|
||||
|
||||
/** Largest width the pinned split may take, leaving the page room to reflow. */
|
||||
export function pinnedWidth(w: number, vw: number): number {
|
||||
return clamp(w, MIN_W, Math.max(MIN_W, Math.min(MAX_W, vw - 480)));
|
||||
}
|
||||
|
||||
/** Clamp a rectangle into the viewport, keeping its size within the minimums. */
|
||||
export function fitRect<T extends Rect>(rect: T, vw: number, vh: number, inset = INSET): T {
|
||||
const availW = Math.max(1, vw - inset * 2);
|
||||
const availH = Math.max(1, vh - inset * 2);
|
||||
const w = clamp(rect.w, Math.min(MIN_W, availW), Math.min(MAX_W, availW));
|
||||
const h = clamp(rect.h, Math.min(MIN_H, availH), availH);
|
||||
return {
|
||||
...rect,
|
||||
x: clamp(rect.x, inset, vw - w - inset),
|
||||
y: clamp(rect.y, inset, vh - h - inset),
|
||||
w,
|
||||
h,
|
||||
};
|
||||
}
|
||||
|
||||
/** Validate a stored value, filling any missing field from the defaults. */
|
||||
export function normalizeLayout(raw: unknown, vw: number, vh: number): DockLayout {
|
||||
const d = defaultLayout(vw, vh);
|
||||
if (!raw || typeof raw !== "object") return d;
|
||||
const o = raw as Partial<Record<keyof DockLayout, unknown>>;
|
||||
const mode: DockMode = o.mode === "left" || o.mode === "right" || o.mode === "float" ? o.mode : "float";
|
||||
const num = (value: unknown, fallback: number): number =>
|
||||
typeof value === "number" && Number.isFinite(value) ? value : fallback;
|
||||
return fitRect(
|
||||
{ mode, x: num(o.x, d.x), y: num(o.y, d.y), w: num(o.w, d.w), h: num(o.h, d.h) },
|
||||
vw,
|
||||
vh,
|
||||
);
|
||||
}
|
||||
|
||||
/** Resize a rectangle from one of the eight edges/corners by a pointer delta. */
|
||||
export function resizeRect(origin: Rect, dir: ResizeDir, dx: number, dy: number, vw: number, vh: number): Rect {
|
||||
const rect = { ...origin };
|
||||
const minW = Math.min(MIN_W, Math.max(1, vw - INSET * 2));
|
||||
const minH = Math.min(MIN_H, Math.max(1, vh - INSET * 2));
|
||||
if (dir.includes("e")) rect.w = clamp(origin.w + dx, minW, Math.max(minW, vw - origin.x - INSET));
|
||||
if (dir.includes("s")) rect.h = clamp(origin.h + dy, minH, Math.max(minH, vh - origin.y - INSET));
|
||||
if (dir.includes("w")) {
|
||||
rect.x = clamp(origin.x + dx, INSET, origin.x + origin.w - minW);
|
||||
rect.w = origin.x + origin.w - rect.x;
|
||||
}
|
||||
if (dir.includes("n")) {
|
||||
rect.y = clamp(origin.y + dy, INSET, origin.y + origin.h - minH);
|
||||
rect.h = origin.y + origin.h - rect.y;
|
||||
}
|
||||
return rect;
|
||||
}
|
||||
|
||||
/** The pinned side a pointer near an edge would commit to on release. */
|
||||
export function snapEdge(pointerX: number, vw: number, edge = EDGE): "left" | "right" | null {
|
||||
if (pointerX <= edge) return "left";
|
||||
if (pointerX >= vw - edge) return "right";
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the minimised bar sits: docked at the bottom of the screen, under the
|
||||
* window's horizontal position or on the side the mode pins to. Returned as a
|
||||
* bottom offset so the bar's own height never has to be known here.
|
||||
*/
|
||||
export function barPlacement(rect: Rect, mode: DockMode, vw: number): { x: number; bottom: number; w: number } {
|
||||
const w = Math.max(rect.w, Math.min(BAR_W, vw - INSET * 2));
|
||||
const x = mode === "left" ? 0 : mode === "right" ? Math.max(0, vw - w) : clamp(rect.x, INSET, Math.max(INSET, vw - w - INSET));
|
||||
return { x, bottom: INSET, w };
|
||||
}
|
||||
|
||||
/** Pointer travel down on the header that hides the conversation on a phone. */
|
||||
export const SWIPE = 48;
|
||||
|
||||
/**
|
||||
* How much of the layout viewport the on-screen keyboard covers, 0 when there
|
||||
* is none. Fixed elements stay anchored to the layout viewport, so the phone
|
||||
* bar offsets by this to ride above the keyboard.
|
||||
*/
|
||||
export function keyboardCover(innerHeight: number, vv: { height: number; offsetTop: number } | null): number {
|
||||
return vv ? Math.max(0, Math.round(innerHeight - vv.height - vv.offsetTop)) : 0;
|
||||
}
|
||||
|
||||
/** The phone bar's bottom offset: above the keyboard while one is up, else the safe area. */
|
||||
export function phoneBarBottom(keyboard: number): string {
|
||||
return keyboard > 0 ? `${keyboard + 8}px` : "max(0.5rem, env(safe-area-inset-bottom))";
|
||||
}
|
||||
|
||||
/** The old { side, width } dock preference, as a partial new layout. */
|
||||
export function legacyLayout(raw: unknown): Partial<DockLayout> | null {
|
||||
if (!raw || typeof raw !== "object") return null;
|
||||
const o = raw as Record<string, unknown>;
|
||||
const partial: Partial<DockLayout> = { mode: o.side === "left" || o.side === "right" ? o.side : "float" };
|
||||
if (typeof o.width === "number" && Number.isFinite(o.width)) partial.w = o.width;
|
||||
return partial;
|
||||
}
|
||||
|
||||
export interface StorageLike {
|
||||
getItem(key: string): string | null;
|
||||
setItem(key: string, value: string): void;
|
||||
removeItem(key: string): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Move the old "archie.chat.dock" preference into the new key (the side becomes
|
||||
* the mode, the width the window width) and drop the old key either way: the
|
||||
* new key deliberately replaces it.
|
||||
*/
|
||||
export function migrateDockStorage(storage: StorageLike, vw: number, vh: number): void {
|
||||
try {
|
||||
const legacy = storage.getItem(LEGACY_DOCK_STORAGE_KEY);
|
||||
if (storage.getItem(DOCK_STORAGE_KEY) === null && legacy !== null) {
|
||||
let parsed: unknown = null;
|
||||
try {
|
||||
parsed = JSON.parse(legacy);
|
||||
} catch {
|
||||
parsed = null;
|
||||
}
|
||||
storage.setItem(DOCK_STORAGE_KEY, JSON.stringify(normalizeLayout(legacyLayout(parsed) ?? {}, vw, vh)));
|
||||
}
|
||||
if (legacy !== null) storage.removeItem(LEGACY_DOCK_STORAGE_KEY);
|
||||
} catch {
|
||||
// Unwritable storage leaves the dock at its defaults for this visit.
|
||||
}
|
||||
}
|
||||
|
||||
export function keyStep(fast: boolean): number {
|
||||
return fast ? KEY_STEP_FAST : KEY_STEP;
|
||||
}
|
||||
|
||||
/** The separator orientation announced for a resize handle. */
|
||||
export function handleOrientation(dir: ResizeDir): "horizontal" | "vertical" {
|
||||
return dir === "e" || dir === "w" ? "vertical" : "horizontal";
|
||||
}
|
||||
|
||||
/** The size a resize handle announces: its height on the north/south edges, else its width. */
|
||||
export function handleValue(dir: ResizeDir, rect: Rect): number {
|
||||
return dir === "n" || dir === "s" ? Math.round(rect.h) : Math.round(rect.w);
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { RouterLink } from "vue-router";
|
||||
|
||||
import Logo from "@/components/topbar/Logo.vue";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import ChatSuggestions from "./ChatSuggestions.vue";
|
||||
import { chatModelReady } from "./state";
|
||||
|
||||
/**
|
||||
* What the panel opens on before there is a conversation: the mark, a greeting
|
||||
* and the prompts for this page. Once the conversation has messages the
|
||||
* prompts move beside the composer.
|
||||
*/
|
||||
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="w-full self-center justify-self-center px-1 py-6">
|
||||
<div aria-hidden="true" class="mb-4 flex justify-center">
|
||||
<Logo :open="false" class="text-[4rem]!" />
|
||||
</div>
|
||||
<h2 class="mb-5 text-center text-xl font-semibold tracking-tight">How can I help?</h2>
|
||||
<ChatSuggestions v-if="chatModelReady" list />
|
||||
<Alert v-else class="text-label">
|
||||
<AlertDescription class="flex flex-wrap items-center justify-between gap-2">
|
||||
No agent model is set.
|
||||
<Button as-child variant="outline" size="sm"><RouterLink to="/settings" class="no-underline">Choose a model</RouterLink></Button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,35 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import type { ChatInline } from "./markdown";
|
||||
|
||||
/** One inline run: the spans of a paragraph, a heading or a table cell. */
|
||||
defineProps<{ inline: ChatInline[] }>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<template v-for="(span, i) in inline" :key="i">
|
||||
<img
|
||||
v-if="span.kind === 'image'"
|
||||
:src="span.src"
|
||||
:alt="span.alt"
|
||||
loading="lazy"
|
||||
class="my-1 block max-h-96 max-w-full cursor-pointer rounded-md border border-border bg-card object-contain"
|
||||
/>
|
||||
<del v-else-if="span.kind === 'del'">{{ span.text }}</del>
|
||||
<strong v-else-if="span.kind === 'strong'">{{ span.text }}</strong>
|
||||
<code
|
||||
v-else-if="span.kind === 'code'"
|
||||
class="rounded bg-foreground/10 px-1 py-0.5 font-mono text-[0.9em]"
|
||||
>{{ span.text }}</code
|
||||
>
|
||||
<a
|
||||
v-else-if="span.kind === 'link'"
|
||||
:href="span.href"
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
class="text-link underline-offset-4 hover:underline"
|
||||
>{{ span.text }}</a
|
||||
>
|
||||
<em v-else-if="span.kind === 'em'">{{ span.text }}</em>
|
||||
<template v-else>{{ span.text }}</template>
|
||||
</template>
|
||||
</template>
|
||||
@@ -1,45 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ArrowDownIcon } from "@lucide/vue";
|
||||
import { computed, onMounted, onUnmounted, ref, watch } from "vue";
|
||||
|
||||
import { MessageScrollerButton, useMessageScrollerScrollable } from "@/components/ui/message-scroller";
|
||||
import { setAtEnd, unseenCount } from "./unseen";
|
||||
|
||||
/**
|
||||
* The scroller's jump-to-latest button. It reads where the reader is for the
|
||||
* unseen count and says how many replies are waiting below.
|
||||
*
|
||||
* The scroller measures on the frames after it mounts, and until then it
|
||||
* reports "not scrollable", which would look like the end. The reader counts
|
||||
* as at the end only once it has measured.
|
||||
*/
|
||||
const scrollable = useMessageScrollerScrollable();
|
||||
const measured = ref(false);
|
||||
let frame = 0;
|
||||
onMounted(() => {
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = requestAnimationFrame(() => {
|
||||
measured.value = true;
|
||||
});
|
||||
});
|
||||
});
|
||||
onUnmounted(() => {
|
||||
cancelAnimationFrame(frame);
|
||||
setAtEnd(false);
|
||||
});
|
||||
watch(
|
||||
() => measured.value && !scrollable.value.end,
|
||||
(end) => setAtEnd(end),
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const label = computed(() => `${unseenCount.value} new ${unseenCount.value === 1 ? "reply" : "replies"}`);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<MessageScrollerButton :size="unseenCount ? 'sm' : 'icon-sm'" :class="unseenCount ? 'gap-1.5 whitespace-nowrap' : undefined">
|
||||
<ArrowDownIcon />
|
||||
<template v-if="unseenCount">{{ label }}</template>
|
||||
<span v-else class="sr-only">Scroll to end</span>
|
||||
</MessageScrollerButton>
|
||||
</template>
|
||||
@@ -1,100 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
|
||||
import CodeView from "@/base/CodeView.vue";
|
||||
import ChatInline from "./ChatInline.vue";
|
||||
import { parseMarkdown } from "./markdown";
|
||||
|
||||
/**
|
||||
* A reply rendered as semantic HTML: headings, lists, quotes, fenced code,
|
||||
* tables, inline emphasis. The parse is a computed, so a reply that grows a
|
||||
* token at a time re-renders from the text it now has rather than accumulating
|
||||
* markup.
|
||||
*/
|
||||
const props = defineProps<{ text: string }>();
|
||||
|
||||
const blocks = computed(() => parseMarkdown(props.text));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="[overflow-wrap:anywhere]">
|
||||
<template v-for="(block, i) in blocks" :key="i">
|
||||
<CodeView v-if="block.kind === 'pre'" :code="block.code" :lang="block.lang" class="my-2" />
|
||||
|
||||
<table
|
||||
v-else-if="block.kind === 'table'"
|
||||
class="my-3 w-full border-collapse text-[0.92em]"
|
||||
>
|
||||
<thead>
|
||||
<tr>
|
||||
<th
|
||||
v-for="(cell, c) in block.head"
|
||||
:key="c"
|
||||
class="border border-border bg-muted px-2 py-1.5 text-left font-semibold"
|
||||
>
|
||||
<ChatInline :inline="cell" />
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="(row, r) in block.rows" :key="r">
|
||||
<td
|
||||
v-for="(cell, c) in row"
|
||||
:key="c"
|
||||
class="border border-border px-2 py-1.5 text-left"
|
||||
>
|
||||
<ChatInline :inline="cell" />
|
||||
</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
<blockquote
|
||||
v-else-if="block.kind === 'blockquote'"
|
||||
class="my-2 border-l-[3px] border-primary pl-3 text-fg-muted"
|
||||
>
|
||||
<ChatInline :inline="block.inline" />
|
||||
</blockquote>
|
||||
|
||||
<h1
|
||||
v-else-if="block.kind === 'h1'"
|
||||
class="mt-1 mb-2 text-xl leading-tight font-semibold tracking-[-0.02em]"
|
||||
>
|
||||
<ChatInline :inline="block.inline" />
|
||||
</h1>
|
||||
<h2
|
||||
v-else-if="block.kind === 'h2'"
|
||||
class="mt-1 mb-2 text-lg leading-tight font-semibold tracking-[-0.02em]"
|
||||
>
|
||||
<ChatInline :inline="block.inline" />
|
||||
</h2>
|
||||
<h3
|
||||
v-else-if="block.kind === 'h3'"
|
||||
class="mt-1 mb-2 text-base leading-tight font-semibold tracking-[-0.02em]"
|
||||
>
|
||||
<ChatInline :inline="block.inline" />
|
||||
</h3>
|
||||
|
||||
<ul
|
||||
v-else-if="block.kind === 'ul'"
|
||||
class="my-2.5 flex list-disc flex-col gap-1 pl-5"
|
||||
>
|
||||
<li v-for="(item, n) in block.items" :key="n">
|
||||
<ChatInline :inline="item" />
|
||||
</li>
|
||||
</ul>
|
||||
<ol
|
||||
v-else-if="block.kind === 'ol'"
|
||||
class="my-2.5 flex list-decimal flex-col gap-1 pl-5"
|
||||
>
|
||||
<li v-for="(item, n) in block.items" :key="n">
|
||||
<ChatInline :inline="item" />
|
||||
</li>
|
||||
</ol>
|
||||
|
||||
<p v-else-if="block.kind === 'p'" class="mb-2.5 last:mb-0">
|
||||
<ChatInline :inline="block.inline" />
|
||||
</p>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,26 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ArrowUpRight } from "@lucide/vue";
|
||||
|
||||
/**
|
||||
* A dashboard_navigate result: a clickable chip that routes the operator to a
|
||||
* dashboard page. It is an action, not evidence, so it is styled as a button
|
||||
* rather than a muted log line, and it visibly invites a click. It is the only
|
||||
* clickable navigation surface in the transcript.
|
||||
*
|
||||
* A RouterLink rather than a `#/path` anchor: history routing means the server
|
||||
* stores bare paths, and an anchor would reload the whole app to change one
|
||||
* segment.
|
||||
*/
|
||||
defineProps<{ path: string; label?: string }>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<RouterLink
|
||||
:to="path"
|
||||
:title="`Go to ${label || path}`"
|
||||
class="inline-flex max-w-full items-center gap-1.5 rounded-md border border-primary/45 bg-primary-soft px-2.5 py-1 text-caption font-semibold text-link transition-colors hover:border-primary hover:bg-primary/15 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-primary"
|
||||
>
|
||||
<ArrowUpRight aria-hidden="true" class="size-3.5 shrink-0" />
|
||||
<span class="truncate">{{ label || path }}</span>
|
||||
</RouterLink>
|
||||
</template>
|
||||
@@ -1,82 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ArrowUpRight, ChevronDown, ClipboardCheck, MessageSquare, Radio } from "@lucide/vue";
|
||||
import { onMounted, ref } from "vue";
|
||||
import { RouterLink } from "vue-router";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
||||
import { Item, ItemActions, ItemContent, ItemMedia, ItemTitle } from "@/components/ui/item";
|
||||
import { Timestamp } from "@/components/ui/timestamp";
|
||||
import type { Message } from "../api";
|
||||
import ChatApprovalCard from "./ChatApprovalCard.vue";
|
||||
import { conversationOf, selectSession } from "./state";
|
||||
|
||||
/**
|
||||
* A message from a run in the conversation: a notification, an approval
|
||||
* request with its Approve and Deny, or the answer one got. A request a
|
||||
* conversation asked links back to that conversation rather than to a run.
|
||||
*/
|
||||
const props = defineProps<{ notice: Message }>();
|
||||
|
||||
const askedBy = ref<{ session: string } | null>(null);
|
||||
const resolved = ref(false);
|
||||
|
||||
onMounted(async () => {
|
||||
if (props.notice.run_id) {
|
||||
const session = await conversationOf(props.notice.run_id);
|
||||
askedBy.value = session ? { session } : null;
|
||||
}
|
||||
resolved.value = true;
|
||||
});
|
||||
|
||||
const icons = { notification: Radio, approval_request: Radio, approval_answer: ClipboardCheck };
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ChatApprovalCard
|
||||
v-if="notice.kind === 'approval_request' && notice.request_id"
|
||||
:request-id="notice.request_id"
|
||||
:action="notice.title"
|
||||
:summary="notice.body"
|
||||
:run-id="notice.run_id"
|
||||
/>
|
||||
<Item v-else variant="outline" size="sm" class="items-start" role="group" :aria-label="notice.title">
|
||||
<ItemMedia variant="icon" class="mt-0.5 text-muted-foreground"><component :is="icons[notice.kind]" aria-hidden="true" /></ItemMedia>
|
||||
<ItemContent class="min-w-0">
|
||||
<div class="flex flex-wrap items-baseline justify-between gap-x-3">
|
||||
<ItemTitle class="w-auto min-w-0 break-words">{{ notice.title }}</ItemTitle>
|
||||
<Timestamp :at="notice.created_at" class="text-caption text-muted-foreground" />
|
||||
</div>
|
||||
<Collapsible v-if="notice.body || notice.attempts?.length" v-slot="{ open }">
|
||||
<CollapsibleTrigger as-child>
|
||||
<Button variant="ghost" size="xs" class="-ml-2" :aria-label="`${open ? 'Hide' : 'View'} details for ${notice.title}`">
|
||||
{{ open ? "Hide details" : "View details" }}
|
||||
<ChevronDown :class="open && 'rotate-180'" aria-hidden="true" data-icon="inline-end" />
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent class="mt-1 rounded-lg bg-muted/50 p-3">
|
||||
<p v-if="notice.body" class="whitespace-pre-wrap break-words leading-relaxed">{{ notice.body }}</p>
|
||||
<ul v-if="notice.attempts?.length" class="mt-2 flex flex-col gap-1 text-caption">
|
||||
<li v-for="a in notice.attempts" :key="`${a.channel}:${a.attempt}`" class="flex flex-wrap items-center gap-2">
|
||||
<span class="font-medium">{{ a.channel }}</span>
|
||||
<span class="text-muted-foreground">Attempt {{ a.attempt }}</span>
|
||||
<Badge :variant="a.ok ? 'secondary' : 'danger'">{{ a.ok ? "Delivered" : "Failed" }}</Badge>
|
||||
<span v-if="a.error" class="break-all text-destructive">{{ a.error }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</ItemContent>
|
||||
<ItemActions v-if="notice.run_id && resolved">
|
||||
<Button v-if="askedBy" variant="link" size="sm" @click="selectSession(askedBy.session)">
|
||||
<MessageSquare aria-hidden="true" data-icon="inline-start" />Open conversation
|
||||
</Button>
|
||||
<Button v-else variant="link" size="sm" as-child>
|
||||
<RouterLink :to="{ name: 'run', params: { id: notice.run_id } }" :aria-label="`View run for ${notice.title}`"
|
||||
>View run <ArrowUpRight aria-hidden="true" data-icon="inline-end"
|
||||
/></RouterLink>
|
||||
</Button>
|
||||
</ItemActions>
|
||||
</Item>
|
||||
</template>
|
||||
@@ -1,38 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ChevronDown, ShieldAlert } from "@lucide/vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
|
||||
import { ReadError } from "@/components/ui/read-error";
|
||||
import ChatApprovalCard from "./ChatApprovalCard.vue";
|
||||
import { approvalReadFailed, loadApprovals, otherApprovals } from "./state";
|
||||
|
||||
/**
|
||||
* Approvals waiting for an answer that the open conversation doesn't show,
|
||||
* such as one a run asked before this conversation began, so none is out of
|
||||
* reach from the chat.
|
||||
*/
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ReadError v-if="approvalReadFailed" class="mx-3 mt-2" message="Couldn't load pending approvals." retry-label="Retry" @retry="loadApprovals" />
|
||||
<Collapsible v-else-if="otherApprovals.length" v-slot="{ open }" class="border-t px-3 pt-2">
|
||||
<CollapsibleTrigger as-child>
|
||||
<Button variant="ghost" size="sm" class="w-full justify-start text-warn">
|
||||
<ShieldAlert aria-hidden="true" data-icon="inline-start" />
|
||||
{{ otherApprovals.length }} awaiting approval
|
||||
<ChevronDown :class="['ml-auto', open && 'rotate-180']" aria-hidden="true" />
|
||||
</Button>
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent class="flex max-h-[30dvh] flex-col overflow-y-auto pb-1">
|
||||
<ChatApprovalCard
|
||||
v-for="request in otherApprovals"
|
||||
:key="request.id"
|
||||
:request-id="request.id"
|
||||
:action="request.action"
|
||||
:summary="request.summary"
|
||||
:run-id="request.run_id"
|
||||
/>
|
||||
</CollapsibleContent>
|
||||
</Collapsible>
|
||||
</template>
|
||||
@@ -1,159 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { Copy, Ellipsis, Pencil, RotateCw, Trash2 } from "@lucide/vue";
|
||||
import { ref } from "vue";
|
||||
import { toast } from "vue-sonner";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import {
|
||||
Popover,
|
||||
PopoverAnchor,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@/components/ui/popover";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import ChatSettings from "./ChatSettings.vue";
|
||||
import { currentSession, deleteSession, messages, renameSession, retryLast, useEscapeLayer } from "./state";
|
||||
|
||||
/**
|
||||
* The menu behind the bar's one "more" button: what acts on the conversation
|
||||
* itself rather than on what is being said (send the last message again,
|
||||
* rename, copy or delete the conversation), then the model it runs on. Each
|
||||
* is also a slash command. The popover closes as the action goes, because its
|
||||
* outcome shows in the transcript, not in the menu.
|
||||
*/
|
||||
const open = ref(false);
|
||||
useEscapeLayer(open);
|
||||
|
||||
function retry(): void {
|
||||
open.value = false;
|
||||
void retryLast();
|
||||
}
|
||||
|
||||
// Reply text is already Markdown, so the transcript is the messages under a
|
||||
// heading per speaker. Empty turns (tool-only replies) have nothing to paste.
|
||||
async function copyMarkdown(): Promise<void> {
|
||||
open.value = false;
|
||||
const text = messages.value
|
||||
.map((m) => {
|
||||
const body = m.notice ? `${m.notice.title}\n\n${m.notice.body}`.trim() : m.text.trim();
|
||||
if (!body) return "";
|
||||
return `### ${m.from === "web" ? "You" : "Archie"}\n\n${body}`;
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
if (!text) {
|
||||
toast.error("Nothing to copy yet.");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
} catch (err) {
|
||||
toast.error(`Couldn't copy: ${err instanceof Error ? err.message : "the clipboard is unavailable"}`);
|
||||
return;
|
||||
}
|
||||
toast.success("Copied as Markdown");
|
||||
}
|
||||
|
||||
// Rename asks for the title in a labelled dialog, not window.prompt; delete
|
||||
// asks to confirm, since it can't be undone.
|
||||
const promptOpen = ref(false);
|
||||
const confirmOpen = ref(false);
|
||||
// A dialog owns Escape while open, so closing it leaves the dock open.
|
||||
useEscapeLayer(promptOpen);
|
||||
useEscapeLayer(confirmOpen);
|
||||
const promptValue = ref("");
|
||||
function rename(): void {
|
||||
open.value = false;
|
||||
promptValue.value = "";
|
||||
promptOpen.value = true;
|
||||
}
|
||||
function submitPrompt(): void {
|
||||
const value = promptValue.value.trim();
|
||||
promptOpen.value = false;
|
||||
if (value) void renameSession(value);
|
||||
}
|
||||
function confirmDelete(): void {
|
||||
open.value = false;
|
||||
confirmOpen.value = true;
|
||||
}
|
||||
function remove(): void {
|
||||
confirmOpen.value = false;
|
||||
void deleteSession();
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Popover v-model:open="open">
|
||||
<!-- The anchor sits outside the tooltip chain on purpose: nested inside
|
||||
TooltipTrigger, the popper anchor ref resolves to a component object
|
||||
rather than the button, the content is never positioned, and the menu
|
||||
stays parked off-screen. -->
|
||||
<PopoverAnchor as-child>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<PopoverTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon-sm"
|
||||
class="flex-none"
|
||||
aria-label="More"
|
||||
>
|
||||
<Ellipsis />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>More</TooltipContent>
|
||||
</Tooltip>
|
||||
</PopoverAnchor>
|
||||
<PopoverContent align="end" class="grid w-64 gap-0.5 p-1">
|
||||
<template v-if="currentSession">
|
||||
<Button variant="ghost" size="sm" class="justify-start" @click="retry"
|
||||
><RotateCw data-icon="inline-start" />Retry</Button
|
||||
>
|
||||
<Button variant="ghost" size="sm" class="justify-start" @click="rename"
|
||||
><Pencil data-icon="inline-start" />Rename</Button
|
||||
>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="justify-start"
|
||||
@click="copyMarkdown"
|
||||
><Copy data-icon="inline-start" />Copy as Markdown</Button
|
||||
>
|
||||
<Button variant="ghost" size="sm" class="justify-start text-destructive" @click="confirmDelete"
|
||||
><Trash2 data-icon="inline-start" />Delete</Button
|
||||
>
|
||||
<Separator class="my-1" />
|
||||
</template>
|
||||
<ChatSettings />
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
<Dialog :open="promptOpen" @update:open="(v: boolean) => (promptOpen = v)">
|
||||
<DialogContent>
|
||||
<DialogHeader><DialogTitle>Rename conversation</DialogTitle></DialogHeader>
|
||||
<Input v-model="promptValue" aria-label="Title" maxlength="120" @keydown.enter.prevent="submitPrompt" />
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" @click="promptOpen = false">Cancel</Button>
|
||||
<Button :disabled="!promptValue.trim()" @click="submitPrompt">Rename</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<Dialog :open="confirmOpen" @update:open="(v: boolean) => (confirmOpen = v)">
|
||||
<DialogContent>
|
||||
<DialogHeader><DialogTitle>Delete this conversation?</DialogTitle></DialogHeader>
|
||||
<DialogFooter>
|
||||
<Button variant="ghost" @click="confirmOpen = false">Cancel</Button>
|
||||
<Button variant="destructive" @click="remove">Delete</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</template>
|
||||
@@ -1,70 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { Check, History, SquarePen, X } from "@lucide/vue";
|
||||
import { onMounted, ref } from "vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { sessionTitle } from "./session";
|
||||
import { currentSession, newChat, selectSession, sessions } from "./state";
|
||||
|
||||
/**
|
||||
* The conversation drawer the bar's menu button opens over the panel: a new
|
||||
* conversation first, then every conversation to switch to. It covers the
|
||||
* panel rather than dropping down, so long titles get the panel's width.
|
||||
*/
|
||||
const emit = defineEmits<{ close: [] }>();
|
||||
|
||||
// Focus moves into the drawer, so Escape and Tab act on it straight away. The
|
||||
// drawer itself takes it, not its first button, whose tooltip would open.
|
||||
const nav = ref<HTMLElement | null>(null);
|
||||
onMounted(() => nav.value?.focus());
|
||||
|
||||
function choose(id: string): void {
|
||||
selectSession(id);
|
||||
emit("close");
|
||||
}
|
||||
|
||||
function start(): void {
|
||||
newChat();
|
||||
emit("close");
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<nav
|
||||
ref="nav"
|
||||
tabindex="-1"
|
||||
aria-label="Conversations"
|
||||
class="outline-none absolute inset-0 z-20 flex flex-col gap-0.5 overflow-y-auto rounded-[inherit] bg-popover p-2"
|
||||
@pointerdown.stop
|
||||
@dblclick.stop
|
||||
@keydown.esc.stop.prevent="emit('close')"
|
||||
>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="ghost" size="icon-sm" class="mb-1" aria-label="Close conversations" @click="emit('close')">
|
||||
<X />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Close</TooltipContent>
|
||||
</Tooltip>
|
||||
<Button variant="ghost" size="sm" class="justify-start" @click="start">
|
||||
<SquarePen data-icon="inline-start" />New chat
|
||||
</Button>
|
||||
<div class="mt-2 flex items-center gap-2 px-2 py-1 text-caption text-fg-muted">
|
||||
<History class="size-3.5" aria-hidden="true" />Chats
|
||||
</div>
|
||||
<Button
|
||||
v-for="session in sessions"
|
||||
:key="session.session_id"
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
class="justify-start pl-7 font-normal"
|
||||
:aria-current="session.session_id === currentSession ? 'true' : undefined"
|
||||
@click="choose(session.session_id)"
|
||||
>
|
||||
<span class="min-w-0 flex-1 truncate text-left">{{ sessionTitle(session) }}</span>
|
||||
<Check v-if="session.session_id === currentSession" class="flex-none" aria-hidden="true" />
|
||||
</Button>
|
||||
</nav>
|
||||
</template>
|
||||
@@ -1,21 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { RouterLink } from "vue-router";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { activeModel, modelError, statusText } from "./state";
|
||||
|
||||
/**
|
||||
* What the panel is doing right now and the model that answers. The model is
|
||||
* the organisation's agent model, set in Settings like every agent's.
|
||||
*/
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="grid gap-1 p-1 text-label">
|
||||
<span v-if="statusText !== 'Ready'" class="text-caption text-fg-subtle">{{ statusText }}</span>
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<span class="min-w-0 truncate" :class="!activeModel && 'text-fg-muted'">{{ activeModel || modelError || "No agent model" }}</span>
|
||||
<Button variant="link" size="sm" as-child><RouterLink to="/settings">Change</RouterLink></Button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,71 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, ref, watch } from "vue";
|
||||
|
||||
import { commandScrollTop } from "./command-scroll";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { Completion } from "./commands";
|
||||
|
||||
/**
|
||||
* The composer palette, floating above it: the commands after `/`. The arrow
|
||||
* keys and the pointer both land here.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
matches: Completion[];
|
||||
selection: number;
|
||||
label: string;
|
||||
error?: string;
|
||||
}>();
|
||||
const emit = defineEmits<{ choose: [index: number]; retry: [] }>();
|
||||
|
||||
const menu = ref<HTMLElement | null>(null);
|
||||
|
||||
// Arrow keys move the selection, and the list scrolls so the highlight stays
|
||||
// visible once the matches run past the rows that fit. The arithmetic is
|
||||
// command-scroll.ts's; this only applies what it returns. flush: 'post' so the
|
||||
// option being measured is the one just selected, not the one leaving.
|
||||
watch(
|
||||
() => [props.selection, props.matches.length],
|
||||
async () => {
|
||||
await nextTick();
|
||||
const el = menu.value;
|
||||
const option = el?.children[props.selection] as HTMLElement | undefined;
|
||||
if (!el || !option) return;
|
||||
el.scrollTop = commandScrollTop({
|
||||
scrollTop: el.scrollTop,
|
||||
viewportHeight: el.clientHeight,
|
||||
optionTop: option.offsetTop,
|
||||
optionHeight: option.offsetHeight,
|
||||
});
|
||||
},
|
||||
{ flush: "post" },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
ref="menu"
|
||||
id="slash-palette"
|
||||
role="listbox"
|
||||
:aria-label="label"
|
||||
class="absolute inset-x-3 bottom-[calc(100%-0.25rem)] z-30 grid max-h-72 gap-0.5 overflow-auto rounded-lg border border-border-strong bg-popover p-1.5 text-label shadow-md"
|
||||
>
|
||||
<div v-if="error" role="alert" class="flex items-center justify-between gap-2 px-2.5 py-2 text-danger">
|
||||
<span class="truncate">{{ error }}</span>
|
||||
<Button variant="outline" size="sm" @mousedown.prevent @click="emit('retry')">Retry</Button>
|
||||
</div>
|
||||
<button
|
||||
v-for="(item, index) in matches"
|
||||
:key="item.key"
|
||||
type="button"
|
||||
role="option"
|
||||
:id="`slash-palette-option-${index}`"
|
||||
:aria-selected="index === selection"
|
||||
class="flex flex-col gap-0.5 rounded-md border border-transparent px-2.5 py-1.5 text-left text-fg-muted hover:bg-muted hover:text-foreground aria-selected:border-border aria-selected:bg-muted aria-selected:text-foreground"
|
||||
@mousedown.prevent
|
||||
@click="emit('choose', index)"
|
||||
>
|
||||
<code class="truncate text-foreground">{{ item.label }}</code>
|
||||
<span v-if="item.detail" class="line-clamp-2 text-caption">{{ item.detail }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,93 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { MessageSquare } from "@lucide/vue";
|
||||
import { computed, onUnmounted } from "vue";
|
||||
import { useRoute } from "vue-router";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { chatModelReady, messages, placeholderHint, sendMessage } from "./state";
|
||||
import { suggestionsForRoute } from "./suggestions";
|
||||
|
||||
/**
|
||||
* The suggested prompts for the page the operator is on. The empty
|
||||
* conversation lists them (`list`); beside the composer they are a row of
|
||||
* chips that scrolls sideways. None show until an agent model is configured. A
|
||||
* click sends the prompt as its own message rather than filling the field, and
|
||||
* resting on one previews it as the composer's placeholder.
|
||||
*/
|
||||
defineProps<{ list?: boolean }>();
|
||||
|
||||
const route = useRoute();
|
||||
// No model, no prompts: one sent now could only fail.
|
||||
// A prompt already asked in this conversation is not suggested again.
|
||||
const prompts = computed(() => {
|
||||
if (!chatModelReady.value) return [];
|
||||
const asked = new Set(messages.value.filter((m) => m.from === "web").map((m) => m.text.trim()));
|
||||
return suggestionsForRoute(route).filter((p) => !asked.has(p));
|
||||
});
|
||||
|
||||
function send(prompt: string): void {
|
||||
placeholderHint.value = "";
|
||||
void sendMessage({ textOverride: prompt });
|
||||
}
|
||||
function preview(prompt: string): void {
|
||||
placeholderHint.value = prompt;
|
||||
}
|
||||
// A vertical wheel scrolls the row sideways; a trackpad's sideways swipe
|
||||
// already does.
|
||||
function scrollSideways(event: WheelEvent): void {
|
||||
if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return;
|
||||
const row = event.currentTarget as HTMLElement;
|
||||
if (row.scrollWidth <= row.clientWidth) return;
|
||||
event.preventDefault();
|
||||
row.scrollLeft += event.deltaY;
|
||||
}
|
||||
function clear(): void {
|
||||
placeholderHint.value = "";
|
||||
}
|
||||
onUnmounted(clear);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ul v-if="prompts.length && list" class="flex flex-col gap-1 text-left" aria-label="Suggested prompts">
|
||||
<li v-for="prompt in prompts" :key="prompt">
|
||||
<Button
|
||||
variant="ghost"
|
||||
class="h-auto w-full justify-start gap-3 py-1.5 whitespace-normal text-left font-normal"
|
||||
@click="send(prompt)"
|
||||
@pointerenter="preview(prompt)"
|
||||
@pointerleave="clear"
|
||||
@focus="preview(prompt)"
|
||||
@blur="clear"
|
||||
>
|
||||
<span class="flex size-7 flex-none items-center justify-center rounded-md border" aria-hidden="true">
|
||||
<MessageSquare class="size-3.5" />
|
||||
</span>
|
||||
{{ prompt }}
|
||||
</Button>
|
||||
</li>
|
||||
</ul>
|
||||
<!-- One row that scrolls sideways, so the prompts never push the
|
||||
transcript up by more than a line. -->
|
||||
<div
|
||||
v-else-if="prompts.length"
|
||||
class="-mx-3 mb-2 flex snap-x snap-mandatory scroll-px-3 gap-1.5 overflow-x-auto px-3 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
|
||||
role="group"
|
||||
aria-label="Suggested prompts"
|
||||
@wheel="scrollSideways"
|
||||
>
|
||||
<Button
|
||||
v-for="prompt in prompts"
|
||||
:key="prompt"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="flex-none snap-start whitespace-nowrap"
|
||||
@click="send(prompt)"
|
||||
@pointerenter="preview(prompt)"
|
||||
@pointerleave="clear"
|
||||
@focus="preview(prompt)"
|
||||
@blur="clear"
|
||||
>
|
||||
{{ prompt }}
|
||||
</Button>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,50 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { BrainIcon } from "@lucide/vue";
|
||||
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import {
|
||||
Trace,
|
||||
TraceCollapsible,
|
||||
TraceCollapsibleContent,
|
||||
TraceCollapsibleTrigger,
|
||||
TraceIcon,
|
||||
TraceLine,
|
||||
TraceTitle,
|
||||
} from "@/components/ui/trace";
|
||||
|
||||
/**
|
||||
* The live turn's thinking: the model's reasoning as it streams, in the same
|
||||
* collapsible trace a tool call uses. While the turn has not produced any
|
||||
* reasoning yet, the icon spins and the title shimmers; once text arrives it
|
||||
* streams into the open trace. A finished turn's thinking is folded away. A
|
||||
* turn that never reasons renders nothing, which the caller decides by not
|
||||
* mounting this at all.
|
||||
*/
|
||||
withDefaults(
|
||||
defineProps<{
|
||||
text?: string;
|
||||
/** The turn is still arriving and has not reasoned yet. */
|
||||
pending?: boolean;
|
||||
/** A finished turn's thinking starts folded away. */
|
||||
collapsed?: boolean;
|
||||
}>(),
|
||||
{ text: "", pending: false, collapsed: false },
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Trace class="my-2">
|
||||
<TraceCollapsible :default-open="!collapsed">
|
||||
<TraceCollapsibleTrigger>
|
||||
<TraceLine :status="pending && !text ? 'running' : undefined">
|
||||
<TraceIcon>
|
||||
<Spinner v-if="pending && !text" />
|
||||
<BrainIcon v-else />
|
||||
</TraceIcon>
|
||||
<TraceTitle>Thinking</TraceTitle>
|
||||
</TraceLine>
|
||||
</TraceCollapsibleTrigger>
|
||||
<TraceCollapsibleContent v-if="text" class="whitespace-pre-wrap [overflow-wrap:anywhere]">{{ text }}</TraceCollapsibleContent>
|
||||
</TraceCollapsible>
|
||||
</Trace>
|
||||
</template>
|
||||
@@ -1,110 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Spinner } from "@/components/ui/spinner";
|
||||
import { CircleCheck, CircleX } from "@lucide/vue";
|
||||
import { computed } from "vue";
|
||||
|
||||
import { CodeBlock, CodeBlockContent } from "@/components/ui/code-block";
|
||||
import { duration as formatDuration } from "@/lib/format";
|
||||
import {
|
||||
TraceCollapsible,
|
||||
TraceCollapsibleContent,
|
||||
TraceCollapsibleTrigger,
|
||||
TraceIcon,
|
||||
TraceLine,
|
||||
TraceTitle,
|
||||
} from "@/components/ui/trace";
|
||||
import ChatNavChip from "./ChatNavChip.vue";
|
||||
import type { ChatToolCall } from "./state";
|
||||
|
||||
/**
|
||||
* One tool call: the name, and what came back once it is opened.
|
||||
*
|
||||
* A quiet line rather than the point of the reply: it is evidence for the
|
||||
* answer under it, so it is dim, and a failed call is the only thing here that
|
||||
* raises its voice. The parameters it was given and its outcome are folded away
|
||||
* until asked for. Rendered inside a Trace, which an empty list never creates,
|
||||
* so a turn that called no tools looks untouched.
|
||||
*/
|
||||
const props = defineProps<{
|
||||
tool: ChatToolCall;
|
||||
/** The turn is still arriving, so a call with no outcome yet is running. */
|
||||
streaming?: boolean;
|
||||
}>();
|
||||
|
||||
const name = computed(
|
||||
() => props.tool.name || props.tool.Name || props.tool.tool || "tool",
|
||||
);
|
||||
const parameters = computed(
|
||||
() => props.tool.parameters || props.tool.Parameters || "",
|
||||
);
|
||||
const failed = computed(() =>
|
||||
Boolean(props.tool.err || props.tool.Err || props.tool.failed),
|
||||
);
|
||||
|
||||
// A recorded turn reports its outcome in summary, a live frame in text, and a
|
||||
// failure may only carry the error.
|
||||
const outcome = computed(
|
||||
() =>
|
||||
props.tool.summary ||
|
||||
props.tool.Summary ||
|
||||
props.tool.text ||
|
||||
props.tool.err ||
|
||||
props.tool.Err ||
|
||||
"",
|
||||
);
|
||||
const running = computed(() => !outcome.value && !failed.value && !!props.streaming);
|
||||
const duration = computed(() => formatDuration(props.tool.duration_ms));
|
||||
// The row shows the call's main value, as "git diff --stat" rather than its
|
||||
// JSON: the first string argument, else its arguments as key: value pairs.
|
||||
const argument = computed(() => {
|
||||
try {
|
||||
const args: unknown = JSON.parse(parameters.value);
|
||||
if (args && typeof args === "object" && !Array.isArray(args)) {
|
||||
const first = Object.values(args).find((v) => typeof v === "string" && v);
|
||||
if (typeof first === "string") return first.split("\n", 1)[0];
|
||||
return Object.entries(args)
|
||||
.map(([key, value]) => `${key}: ${typeof value === "object" ? JSON.stringify(value) : value}`)
|
||||
.join(", ");
|
||||
}
|
||||
} catch {
|
||||
// Truncated or not JSON: show it as it came.
|
||||
}
|
||||
return parameters.value.split("\n", 1)[0];
|
||||
});
|
||||
const detail = computed(() =>
|
||||
[parameters.value && `> ${parameters.value}`, outcome.value].filter(Boolean).join("\n\n"),
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<ChatNavChip v-if="tool.path" :path="tool.path" :label="tool.label" />
|
||||
<TraceCollapsible v-else-if="detail" :default-open="failed">
|
||||
<TraceCollapsibleTrigger>
|
||||
<TraceLine :status="failed ? 'error' : running ? 'running' : undefined">
|
||||
<TraceIcon>
|
||||
<CircleX v-if="failed" />
|
||||
<Spinner v-else-if="running" />
|
||||
<CircleCheck v-else class="text-ok" />
|
||||
</TraceIcon>
|
||||
<span class="font-mono text-foreground">{{ name }}</span>
|
||||
<TraceTitle class="font-mono text-caption">{{ argument }}</TraceTitle>
|
||||
<span v-if="duration" class="shrink-0 text-caption tabular-nums">{{ duration }}</span>
|
||||
</TraceLine>
|
||||
</TraceCollapsibleTrigger>
|
||||
<TraceCollapsibleContent>
|
||||
<CodeBlock size="sm">
|
||||
<CodeBlockContent wrap class="max-h-64">{{ detail }}</CodeBlockContent>
|
||||
</CodeBlock>
|
||||
</TraceCollapsibleContent>
|
||||
</TraceCollapsible>
|
||||
<TraceLine v-else :status="failed ? 'error' : running ? 'running' : undefined">
|
||||
<TraceIcon>
|
||||
<CircleX v-if="failed" />
|
||||
<Spinner v-else-if="running" />
|
||||
<CircleCheck v-else class="text-ok" />
|
||||
</TraceIcon>
|
||||
<span class="font-mono text-foreground">{{ name }}</span>
|
||||
<TraceTitle class="font-mono text-caption">{{ argument }}</TraceTitle>
|
||||
<span v-if="duration" class="shrink-0 text-caption tabular-nums">{{ duration }}</span>
|
||||
</TraceLine>
|
||||
</template>
|
||||
@@ -1,47 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Wrench } from "@lucide/vue";
|
||||
import { computed } from "vue";
|
||||
|
||||
import {
|
||||
TraceCollapsible,
|
||||
TraceCollapsibleContent,
|
||||
TraceCollapsibleTrigger,
|
||||
TraceIcon,
|
||||
TraceLine,
|
||||
TraceTitle,
|
||||
} from "@/components/ui/trace";
|
||||
import ChatToolCall from "./ChatToolCall.vue";
|
||||
import type { ChatToolCall as ToolCall } from "./state";
|
||||
|
||||
/**
|
||||
* A run of consecutive tool calls as one line, opened to the individual
|
||||
* calls. A failure anywhere in the run opens it.
|
||||
*/
|
||||
const props = defineProps<{ tools: ToolCall[]; streaming?: boolean }>();
|
||||
|
||||
const failed = (tool: ToolCall) => Boolean(tool.err || tool.Err || tool.failed);
|
||||
|
||||
const anyFailed = computed(() => props.tools.some(failed));
|
||||
const title = computed(() => `${props.tools.length} tool call${props.tools.length === 1 ? "" : "s"}`);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<TraceCollapsible :default-open="anyFailed">
|
||||
<TraceCollapsibleTrigger>
|
||||
<TraceLine :status="anyFailed ? 'error' : undefined">
|
||||
<TraceIcon><Wrench /></TraceIcon>
|
||||
<TraceTitle class="truncate">{{ title }}</TraceTitle>
|
||||
</TraceLine>
|
||||
</TraceCollapsibleTrigger>
|
||||
<TraceCollapsibleContent>
|
||||
<div class="flex flex-col gap-1.5">
|
||||
<ChatToolCall
|
||||
v-for="(tool, i) in tools"
|
||||
:key="i"
|
||||
:tool="tool"
|
||||
:streaming="streaming && i === tools.length - 1"
|
||||
/>
|
||||
</div>
|
||||
</TraceCollapsibleContent>
|
||||
</TraceCollapsible>
|
||||
</template>
|
||||
@@ -1,42 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { MessageCircle } from "@lucide/vue";
|
||||
import { computed } from "vue";
|
||||
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Kbd } from "@/components/ui/kbd";
|
||||
import { dockExpanded } from "./state";
|
||||
import { unseenCount } from "./unseen";
|
||||
|
||||
/**
|
||||
* Opens and closes the chat dock from the topbar, so a dock that is minimised,
|
||||
* or hidden because it is docked, is one click away without knowing Ctrl+/.
|
||||
*/
|
||||
const shortcut = navigator.platform.startsWith("Mac") ? "⌘/" : "Ctrl /";
|
||||
const label = computed(() => {
|
||||
const action = dockExpanded.value ? "Hide chat" : "Chat with Archie";
|
||||
return unseenCount.value ? `${action}, ${unseenCount.value} new` : action;
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Tooltip>
|
||||
<TooltipTrigger as-child>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
class="relative"
|
||||
:aria-label="label"
|
||||
:aria-pressed="dockExpanded"
|
||||
@click="dockExpanded = !dockExpanded"
|
||||
>
|
||||
<MessageCircle class="size-4" aria-hidden="true" />
|
||||
<Badge v-if="unseenCount" class="absolute -top-0.5 -right-1.5 h-4 min-w-4 px-1 text-caption tabular-nums" aria-hidden="true">
|
||||
{{ unseenCount }}
|
||||
</Badge>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ dockExpanded ? "Hide chat" : "Chat with Archie" }} <Kbd>{{ shortcut }}</Kbd></TooltipContent>
|
||||
</Tooltip>
|
||||
</template>
|
||||
@@ -1,98 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
MessageScroller,
|
||||
MessageScrollerContent,
|
||||
MessageScrollerItem,
|
||||
MessageScrollerProvider,
|
||||
MessageScrollerViewport,
|
||||
} from "@/components/ui/message-scroller";
|
||||
import ChatApprovalCard from "./ChatApprovalCard.vue";
|
||||
import ChatBubble from "./ChatBubble.vue";
|
||||
import ChatEmptyState from "./ChatEmptyState.vue";
|
||||
import ChatJumpButton from "./ChatJumpButton.vue";
|
||||
import ChatNoticeCard from "./ChatNoticeCard.vue";
|
||||
import { Alert, AlertDescription } from "@/components/ui/alert";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { currentSession, isLoadingSession, messages, retryLast, selectSession, sessionError } from "./state";
|
||||
|
||||
/**
|
||||
* The conversation: each message and its reply, the cards runs sent while it
|
||||
* was open, and what the panel says before any exist.
|
||||
*
|
||||
* The scroller follows the tail, and stops following the moment the reader
|
||||
* scrolls up rather than yanking them back on every streamed token.
|
||||
*/
|
||||
const rows = computed(() =>
|
||||
messages.value.map((m) => ({
|
||||
...m,
|
||||
thinkingPending: !!m.live && !m.text && !m.reasoning && !m.tool_calls?.length,
|
||||
})),
|
||||
);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<MessageScrollerProvider auto-scroll default-scroll-position="last-anchor">
|
||||
<MessageScroller class="min-h-0 flex-1">
|
||||
<MessageScrollerViewport>
|
||||
<MessageScrollerContent class="gap-4 p-4">
|
||||
<template v-if="isLoadingSession && !rows.length">
|
||||
<Skeleton class="h-14 w-3/5 self-end rounded-xl" />
|
||||
<Skeleton class="h-24 w-4/5 rounded-xl" />
|
||||
<Skeleton class="h-10 w-2/5 self-end rounded-xl" />
|
||||
</template>
|
||||
|
||||
<div v-else-if="sessionError && !rows.length" class="flex flex-col items-center gap-3 p-4">
|
||||
<Alert variant="destructive" class="max-w-md"><AlertDescription>{{ sessionError }}</AlertDescription></Alert>
|
||||
<Button variant="outline" size="sm" @click="selectSession(currentSession)">Retry</Button>
|
||||
</div>
|
||||
|
||||
<ChatEmptyState v-else-if="!rows.length" />
|
||||
|
||||
<template v-else>
|
||||
<MessageScrollerItem
|
||||
v-for="row in rows"
|
||||
:key="row.key"
|
||||
:message-id="row.key"
|
||||
:scroll-anchor="row.from === 'web'"
|
||||
>
|
||||
<ChatNoticeCard v-if="row.notice" :notice="row.notice" />
|
||||
<ChatBubble
|
||||
v-else
|
||||
:text="row.live && !row.text ? '…' : row.text"
|
||||
:tools="row.tool_calls"
|
||||
:page="row.page"
|
||||
:assistant="row.from === 'assistant'"
|
||||
:streaming="row.live"
|
||||
:reasoning="row.reasoning"
|
||||
:thinking-pending="row.thinkingPending"
|
||||
:error="row.error"
|
||||
>
|
||||
<ChatApprovalCard
|
||||
v-for="approval in row.approvals"
|
||||
:key="approval.request_id"
|
||||
:request-id="approval.request_id"
|
||||
:action="approval.action"
|
||||
:summary="approval.summary"
|
||||
:outcome="approval.outcome"
|
||||
/>
|
||||
<Button
|
||||
v-if="row.error && row.turn"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
class="mt-2"
|
||||
@click="retryLast(row.turn)"
|
||||
>Retry</Button>
|
||||
</ChatBubble>
|
||||
</MessageScrollerItem>
|
||||
</template>
|
||||
<Alert v-if="sessionError && rows.length" variant="destructive"><AlertDescription>{{ sessionError }}</AlertDescription></Alert>
|
||||
</MessageScrollerContent>
|
||||
</MessageScrollerViewport>
|
||||
|
||||
<ChatJumpButton />
|
||||
</MessageScroller>
|
||||
</MessageScrollerProvider>
|
||||
</template>
|
||||
@@ -1,41 +0,0 @@
|
||||
// Keeping the arrow-key selection visible in the command palette.
|
||||
//
|
||||
// The palette caps its height and scrolls, so once the matches run past the
|
||||
// visible rows the selection must scroll with the highlight. Browsers have
|
||||
// scrollIntoView, but the decision is pure
|
||||
// arithmetic and worth testing on its own, so the effect only applies what
|
||||
// this returns.
|
||||
|
||||
/** The palette's scroll geometry and the selected option's position in it. */
|
||||
export interface CommandScrollGeometry {
|
||||
scrollTop: number;
|
||||
viewportHeight: number;
|
||||
optionTop: number;
|
||||
optionHeight: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* commandScrollTop returns the scrollTop that brings the selected option fully
|
||||
* into view, or the current scrollTop when it is already visible. Mirrors
|
||||
* `scrollIntoView({ block: "nearest" })`: it moves the minimum distance, and
|
||||
* scrolls up for an option above the viewport, down for one below.
|
||||
*/
|
||||
export function commandScrollTop({
|
||||
scrollTop,
|
||||
viewportHeight,
|
||||
optionTop,
|
||||
optionHeight,
|
||||
}: CommandScrollGeometry): number {
|
||||
// An option taller than the viewport cannot be shown whole. Align its top,
|
||||
// which holds the command itself; aligning the bottom would scroll the name
|
||||
// out of sight and leave only the tail of its description.
|
||||
if (optionHeight >= viewportHeight) return optionTop;
|
||||
|
||||
if (optionTop < scrollTop) return optionTop;
|
||||
|
||||
const optionBottom = optionTop + optionHeight;
|
||||
const viewportBottom = scrollTop + viewportHeight;
|
||||
if (optionBottom > viewportBottom) return optionBottom - viewportHeight;
|
||||
|
||||
return scrollTop;
|
||||
}
|
||||
@@ -1,88 +0,0 @@
|
||||
import type { ChatCommandSpec } from "./state";
|
||||
|
||||
/**
|
||||
* The composer palette's arithmetic, kept out of the composer so it is decided
|
||||
* in one place rather than reconstructed from DOM positions twice. `/`
|
||||
* completes a command.
|
||||
*/
|
||||
|
||||
export type Trigger = "/";
|
||||
|
||||
/** One row of the palette: what is shown, and the key that identifies it. */
|
||||
export interface Completion {
|
||||
key: string;
|
||||
label: string;
|
||||
detail: string;
|
||||
}
|
||||
|
||||
/** The trigger word the caret sits in: at the start or after whitespace. */
|
||||
const OPEN_TOKEN = /(?:^|\s)([/])([^\s]*)$/;
|
||||
|
||||
/** How many matches the palette will show at once. */
|
||||
const MAX_MATCHES = 8;
|
||||
|
||||
/** detectTrigger returns the trigger and the text typed after it, if any. */
|
||||
export function detectTrigger(
|
||||
value: string,
|
||||
caret: number,
|
||||
): { trigger: Trigger; query: string } | null {
|
||||
const match = value.slice(0, caret).match(OPEN_TOKEN);
|
||||
if (!match) return null;
|
||||
return { trigger: match[1] as Trigger, query: match[2].toLowerCase() };
|
||||
}
|
||||
|
||||
/** Commands matched on the command and its description together. */
|
||||
export function commandCompletions(
|
||||
specs: ChatCommandSpec[],
|
||||
query: string,
|
||||
): Completion[] {
|
||||
return specs
|
||||
.filter((spec) =>
|
||||
`${spec.command} ${spec.description ?? ""}`.toLowerCase().includes(query),
|
||||
)
|
||||
.slice(0, MAX_MATCHES)
|
||||
.map((spec) => ({
|
||||
key: spec.command,
|
||||
label: spec.command,
|
||||
detail: spec.description || spec.usage || "",
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* replaceToken swaps the trigger word the caret sits in for `insert` and
|
||||
* returns the caret just after it. A space follows the insert unless one
|
||||
* already does, so completing mid-sentence never doubles it. An empty insert
|
||||
* removes the token.
|
||||
*/
|
||||
export function replaceToken(
|
||||
value: string,
|
||||
caret: number,
|
||||
insert: string,
|
||||
): { text: string; cursor: number } {
|
||||
const before = value.slice(0, caret);
|
||||
const after = value.slice(caret);
|
||||
const start = before.search(/(?:^|\s)[/][^\s]*$/);
|
||||
const tokenStart =
|
||||
start < 0 ? before.length : start + (/\s/.test(before[start]) ? 1 : 0);
|
||||
const head = before.slice(0, tokenStart);
|
||||
const gap = insert === "" || /^\s/.test(after) ? "" : " ";
|
||||
// Removing the token must not leave the words either side of it two spaces apart.
|
||||
const tail = insert === "" && /\s$/.test(head) ? after.replace(/^[ \t]/, "") : after;
|
||||
return {
|
||||
text: `${head}${insert}${gap}${tail}`,
|
||||
cursor: tokenStart + insert.length + gap.length,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* isExactCommand reports whether the composer already holds a command and
|
||||
* nothing else. Enter then sends it rather than completing it, so a command
|
||||
* typed in full is never re-entered by the palette that was offering it.
|
||||
*/
|
||||
export function isExactCommand(
|
||||
specs: ChatCommandSpec[],
|
||||
value: string,
|
||||
): boolean {
|
||||
const trimmed = value.trim();
|
||||
return specs.some((spec) => spec.command === trimmed);
|
||||
}
|
||||
@@ -1,191 +0,0 @@
|
||||
/**
|
||||
* Chat markdown.
|
||||
*
|
||||
* Telegram-style rich blocks -- headings, lists, quotes, fenced code, tables,
|
||||
* inline emphasis/links/images -- parsed into a tree that ChatMarkdown renders
|
||||
* as semantic HTML. The parse is separate from the render so a streamed reply
|
||||
* can be re-rendered on every frame without re-deciding what the text means.
|
||||
*/
|
||||
|
||||
/** One span of an inline run: what a paragraph's text breaks down into. */
|
||||
export type ChatInline =
|
||||
| { kind: "text"; text: string }
|
||||
| { kind: "strong"; text: string }
|
||||
| { kind: "em"; text: string }
|
||||
| { kind: "del"; text: string }
|
||||
| { kind: "code"; text: string }
|
||||
| { kind: "link"; text: string; href: string }
|
||||
| { kind: "image"; alt: string; src: string };
|
||||
|
||||
/** One block of the document. Lists carry their items as inline runs. */
|
||||
export type ChatBlock =
|
||||
| { kind: "p" | "h1" | "h2" | "h3" | "blockquote"; inline: ChatInline[] }
|
||||
| { kind: "ul" | "ol"; items: ChatInline[][] }
|
||||
| { kind: "pre"; code: string; lang: string }
|
||||
| { kind: "table"; head: ChatInline[][]; rows: ChatInline[][][] };
|
||||
|
||||
const INLINE =
|
||||
/(!\[[^\]]*\]\((?:https?:\/\/[^\s)]+|data:image\/[^\s)]+|\/[^\s)]+)\)|~~[^~]+~~|\*\*[^*]+\*\*|__[^_]+__|`[^`]+`|\[[^\]]+\]\((?:https?:\/\/[^\s)]+|\/[^\s)]+)\)|\*[^*]+\*|_[^_]+_)/g;
|
||||
|
||||
function plainText(text: string): ChatInline[] {
|
||||
return text ? [{ kind: "text", text }] : [];
|
||||
}
|
||||
|
||||
// inlineMarkdown returns the children of one line: plain text and the element
|
||||
// each matched span becomes, in order.
|
||||
function inlineMarkdown(text: string): ChatInline[] {
|
||||
const children: ChatInline[] = [];
|
||||
let cursor = 0;
|
||||
for (const match of String(text).matchAll(INLINE)) {
|
||||
if (match.index > cursor)
|
||||
children.push(...plainText(text.slice(cursor, match.index)));
|
||||
const value = match[0];
|
||||
if (value.startsWith("![")) {
|
||||
const img = value.match(/^!\[([^\]]*)\]\((.+)\)$/);
|
||||
if (img)
|
||||
children.push({ kind: "image", alt: img[1] || "Image", src: img[2] });
|
||||
} else if (value.startsWith("~~")) {
|
||||
children.push({ kind: "del", text: value.slice(2, -2) });
|
||||
} else if (value.startsWith("**") || value.startsWith("__")) {
|
||||
children.push({ kind: "strong", text: value.slice(2, -2) });
|
||||
} else if (value.startsWith("`")) {
|
||||
children.push({ kind: "code", text: value.slice(1, -1) });
|
||||
} else if (value.startsWith("[")) {
|
||||
const link = value.match(
|
||||
/^\[([^\]]+)\]\((https?:\/\/[^\s)]+|\/[^\s)]+)\)$/,
|
||||
);
|
||||
if (link) children.push({ kind: "link", text: link[1], href: link[2] });
|
||||
} else {
|
||||
children.push({ kind: "em", text: value.slice(1, -1) });
|
||||
}
|
||||
cursor = match.index + value.length;
|
||||
}
|
||||
if (cursor < text.length)
|
||||
children.push(...plainText(text.slice(cursor)));
|
||||
return children;
|
||||
}
|
||||
|
||||
export function parseMarkdown(text: string | null | undefined): ChatBlock[] {
|
||||
const blocks: ChatBlock[] = [];
|
||||
const lines = String(text || "").split("\n");
|
||||
let paragraph: string[] = [];
|
||||
let list: { tag: "ul" | "ol"; items: string[] } | null = null;
|
||||
let code: string[] | null = null;
|
||||
let lang = "";
|
||||
|
||||
const flushParagraph = () => {
|
||||
if (paragraph.length) {
|
||||
blocks.push({ kind: "p", inline: inlineMarkdown(paragraph.join(" ")) });
|
||||
paragraph = [];
|
||||
}
|
||||
};
|
||||
const flushList = () => {
|
||||
if (!list) return;
|
||||
blocks.push({
|
||||
kind: list.tag,
|
||||
items: list.items.map((item) => inlineMarkdown(item)),
|
||||
});
|
||||
list = null;
|
||||
};
|
||||
|
||||
for (let index = 0; index < lines.length; index++) {
|
||||
const line = lines[index];
|
||||
if (line.startsWith("```")) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
if (code) {
|
||||
blocks.push({ kind: "pre", code: code.join("\n"), lang });
|
||||
code = null;
|
||||
} else {
|
||||
code = [];
|
||||
lang = line.slice(3).trim().split(/\s/)[0];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (code) {
|
||||
code.push(line);
|
||||
continue;
|
||||
}
|
||||
const headerCells = tableCells(line);
|
||||
const separatorCells =
|
||||
index + 1 < lines.length ? tableCells(lines[index + 1]) : null;
|
||||
if (
|
||||
headerCells &&
|
||||
separatorCells &&
|
||||
isTableSeparator(separatorCells) &&
|
||||
headerCells.length === separatorCells.length
|
||||
) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
const rows: string[][] = [];
|
||||
for (index += 2; index < lines.length; index++) {
|
||||
const cells = tableCells(lines[index]);
|
||||
if (!cells || cells.length !== headerCells.length) {
|
||||
index--;
|
||||
break;
|
||||
}
|
||||
rows.push(cells);
|
||||
}
|
||||
blocks.push({
|
||||
kind: "table",
|
||||
head: headerCells.map((cell) => inlineMarkdown(cell)),
|
||||
rows: rows.map((row) => row.map((cell) => inlineMarkdown(cell))),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
if (!line.trim()) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
continue;
|
||||
}
|
||||
const heading = line.match(/^(#{1,3})\s+(.+)$/);
|
||||
if (heading) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
blocks.push({
|
||||
kind: `h${heading[1].length}` as "h1" | "h2" | "h3",
|
||||
inline: inlineMarkdown(heading[2]),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const bullet = line.match(/^\s*[-*]\s+(.+)$/);
|
||||
const ordered = line.match(/^\s*\d+[.)]\s+(.+)$/);
|
||||
if (bullet || ordered) {
|
||||
flushParagraph();
|
||||
const tag = ordered ? "ol" : "ul";
|
||||
if (!list || list.tag !== tag) {
|
||||
flushList();
|
||||
list = { tag, items: [] };
|
||||
}
|
||||
list.items.push((bullet || ordered)![1]);
|
||||
continue;
|
||||
}
|
||||
if (line.startsWith(">")) {
|
||||
flushParagraph();
|
||||
flushList();
|
||||
blocks.push({
|
||||
kind: "blockquote",
|
||||
inline: inlineMarkdown(line.replace(/^>\s?/, "")),
|
||||
});
|
||||
continue;
|
||||
}
|
||||
paragraph.push(line);
|
||||
}
|
||||
flushParagraph();
|
||||
flushList();
|
||||
if (code) blocks.push({ kind: "pre", code: code.join("\n"), lang });
|
||||
|
||||
return blocks;
|
||||
}
|
||||
|
||||
function tableCells(line: string): string[] | null {
|
||||
const value = String(line || "").trim();
|
||||
if (!value.includes("|")) return null;
|
||||
const unwrapped = value.replace(/^\|/, "").replace(/\|$/, "");
|
||||
const cells = unwrapped.split("|").map((cell) => cell.trim());
|
||||
return cells.length > 1 && cells.every((cell) => cell !== "") ? cells : null;
|
||||
}
|
||||
|
||||
function isTableSeparator(cells: string[]): boolean {
|
||||
return cells.every((cell) => /^:?-{3,}:?$/.test(cell));
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
import { useAppearanceStore } from "@/stores/appearance";
|
||||
|
||||
import type { ChatSession } from "./state";
|
||||
|
||||
// One formatter per zone, cached: the zone chosen under Appearance is applied
|
||||
// here like Timestamp applies it, not the browser's zone.
|
||||
const startedCache = new Map<string, Intl.DateTimeFormat>();
|
||||
function started(zone: string): Intl.DateTimeFormat {
|
||||
const cached = startedCache.get(zone);
|
||||
if (cached) return cached;
|
||||
const format = new Intl.DateTimeFormat(undefined, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
...(zone ? { timeZone: zone } : {}),
|
||||
});
|
||||
startedCache.set(zone, format);
|
||||
return format;
|
||||
}
|
||||
|
||||
// An untitled conversation is named by when it began, which tells two apart
|
||||
// where a raw id cannot.
|
||||
export function sessionTitle(session: ChatSession): string {
|
||||
const named = session.title;
|
||||
if (named) return named;
|
||||
return session.created_at
|
||||
? started(useAppearanceStore().timeZone).format(new Date(session.created_at))
|
||||
: "New chat";
|
||||
}
|
||||
@@ -1,677 +0,0 @@
|
||||
import { computed, onMounted, onUnmounted, ref, watch, type Ref } from "vue";
|
||||
|
||||
import router from "../router";
|
||||
import {
|
||||
answerApproval,
|
||||
cancelChatTurn,
|
||||
chatSessions,
|
||||
chatTurn,
|
||||
chatTurnEvents,
|
||||
chatTurns,
|
||||
composerStream,
|
||||
createChatSession,
|
||||
deleteChatSession,
|
||||
latestMessages,
|
||||
messagesAfter,
|
||||
pendingApprovals,
|
||||
renameChatSession,
|
||||
sendChatTurn,
|
||||
Unauthorized,
|
||||
type ChatActionDone,
|
||||
type ChatApproval,
|
||||
type ChatSession,
|
||||
type ChatTurn,
|
||||
type Message,
|
||||
type PendingApproval,
|
||||
} from "../api";
|
||||
import { commandCompletions, detectTrigger, type Completion, type Trigger } from "./commands";
|
||||
|
||||
/**
|
||||
* The chat's shared state.
|
||||
*
|
||||
* The dock and the composer page are separate components and the dock survives
|
||||
* a navigation, so the conversation lives in a module rather than in either
|
||||
* one. Turns are the server's: a message is stored before it is shown as sent,
|
||||
* a turn sent while another runs waits in the server's queue, and what a turn
|
||||
* streams is recorded, so a reload follows a running turn from where it is.
|
||||
* Notifications and approval requests from runs show in the conversation as
|
||||
* cards; an approval is answered only through its card.
|
||||
*/
|
||||
|
||||
export type { ChatSession };
|
||||
|
||||
/** One slash command the composer accepts. */
|
||||
export interface ChatCommandSpec {
|
||||
command: string;
|
||||
usage?: string;
|
||||
description?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A tool the assistant called, or a page it offered: a navigation carries
|
||||
* `path` and renders as a link rather than a tool line.
|
||||
*/
|
||||
export interface ChatToolCall {
|
||||
id?: string;
|
||||
name?: string;
|
||||
tool?: string;
|
||||
parameters?: string;
|
||||
summary?: string;
|
||||
text?: string;
|
||||
failed?: boolean;
|
||||
duration_ms?: number;
|
||||
text_offset?: number;
|
||||
path?: string;
|
||||
label?: string;
|
||||
Name?: string;
|
||||
Parameters?: string;
|
||||
Summary?: string;
|
||||
Err?: string;
|
||||
err?: string;
|
||||
}
|
||||
|
||||
/** One row of the transcript: the operator's message, Archie's reply, or a card from a run. */
|
||||
export interface ChatMessage {
|
||||
key: string;
|
||||
from: "web" | "assistant" | "notice";
|
||||
text: string;
|
||||
/** The page the message was asked from. */
|
||||
page?: string;
|
||||
tool_calls?: ChatToolCall[];
|
||||
/** Actions judgement held during the turn, with what became of each. */
|
||||
approvals?: (ChatApproval & { outcome?: ChatActionDone })[];
|
||||
reasoning?: string;
|
||||
/** The reply is still arriving. */
|
||||
live?: boolean;
|
||||
/** The turn waits behind another one in this conversation. */
|
||||
queued?: boolean;
|
||||
error?: boolean;
|
||||
/** The turn this row belongs to, for a retry. */
|
||||
turn?: ChatTurn;
|
||||
notice?: Message;
|
||||
}
|
||||
|
||||
export const sessions = ref<ChatSession[]>([]);
|
||||
export const currentSession = ref("");
|
||||
const turns = ref<ChatTurn[]>([]);
|
||||
const notices = ref<Message[]>([]);
|
||||
/** Approval requests waiting for an answer, from any run or conversation. */
|
||||
export const approvals = ref<PendingApproval[]>([]);
|
||||
export const approvalReadFailed = ref(false);
|
||||
export const noticeError = ref("");
|
||||
|
||||
const drafts = ref<Record<string, string>>({});
|
||||
/** Whether the chat dock shows the conversation; the dock, Ctrl+/ and the topbar button share it. */
|
||||
export const dockExpanded = ref(false);
|
||||
/** A suggested prompt the pointer or focus rests on, previewed as the composer placeholder. */
|
||||
export const placeholderHint = ref("");
|
||||
/** The unsent text of the open conversation; each conversation keeps its own. */
|
||||
export const composerText = computed({
|
||||
get: () => drafts.value[currentSession.value] ?? "",
|
||||
set: (value: string) => {
|
||||
drafts.value = { ...drafts.value, [currentSession.value]: value };
|
||||
},
|
||||
});
|
||||
|
||||
export const statusText = ref("Ready");
|
||||
export const isLoadingSession = ref(false);
|
||||
// A failed conversation load or send: shown in the transcript itself.
|
||||
export const sessionError = ref("");
|
||||
export const activeModel = ref("");
|
||||
export const modelError = ref("");
|
||||
/** Whether an agent model is configured, so a prompt sent now can be answered. */
|
||||
export const chatModelReady = computed(() => !!activeModel.value);
|
||||
/** The dashboard was refused: the shell signs the operator out. */
|
||||
export const unauthorized = ref(false);
|
||||
|
||||
/** The commands the composer's palette offers. Each acts on the conversation through its API. */
|
||||
export const commandSpecs = ref<ChatCommandSpec[]>([
|
||||
{ command: "/new", description: "Start a new conversation" },
|
||||
{ command: "/rename", usage: "/rename <title>", description: "Rename this conversation" },
|
||||
{ command: "/retry", description: "Send the last message again" },
|
||||
{ command: "/stop", description: "Stop the turn in progress" },
|
||||
{ command: "/delete", description: "Delete this conversation" },
|
||||
]);
|
||||
export const commandMatches = ref<Completion[]>([]);
|
||||
export const menuTrigger = ref<Trigger>("/");
|
||||
export const commandSelection = ref(0);
|
||||
export const isCommandMenuOpen = ref(false);
|
||||
|
||||
/**
|
||||
* How many layers inside the panel currently own Escape -- an open popover, a
|
||||
* select inside one. The panel's own Escape defers to them.
|
||||
*/
|
||||
const openLayers = ref(0);
|
||||
|
||||
/** Registers a toggleable layer inside the panel, for as long as it is mounted. */
|
||||
export function useEscapeLayer(open: Ref<boolean>): void {
|
||||
watch(open, (isOpen) => {
|
||||
openLayers.value += isOpen ? 1 : -1;
|
||||
});
|
||||
onUnmounted(() => {
|
||||
if (open.value) openLayers.value -= 1;
|
||||
});
|
||||
}
|
||||
|
||||
export function escapeOwnedByLayer(): boolean {
|
||||
return openLayers.value > 0;
|
||||
}
|
||||
|
||||
const unfinished = (t: ChatTurn) => t.state === "queued" || t.state === "running";
|
||||
|
||||
/** A turn of this conversation is waiting or running. */
|
||||
export const isSending = computed(() => turns.value.some(unfinished));
|
||||
|
||||
/** The turns waiting behind the one running, oldest first. */
|
||||
const queuedTurns = computed(() => {
|
||||
return turns.value.filter(unfinished).slice(1);
|
||||
});
|
||||
export const queuedMessages = computed(() => queuedTurns.value.map((t) => t.text));
|
||||
|
||||
function fail(err: unknown, what: string): string {
|
||||
if (err instanceof Unauthorized) unauthorized.value = true;
|
||||
const reason = err instanceof Error ? err.message : String(err);
|
||||
return `${what}: ${reason}`;
|
||||
}
|
||||
|
||||
// The notifications shown in a conversation are those that arrived while it was
|
||||
// the newest one: from its start until the next conversation began.
|
||||
const sessionWindow = computed(() => {
|
||||
const open = sessions.value.find((s) => s.session_id === currentSession.value);
|
||||
if (!open) return null;
|
||||
const later = sessions.value
|
||||
.map((s) => s.created_at)
|
||||
.filter((at) => at > open.created_at)
|
||||
.sort();
|
||||
return { from: open.created_at, to: later[0] };
|
||||
});
|
||||
|
||||
const askedHere = computed(() => new Set(turns.value.flatMap((t) => t.approvals.map((a) => a.request_id))));
|
||||
|
||||
/** The transcript: each turn's message and reply, with the run cards that arrived meanwhile. */
|
||||
export const messages = computed<ChatMessage[]>(() => {
|
||||
const rows: (ChatMessage & { at: string })[] = [];
|
||||
const waiting = new Set(queuedTurns.value.map((t) => t.id));
|
||||
for (const turn of turns.value) {
|
||||
// A message waiting behind another turn shows in the queue above the composer.
|
||||
if (waiting.has(turn.id)) continue;
|
||||
rows.push({ key: `${turn.id}:q`, at: turn.created_at, from: "web", text: turn.text, page: turn.page_label || turn.page, turn });
|
||||
const outcomes = new Map(turn.actions.map((a) => [a.request_id, a]));
|
||||
const failed = turn.state === "failed";
|
||||
rows.push({
|
||||
key: `${turn.id}:a`,
|
||||
at: turn.created_at,
|
||||
from: "assistant",
|
||||
text: failed ? turn.error || "The turn failed." : turn.reply || (turn.state === "cancelled" ? "Stopped before replying." : ""),
|
||||
tool_calls: [
|
||||
...turn.tool_calls,
|
||||
...turn.navigate.map((n) => ({ path: n.path, label: n.label, text_offset: Array.from(turn.reply).length })),
|
||||
],
|
||||
approvals: turn.approvals.map((a) => ({ ...a, outcome: outcomes.get(a.request_id) })),
|
||||
reasoning: turn.reasoning,
|
||||
live: unfinished(turn),
|
||||
error: failed,
|
||||
turn,
|
||||
});
|
||||
}
|
||||
const window = sessionWindow.value;
|
||||
if (window) {
|
||||
for (const notice of notices.value) {
|
||||
if (notice.created_at < window.from || (window.to && notice.created_at >= window.to)) continue;
|
||||
if (notice.request_id && askedHere.value.has(notice.request_id)) continue;
|
||||
rows.push({ key: `n${notice.id}`, at: notice.created_at, from: "notice", text: notice.title, notice });
|
||||
}
|
||||
}
|
||||
// Stable: a turn's two rows keep their order.
|
||||
return rows.sort((a, b) => (a.at < b.at ? -1 : a.at > b.at ? 1 : 0));
|
||||
});
|
||||
|
||||
// Bumped on every conversation switch: a stream for an earlier conversation is
|
||||
// detached and must not write into the one now open.
|
||||
let sessionEpoch = 0;
|
||||
let following: AbortController | null = null;
|
||||
|
||||
async function refreshSessions(): Promise<void> {
|
||||
const data = await chatSessions();
|
||||
sessions.value = data.sessions;
|
||||
activeModel.value = data.active_model;
|
||||
modelError.value = data.model_error ?? "";
|
||||
if (!currentSession.value && data.sessions[0]) await selectSession(data.sessions[0].session_id);
|
||||
}
|
||||
|
||||
export async function selectSession(id: string): Promise<void> {
|
||||
if (!id) return;
|
||||
sessionEpoch++;
|
||||
following?.abort();
|
||||
following = null;
|
||||
currentSession.value = id;
|
||||
turns.value = [];
|
||||
isLoadingSession.value = true;
|
||||
sessionError.value = "";
|
||||
const epoch = sessionEpoch;
|
||||
try {
|
||||
const loaded = await chatTurns(id);
|
||||
if (epoch !== sessionEpoch) return;
|
||||
turns.value = loaded;
|
||||
follow();
|
||||
} catch (err) {
|
||||
if (epoch === sessionEpoch) sessionError.value = fail(err, "Couldn't load the conversation");
|
||||
} finally {
|
||||
if (epoch === sessionEpoch) isLoadingSession.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-reads the open conversation, so actions settled after a turn ended show. */
|
||||
export async function reloadTranscript(): Promise<void> {
|
||||
const id = currentSession.value;
|
||||
if (!id || isSending.value) return;
|
||||
const epoch = sessionEpoch;
|
||||
try {
|
||||
const loaded = await chatTurns(id);
|
||||
if (epoch === sessionEpoch && !isSending.value) turns.value = loaded;
|
||||
} catch {
|
||||
// The next composer event or reopening the conversation reads it again.
|
||||
}
|
||||
}
|
||||
|
||||
function replaceTurn(next: ChatTurn): void {
|
||||
turns.value = turns.value.map((t) => (t.id === next.id ? next : t));
|
||||
}
|
||||
|
||||
/**
|
||||
* Follows the conversation's unfinished turns one at a time, oldest first,
|
||||
* replaying each from its first event so a reload shows it whole. A dropped
|
||||
* stream reconnects from the last event seen.
|
||||
*/
|
||||
function follow(): void {
|
||||
if (following) return;
|
||||
const ctrl = new AbortController();
|
||||
following = ctrl;
|
||||
const epoch = sessionEpoch;
|
||||
void (async () => {
|
||||
let backoff = 1000;
|
||||
try {
|
||||
for (;;) {
|
||||
const next = turns.value.find(unfinished);
|
||||
if (!next || ctrl.signal.aborted || epoch !== sessionEpoch) return;
|
||||
try {
|
||||
await followTurn(next, ctrl.signal);
|
||||
backoff = 1000;
|
||||
} catch (err) {
|
||||
if (ctrl.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) {
|
||||
unauthorized.value = true;
|
||||
return;
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, backoff));
|
||||
backoff = Math.min(backoff * 2, 30000);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (following === ctrl) following = null;
|
||||
if (epoch === sessionEpoch) statusText.value = "Ready";
|
||||
void refreshSessions().catch(() => undefined);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
async function followTurn(start: ChatTurn, signal: AbortSignal): Promise<void> {
|
||||
let turn: ChatTurn = { ...start, reply: "", reasoning: "", tool_calls: [], approvals: [], actions: [], navigate: [] };
|
||||
let seq = 0;
|
||||
// A turn read while queued may have started since.
|
||||
let ended = false;
|
||||
for await (const event of chatTurnEvents(start.id, seq, signal)) {
|
||||
seq = event.seq;
|
||||
switch (event.type) {
|
||||
case "delta":
|
||||
turn = { ...turn, state: "running", reply: turn.reply + event.text };
|
||||
break;
|
||||
case "reasoning":
|
||||
turn = { ...turn, state: "running", reasoning: (turn.reasoning ?? "") + event.text };
|
||||
break;
|
||||
case "tool": {
|
||||
const { seq: _seq, type: _type, ...tool } = event;
|
||||
turn = { ...turn, state: "running", tool_calls: [...turn.tool_calls, tool] };
|
||||
break;
|
||||
}
|
||||
case "navigate":
|
||||
turn = { ...turn, navigate: [...turn.navigate, { path: event.path, label: event.label }] };
|
||||
break;
|
||||
case "approval": {
|
||||
const { seq: _seq, type: _type, ...approval } = event;
|
||||
turn = { ...turn, approvals: [...turn.approvals, approval] };
|
||||
void loadApprovals();
|
||||
break;
|
||||
}
|
||||
case "action": {
|
||||
const { seq: _seq, type: _type, ...done } = event;
|
||||
turn = { ...turn, actions: [...turn.actions, done] };
|
||||
break;
|
||||
}
|
||||
case "done":
|
||||
case "error":
|
||||
case "cancelled":
|
||||
ended = true;
|
||||
break;
|
||||
}
|
||||
replaceTurn(turn);
|
||||
statusText.value = "Thinking…";
|
||||
}
|
||||
if (!ended && !signal.aborted) {
|
||||
// The stream closed before the turn ended: read where it stands and follow again.
|
||||
replaceTurn(await chatTurn(start.id, signal));
|
||||
throw new Error("the stream ended early");
|
||||
}
|
||||
replaceTurn(await chatTurn(start.id, signal));
|
||||
}
|
||||
|
||||
/** Whether a page's context goes with the next message: the route the operator is on. */
|
||||
function currentPage(): string {
|
||||
return router.currentRoute.value.fullPath.split("#")[0] || "/";
|
||||
}
|
||||
|
||||
// The page whose tag the operator removed. Navigating elsewhere shows the tag
|
||||
// again, so the dismissal never outlives the page it was made on.
|
||||
const clearedPage = ref("");
|
||||
watch(currentPage, () => {
|
||||
clearedPage.value = "";
|
||||
});
|
||||
|
||||
/** What the next message is about, named for the tag above the composer. */
|
||||
export const pageTag = computed(() => {
|
||||
const route = router.currentRoute.value;
|
||||
const page = currentPage();
|
||||
if (page === clearedPage.value || route.name === "composer") return null;
|
||||
const id = typeof route.params.id === "string" ? route.params.id : "";
|
||||
const named = typeof route.meta.label === "string" ? route.meta.label : page;
|
||||
return { page, label: id ? `${named} ${id.length > 12 ? id.slice(0, 8) : id}` : named };
|
||||
});
|
||||
|
||||
export function clearPageTag(): void {
|
||||
clearedPage.value = currentPage();
|
||||
}
|
||||
|
||||
async function ensureSession(): Promise<string> {
|
||||
if (currentSession.value) return currentSession.value;
|
||||
const created = await createChatSession();
|
||||
sessions.value = [created, ...sessions.value];
|
||||
sessionEpoch++;
|
||||
currentSession.value = created.session_id;
|
||||
turns.value = [];
|
||||
return created.session_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends the composer's text, or the given text, as a turn. The server stores it
|
||||
* before answering; one sent while a turn runs waits behind it there.
|
||||
*/
|
||||
export async function sendMessage(opts?: { textOverride?: string }): Promise<void> {
|
||||
const typed = opts?.textOverride ?? composerText.value;
|
||||
const text = typed.trim();
|
||||
if (!text) return;
|
||||
closeCommandMenu();
|
||||
if (text.startsWith("/") && (await runCommand(text))) {
|
||||
if (opts?.textOverride === undefined) composerText.value = "";
|
||||
return;
|
||||
}
|
||||
sessionError.value = "";
|
||||
try {
|
||||
const session = await ensureSession();
|
||||
const tag = pageTag.value;
|
||||
const turn = await sendChatTurn(session, text, tag ? { page: tag.page, page_label: tag.label } : undefined);
|
||||
if (session !== currentSession.value) return;
|
||||
if (opts?.textOverride === undefined) drafts.value = { ...drafts.value, [session]: "" };
|
||||
turns.value = [...turns.value, turn];
|
||||
dockExpanded.value = true;
|
||||
statusText.value = "Thinking…";
|
||||
follow();
|
||||
} catch (err) {
|
||||
sessionError.value = fail(err, "Couldn't send the message");
|
||||
}
|
||||
}
|
||||
|
||||
/** Runs a palette command; false when the text isn't one, so it goes as a message. */
|
||||
async function runCommand(text: string): Promise<boolean> {
|
||||
const [command, ...rest] = text.split(/\s+/);
|
||||
const arg = rest.join(" ").trim();
|
||||
switch (command) {
|
||||
case "/new":
|
||||
await newChat();
|
||||
return true;
|
||||
case "/rename":
|
||||
if (arg) await renameSession(arg);
|
||||
return true;
|
||||
case "/retry":
|
||||
await retryLast();
|
||||
return true;
|
||||
case "/stop":
|
||||
stopTurn();
|
||||
return true;
|
||||
case "/delete":
|
||||
await deleteSession();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export async function newChat(): Promise<void> {
|
||||
sessionError.value = "";
|
||||
try {
|
||||
const created = await createChatSession();
|
||||
sessions.value = [created, ...sessions.value];
|
||||
await selectSession(created.session_id);
|
||||
} catch (err) {
|
||||
sessionError.value = fail(err, "Couldn't start a conversation");
|
||||
}
|
||||
}
|
||||
|
||||
export async function renameSession(title: string): Promise<void> {
|
||||
const id = currentSession.value;
|
||||
if (!id) return;
|
||||
try {
|
||||
const renamed = await renameChatSession(id, title);
|
||||
sessions.value = sessions.value.map((s) => (s.session_id === id ? renamed : s));
|
||||
} catch (err) {
|
||||
sessionError.value = fail(err, "Couldn't rename the conversation");
|
||||
}
|
||||
}
|
||||
|
||||
export async function deleteSession(): Promise<void> {
|
||||
const id = currentSession.value;
|
||||
if (!id) return;
|
||||
try {
|
||||
await deleteChatSession(id);
|
||||
sessions.value = sessions.value.filter((s) => s.session_id !== id);
|
||||
currentSession.value = "";
|
||||
turns.value = [];
|
||||
if (sessions.value[0]) await selectSession(sessions.value[0].session_id);
|
||||
} catch (err) {
|
||||
sessionError.value = fail(err, "Couldn't delete the conversation");
|
||||
}
|
||||
}
|
||||
|
||||
/** Sends the last message of the conversation again, as a new turn. */
|
||||
export async function retryLast(turn?: ChatTurn): Promise<void> {
|
||||
const last = turn ?? turns.value.at(-1);
|
||||
if (last) await sendMessage({ textOverride: last.text });
|
||||
}
|
||||
|
||||
/** Stops the running turn, or the next queued one when none runs. */
|
||||
export function stopTurn(): void {
|
||||
const target = turns.value.find((t) => t.state === "running") ?? turns.value.find(unfinished);
|
||||
if (!target) return;
|
||||
statusText.value = "Stopping…";
|
||||
void cancelChatTurn(target.id)
|
||||
.then((t) => replaceTurn({ ...target, state: t.state }))
|
||||
.catch((err) => {
|
||||
sessionError.value = fail(err, "Couldn't stop the turn");
|
||||
});
|
||||
}
|
||||
|
||||
export function removeQueued(index: number): void {
|
||||
const turn = queuedTurns.value[index];
|
||||
if (!turn) return;
|
||||
void cancelChatTurn(turn.id)
|
||||
.then((t) => replaceTurn({ ...turn, state: t.state }))
|
||||
.catch((err) => {
|
||||
sessionError.value = fail(err, "Couldn't remove the queued message");
|
||||
});
|
||||
}
|
||||
|
||||
/** Moves a queued message back into the composer, after anything already typed. */
|
||||
export function editQueued(index: number): void {
|
||||
const turn = queuedTurns.value[index];
|
||||
if (!turn) return;
|
||||
removeQueued(index);
|
||||
composerText.value = composerText.value.trim() ? `${composerText.value}\n${turn.text}` : turn.text;
|
||||
}
|
||||
|
||||
let lastInput = { value: "", caret: 0 };
|
||||
|
||||
/** Opens the palette for the command the caret sits in, or closes it. */
|
||||
export function syncCommandMenu(value: string, caret: number): void {
|
||||
lastInput = { value, caret };
|
||||
const found = detectTrigger(lastInput.value, lastInput.caret);
|
||||
const matches = found?.trigger === "/" ? commandCompletions(commandSpecs.value, found.query) : [];
|
||||
if (!found || !matches.length) {
|
||||
isCommandMenuOpen.value = false;
|
||||
commandMatches.value = [];
|
||||
return;
|
||||
}
|
||||
if (!isCommandMenuOpen.value) commandSelection.value = 0;
|
||||
menuTrigger.value = found.trigger;
|
||||
commandMatches.value = matches;
|
||||
commandSelection.value = Math.min(commandSelection.value, Math.max(matches.length - 1, 0));
|
||||
isCommandMenuOpen.value = true;
|
||||
}
|
||||
|
||||
export function closeCommandMenu(): void {
|
||||
isCommandMenuOpen.value = false;
|
||||
}
|
||||
|
||||
export function moveCommandSelection(delta: number): void {
|
||||
const length = commandMatches.value.length;
|
||||
if (!length) return;
|
||||
commandSelection.value = (commandSelection.value + delta + length) % length;
|
||||
}
|
||||
|
||||
let approvalRead = 0;
|
||||
|
||||
export async function loadApprovals(): Promise<void> {
|
||||
const read = ++approvalRead;
|
||||
try {
|
||||
const pending = await pendingApprovals();
|
||||
if (read !== approvalRead) return;
|
||||
approvals.value = pending;
|
||||
approvalReadFailed.value = false;
|
||||
} catch (err) {
|
||||
if (read !== approvalRead) return;
|
||||
if (err instanceof Unauthorized) unauthorized.value = true;
|
||||
approvalReadFailed.value = true;
|
||||
}
|
||||
}
|
||||
|
||||
/** Answers an approval request. A reply in the conversation never does. */
|
||||
export async function answer(id: string, approved: boolean): Promise<void> {
|
||||
await answerApproval(id, approved);
|
||||
++approvalRead;
|
||||
approvals.value = approvals.value.filter((a) => a.id !== id);
|
||||
await loadApprovals();
|
||||
}
|
||||
|
||||
let noticeStream: AbortController | null = null;
|
||||
const noticeCursor = () => notices.value.at(-1)?.seq ?? 0;
|
||||
|
||||
async function catchUp(through?: number): Promise<void> {
|
||||
do {
|
||||
const more = await messagesAfter(noticeCursor(), noticeStream?.signal);
|
||||
if (more.length === 0) break;
|
||||
notices.value = [...notices.value, ...more];
|
||||
} while (through === undefined || noticeCursor() < through);
|
||||
await loadApprovals();
|
||||
await reloadTranscript();
|
||||
}
|
||||
|
||||
// Notifications and approval requests from runs, followed for as long as the
|
||||
// chat is mounted. The stream sends positions, not messages; the messages
|
||||
// after the last one held are read on each.
|
||||
async function followNotices(ctrl: AbortController): Promise<void> {
|
||||
try {
|
||||
notices.value = await latestMessages(ctrl.signal);
|
||||
noticeError.value = "";
|
||||
} catch (err) {
|
||||
if (ctrl.signal.aborted) return;
|
||||
noticeError.value = fail(err, "Couldn't load notifications");
|
||||
}
|
||||
let backoff = 1000;
|
||||
while (!ctrl.signal.aborted) {
|
||||
try {
|
||||
for await (const seq of composerStream(ctrl.signal, catchUp)) {
|
||||
backoff = 1000;
|
||||
if (seq > noticeCursor()) await catchUp(seq);
|
||||
}
|
||||
} catch (err) {
|
||||
if (ctrl.signal.aborted) return;
|
||||
if (err instanceof Unauthorized) {
|
||||
unauthorized.value = true;
|
||||
return;
|
||||
}
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, backoff));
|
||||
backoff = Math.min(backoff * 2, 30000);
|
||||
}
|
||||
}
|
||||
|
||||
let mounts = 0;
|
||||
|
||||
/**
|
||||
* Loads the conversations and follows run notifications for as long as a chat
|
||||
* surface is mounted. The dock and the composer page share one state, so the
|
||||
* first mount starts it and the last unmount stops it.
|
||||
*/
|
||||
export function useChat(): void {
|
||||
onMounted(() => {
|
||||
if (mounts++ > 0) return;
|
||||
const reopen = currentSession.value;
|
||||
refreshSessions()
|
||||
.then(() => (reopen ? selectSession(reopen) : undefined))
|
||||
.catch((err) => {
|
||||
sessionError.value = fail(err, "Couldn't load conversations");
|
||||
});
|
||||
void loadApprovals();
|
||||
noticeStream = new AbortController();
|
||||
void followNotices(noticeStream);
|
||||
});
|
||||
onUnmounted(() => {
|
||||
if (--mounts > 0) return;
|
||||
noticeStream?.abort();
|
||||
noticeStream = null;
|
||||
following?.abort();
|
||||
following = null;
|
||||
});
|
||||
}
|
||||
|
||||
/** Approval requests waiting for an answer that the open transcript doesn't show. */
|
||||
export const otherApprovals = computed(() => {
|
||||
const shown = new Set(
|
||||
messages.value.flatMap((m) => [...(m.approvals ?? []).map((a) => a.request_id), m.notice?.request_id ?? ""]),
|
||||
);
|
||||
return approvals.value.filter((a) => !shown.has(a.id));
|
||||
});
|
||||
|
||||
// A turn id is a run id to judgement and approvals: a card that names one
|
||||
// links to the conversation it came from, or else to the run.
|
||||
const origins = new Map<string, Promise<string | null>>();
|
||||
|
||||
/** The conversation a run id belongs to, or null when it is a workflow run. */
|
||||
export function conversationOf(runID: string): Promise<string | null> {
|
||||
let found = origins.get(runID);
|
||||
if (!found) {
|
||||
found = chatTurn(runID).then(
|
||||
(t) => t.session_id,
|
||||
() => null,
|
||||
);
|
||||
origins.set(runID, found);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
/**
|
||||
* The suggested prompts shown beside the chat composer, keyed off the page
|
||||
* the operator is on: the route's name, as the page tag reads it.
|
||||
*
|
||||
* Prompts are questions an operator would actually ask on that page, not
|
||||
* demonstrations of the feature.
|
||||
*/
|
||||
|
||||
/** The route as the page tag reads it; only these fields are consulted. */
|
||||
export interface SuggestionRoute {
|
||||
name?: unknown;
|
||||
params?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** The prompts for a route; a run page names the run it is open on. */
|
||||
export function suggestionsForRoute(route: SuggestionRoute): string[] {
|
||||
const name = typeof route.name === "string" ? route.name : "";
|
||||
switch (name) {
|
||||
case "run":
|
||||
return ["What did this run do?", "Why did this run end the way it did?", "Which actions did this run propose?"];
|
||||
case "runs":
|
||||
return ["Which runs failed recently?", "Summarise recent runs", "Which approvals are waiting on me?"];
|
||||
case "events":
|
||||
case "unmatched":
|
||||
return ["Which events arrived today?", "Why didn't my last event start a workflow?", "Which sources are sending events?"];
|
||||
case "classes":
|
||||
case "class":
|
||||
return ["Which actions run without approval?", "Which classes lost autonomy recently?", "What is waiting for my approval?"];
|
||||
case "extensions":
|
||||
case "credentials":
|
||||
case "sources":
|
||||
case "triggers":
|
||||
case "settings":
|
||||
case "controls":
|
||||
case "people":
|
||||
return ["Which model is Archie using right now?", "How do I connect a new source?", "Which extensions are running?"];
|
||||
default:
|
||||
return ["Summarise recent runs", "Which approvals are waiting on me?", "What needs my attention?"];
|
||||
}
|
||||
}
|
||||
@@ -1,44 +0,0 @@
|
||||
import { computed, ref, watch } from "vue";
|
||||
|
||||
import { isLoadingSession, messages, type ChatMessage } from "./state";
|
||||
|
||||
/**
|
||||
* Counts the replies the operator has not seen. A reply is seen once the
|
||||
* conversation is open and scrolled to its end; one that lands before that,
|
||||
* such as a run's notification while the dock is collapsed or the reader is
|
||||
* scrolled up, adds to the count until then.
|
||||
*
|
||||
* It counts finished replies and run cards by position.
|
||||
*/
|
||||
const dockOpen = ref(false);
|
||||
const atEnd = ref(false);
|
||||
const seen = ref(0);
|
||||
|
||||
function isReply(message: ChatMessage): boolean {
|
||||
return message.from !== "web" && !message.live;
|
||||
}
|
||||
|
||||
const total = computed(() => messages.value.filter(isReply).length);
|
||||
const viewing = computed(() => dockOpen.value && atEnd.value);
|
||||
|
||||
export const unseenCount = computed(() => Math.max(0, total.value - seen.value));
|
||||
|
||||
// Opening or switching a conversation loads it, which is not news; a reload
|
||||
// that drops a message must also lower the mark so the next reply still counts.
|
||||
watch(
|
||||
[total, viewing, isLoadingSession],
|
||||
([count, watching, loading], [, , wasLoading]) => {
|
||||
if (watching || loading || wasLoading || count < seen.value) seen.value = count;
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
/** The dock reports whether the conversation is open above the composer. */
|
||||
export function setDockOpen(open: boolean): void {
|
||||
dockOpen.value = open;
|
||||
}
|
||||
|
||||
/** The scroller's jump button reports whether the reader is at the end. */
|
||||
export function setAtEnd(end: boolean): void {
|
||||
atEnd.value = end;
|
||||
}
|
||||
@@ -1,13 +0,0 @@
|
||||
import { createPinia } from "pinia";
|
||||
import { createApp } from "vue";
|
||||
|
||||
import { useAppearanceStore } from "@/stores/appearance";
|
||||
import App from "./App.vue";
|
||||
import router from "./router";
|
||||
import "@/style.css";
|
||||
|
||||
const app = createApp(App);
|
||||
const pinia = createPinia();
|
||||
app.use(pinia).use(router);
|
||||
useAppearanceStore(pinia).initialize();
|
||||
app.mount("#app");
|
||||
@@ -1,22 +0,0 @@
|
||||
import { createRouter, createWebHistory } from "vue-router";
|
||||
|
||||
export default createRouter({
|
||||
history: createWebHistory(),
|
||||
routes: [
|
||||
{ path: "/", redirect: "/composer" },
|
||||
{ path: "/composer", name: "composer", meta: { label: "Composer" }, component: () => import("./ComposerView.vue") },
|
||||
{ path: "/runs", name: "runs", meta: { label: "Runs" }, component: () => import("./RunsView.vue") },
|
||||
{ path: "/unmatched", name: "unmatched", meta: { label: "Unmatched" }, component: () => import("./UnmatchedView.vue") },
|
||||
{ path: "/classes", name: "classes", meta: { label: "Classes" }, component: () => import("./ClassesView.vue") },
|
||||
{ path: "/classes/:id", name: "class", meta: { label: "Class" }, component: () => import("./ClassView.vue"), props: true },
|
||||
{ path: "/people", name: "people", meta: { label: "People" }, component: () => import("./PeopleView.vue") },
|
||||
{ path: "/controls", name: "controls", meta: { label: "Controls" }, component: () => import("./ControlsView.vue") },
|
||||
{ path: "/extensions", name: "extensions", meta: { label: "Extensions" }, component: () => import("./ExtensionsView.vue") },
|
||||
{ path: "/sources", name: "sources", meta: { label: "Sources" }, component: () => import("./SourcesView.vue") },
|
||||
{ path: "/triggers", name: "triggers", meta: { label: "Triggers" }, component: () => import("./TriggersView.vue") },
|
||||
{ path: "/events", name: "events", meta: { label: "Events" }, component: () => import("./EventsView.vue") },
|
||||
{ path: "/credentials", name: "credentials", meta: { label: "Credentials" }, component: () => import("./CredentialsView.vue") },
|
||||
{ path: "/settings", name: "settings", meta: { label: "Settings" }, component: () => import("./SettingsView.vue") },
|
||||
{ path: "/runs/:id", name: "run", meta: { label: "Run" }, component: () => import("./RunView.vue"), props: true },
|
||||
],
|
||||
});
|
||||
@@ -1,32 +0,0 @@
|
||||
import type { Level, Run } from "./api";
|
||||
|
||||
/** The StatusDot tone for a run's state. */
|
||||
export function runTone(state: Run["state"]): "ok" | "warn" | "danger" | "info" | "idle" {
|
||||
switch (state) {
|
||||
case "succeeded":
|
||||
return "ok";
|
||||
case "failed":
|
||||
return "danger";
|
||||
case "running":
|
||||
case "queued":
|
||||
return "info";
|
||||
case "waiting":
|
||||
return "warn";
|
||||
default:
|
||||
return "idle";
|
||||
}
|
||||
}
|
||||
|
||||
const levelLabels: Record<Level, string> = {
|
||||
act_quietly: "Act quietly",
|
||||
act_and_tell: "Act and tell",
|
||||
propose_and_wait: "Propose and wait",
|
||||
escalate: "Escalate",
|
||||
never: "Never",
|
||||
};
|
||||
|
||||
export const levelLabel = (level: Level): string => levelLabels[level];
|
||||
|
||||
/** The class's own names, as one line. */
|
||||
export const className = (c: { connector: string; action: string; target_kind: string; environment: string }): string =>
|
||||
`${c.connector} ${c.action} on ${c.target_kind} in ${c.environment || "no environment"}`;
|
||||
@@ -1,51 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import { answerApproval, composerStream, resetClass, rotateAdminToken, setToken } from "../src/archie/api.ts";
|
||||
|
||||
test("composer stream rejects an unsafe saved token before Fetch", async () => {
|
||||
const originalFetch = globalThis.fetch;
|
||||
const originalStorage = Object.getOwnPropertyDescriptor(globalThis, "sessionStorage");
|
||||
const values = new Map<string, string>();
|
||||
Object.defineProperty(globalThis, "sessionStorage", {
|
||||
configurable: true,
|
||||
value: {
|
||||
getItem: (key: string) => values.get(key) ?? null,
|
||||
setItem: (key: string, value: string) => values.set(key, value),
|
||||
removeItem: (key: string) => values.delete(key),
|
||||
},
|
||||
});
|
||||
const fetchCalls: string[] = [];
|
||||
const authorization: string[] = [];
|
||||
globalThis.fetch = async (_input, init) => {
|
||||
fetchCalls.push(String(_input));
|
||||
authorization.push(new Headers(init?.headers).get("Authorization") ?? "");
|
||||
return new Response(null);
|
||||
};
|
||||
|
||||
try {
|
||||
assert.equal(setToken("valid-prefix-\u23CE"), false);
|
||||
assert.equal(values.has("archie.adminToken"), false);
|
||||
const invalidCalls = [
|
||||
() => composerStream(new AbortController().signal).next(),
|
||||
() => rotateAdminToken(),
|
||||
() => answerApproval("approval", true),
|
||||
() => resetClass("class"),
|
||||
];
|
||||
for (const invoke of invalidCalls) {
|
||||
values.set("archie.adminToken", "valid-prefix-\u23CE");
|
||||
await assert.rejects(invoke(), /Admin token contains unsupported characters/);
|
||||
assert.equal(fetchCalls.length, 0);
|
||||
assert.equal(values.has("archie.adminToken"), false);
|
||||
}
|
||||
|
||||
values.set("archie.adminToken", "plain-ascii-admin-token");
|
||||
assert.deepEqual(await composerStream(new AbortController().signal).next(), { done: true, value: undefined });
|
||||
assert.deepEqual(fetchCalls, ["/api/composer/stream"]);
|
||||
assert.deepEqual(authorization, ["Bearer plain-ascii-admin-token"]);
|
||||
} finally {
|
||||
globalThis.fetch = originalFetch;
|
||||
if (originalStorage) Object.defineProperty(globalThis, "sessionStorage", originalStorage);
|
||||
else Reflect.deleteProperty(globalThis, "sessionStorage");
|
||||
}
|
||||
});
|
||||
@@ -14,11 +14,6 @@ export default defineConfig({
|
||||
build: {
|
||||
outDir: "dist",
|
||||
emptyOutDir: true,
|
||||
rollupOptions: {
|
||||
// index.html is the dashboard the old services and the single binary
|
||||
// both serve; the binary still serves archie.html at /archie.html.
|
||||
input: { main: "index.html", archie: "archie.html" },
|
||||
},
|
||||
},
|
||||
server: {
|
||||
// Proxies the API to a locally running archie-ui (the process that serves
|
||||
|
||||
Reference in new issue
Block a user