feat(ui): integrate @ui-sdk for schedules, chat composer, and agent bridge
This commit is contained in:
18 files changed
+798
-440
No files matched your search
@@ -101,6 +101,14 @@ state; the UI presents them and submits operator choices.
|
||||
and table semantics. A hover action must also be reachable by keyboard.
|
||||
- Keep filtering and pagination consistent with the server. State limitations
|
||||
such as sorting only loaded rows when they affect the operator's decision.
|
||||
- `@ui-sdk/vue` and `@ui-sdk/core` are adopted incrementally alongside
|
||||
`components/ui` (`shadcn-vue` / Reka UI) for high-value interactive
|
||||
components and custom behaviors. Before writing or editing `@ui-sdk` code,
|
||||
read `node_modules/@ui-sdk/core/skills/ui-sdk/SKILL.md` and
|
||||
`node_modules/@ui-sdk/vue/docs/llms.txt` (and `core.md` / `rendering.md` when
|
||||
building a custom primitive). Give every `@ui-sdk` control a clear accessible
|
||||
name, sync state through change callbacks, and mark destructive actions with
|
||||
`data-agent-confirm`.
|
||||
|
||||
## Tests
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@
|
||||
"@lucide/vue": "^1.61.0",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@tanstack/vue-form": "^1.33.5",
|
||||
"@ui-sdk/core": "0.1.0-beta.16",
|
||||
"@ui-sdk/vue": "0.1.0-beta.16",
|
||||
"@vue-flow/background": "^1.3.2",
|
||||
"@vue-flow/core": "^1.48.2",
|
||||
"@vueuse/core": "^15.0.0",
|
||||
|
||||
Generated
+32
@@ -181,6 +181,12 @@ importers:
|
||||
'@tanstack/vue-form':
|
||||
specifier: ^1.33.5
|
||||
version: 1.33.5(vue@3.5.44(typescript@6.0.3))
|
||||
'@ui-sdk/core':
|
||||
specifier: 0.1.0-beta.16
|
||||
version: 0.1.0-beta.16
|
||||
'@ui-sdk/vue':
|
||||
specifier: 0.1.0-beta.16
|
||||
version: 0.1.0-beta.16(@ui-sdk/core@0.1.0-beta.16)(vue@3.5.44(typescript@6.0.3))
|
||||
'@vue-flow/background':
|
||||
specifier: ^1.3.2
|
||||
version: 1.3.2(@vue-flow/core@1.48.2(vue@3.5.44(typescript@6.0.3)))(vue@3.5.44(typescript@6.0.3))
|
||||
@@ -650,6 +656,25 @@ packages:
|
||||
'@types/web-bluetooth@0.0.21':
|
||||
resolution: {integrity: sha512-oIQLCGWtcFZy2JW77j9k8nHzAOpqMHLQejDA48XXMWH6tjCQHz5RCFz1bzsmROyL6PUm+LLnUiI4BCn221inxA==}
|
||||
|
||||
'@ui-sdk/core@0.1.0-beta.16':
|
||||
resolution: {integrity: sha512-I2GMqOviLS/lYfIj2lTqKLbae0V9uSnysK+bSdbhuw2De8zNvrLZiDTc0qzsPNiZvB/bMmUZJS5UDA5Q2Pq4Ng==}
|
||||
|
||||
'@ui-sdk/vue@0.1.0-beta.16':
|
||||
resolution: {integrity: sha512-9Y4aMVrrYrYDNBgiJs1AWW1S6giJQ7wfmyEvN6fU0j3gyO5qmLQ1xLBmZmuCQv1Wt0AIL9VfGpAclW4ZF45IOA==}
|
||||
peerDependencies:
|
||||
'@nuxt/kit': ^4.0.0 || ^5.0.0-0
|
||||
'@nuxt/schema': ^4.0.0 || ^5.0.0-0
|
||||
'@ui-sdk/core': ^0.1.0-beta.16
|
||||
nuxt: ^4.0.0 || ^5.0.0-0
|
||||
vue: '>=3.5'
|
||||
peerDependenciesMeta:
|
||||
'@nuxt/kit':
|
||||
optional: true
|
||||
'@nuxt/schema':
|
||||
optional: true
|
||||
nuxt:
|
||||
optional: true
|
||||
|
||||
'@ungap/structured-clone@1.4.0':
|
||||
resolution: {integrity: sha512-1mEZtMKPM09vDmQt5y7YvmN2+DFTP7Tg0EWXdic8/C6VRnpb33e4ghisCIE3WZjsE2N8mf+QV1Zqh7ZFYLWInQ==}
|
||||
|
||||
@@ -2016,6 +2041,13 @@ snapshots:
|
||||
|
||||
'@types/web-bluetooth@0.0.21': {}
|
||||
|
||||
'@ui-sdk/core@0.1.0-beta.16': {}
|
||||
|
||||
'@ui-sdk/vue@0.1.0-beta.16(@ui-sdk/core@0.1.0-beta.16)(vue@3.5.44(typescript@6.0.3))':
|
||||
dependencies:
|
||||
'@ui-sdk/core': 0.1.0-beta.16
|
||||
vue: 3.5.44(typescript@6.0.3)
|
||||
|
||||
'@ungap/structured-clone@1.4.0': {}
|
||||
|
||||
'@vitejs/plugin-vue@6.0.10(vite@8.3.5(@types/node@26.6.5)(jiti@2.7.0)(yaml@2.9.1))(vue@3.5.44(typescript@6.0.3))':
|
||||
|
||||
@@ -1,2 +1,5 @@
|
||||
allowBuilds:
|
||||
vue-demi: true
|
||||
minimumReleaseAgeExclude:
|
||||
- '@ui-sdk/core@0.1.0-beta.16'
|
||||
- '@ui-sdk/vue@0.1.0-beta.16'
|
||||
+179
-157
@@ -1,73 +1,65 @@
|
||||
<script setup lang="ts">
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { computed, nextTick, ref, watch } from "vue";
|
||||
|
||||
import { Clock, Mic, Pencil, X } from "@lucide/vue";
|
||||
import {
|
||||
createTokenInputController,
|
||||
TokenInput,
|
||||
TokenInputEditor,
|
||||
TokenInputToken,
|
||||
TokenInputTokenRemove,
|
||||
type TokenInputValue,
|
||||
} from "@ui-sdk/vue/token-input";
|
||||
import {
|
||||
type TriggerDefinition,
|
||||
type TriggerMenuDataItem,
|
||||
TriggerMenu,
|
||||
TriggerMenuContent,
|
||||
TriggerMenuEmpty,
|
||||
TriggerMenuItem,
|
||||
TriggerMenuList,
|
||||
} from "@ui-sdk/vue/trigger-menu";
|
||||
import { computed, nextTick, onMounted, ref, watch } from "vue";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { describeError } from "@/lib/api";
|
||||
import { isExactCommand, replaceToken } from "./commands";
|
||||
import ChatSlashPalette from "./ChatSlashPalette.vue";
|
||||
import { api, describeError, type WorkflowVersion } from "@/lib/api";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { useSessionStore } from "@/stores/session";
|
||||
import ChatSuggestions from "./ChatSuggestions.vue";
|
||||
import { serializePromptValue } from "./prompt-tokens";
|
||||
import {
|
||||
closeCommandMenu,
|
||||
commandMatches,
|
||||
commandSelection,
|
||||
commandSpecs,
|
||||
addTaskTag,
|
||||
clearPageTag,
|
||||
pageTag,
|
||||
placeholderHint,
|
||||
messages,
|
||||
commandSpecs,
|
||||
composerText,
|
||||
editQueued,
|
||||
menuTrigger,
|
||||
removeTaskTag,
|
||||
retryTasks,
|
||||
taskForKey,
|
||||
taskLoadError,
|
||||
taskTags,
|
||||
isCommandMenuOpen,
|
||||
isSending,
|
||||
moveCommandSelection,
|
||||
messages,
|
||||
pageTag,
|
||||
placeholderHint,
|
||||
queuedMessages,
|
||||
removeQueued,
|
||||
sendMessage,
|
||||
removeTaskTag,
|
||||
selectorData,
|
||||
sendMessage,
|
||||
sendVoice,
|
||||
stopTurn,
|
||||
syncCommandMenu,
|
||||
taskTags,
|
||||
type TaskRef,
|
||||
} from "./state";
|
||||
|
||||
/**
|
||||
* The composer: the text, the palette that completes a slash command, and the
|
||||
* two actions. It stays writeable and focused while a turn is in flight --
|
||||
* stopping is not the only thing an operator may want to do next -- so 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: the field's own chrome would draw a second box inside
|
||||
* the first. `bg-transparent!` beats the field's dark fill, which the dark
|
||||
* variant would otherwise re-apply over the shell. 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 }>();
|
||||
|
||||
// Voice: recorded in the browser, transcribed by the server like a Telegram
|
||||
// voice note. The mic shows only while the composer is empty.
|
||||
const session = useSessionStore();
|
||||
const prompt = createTokenInputController();
|
||||
|
||||
const canRecord = computed(
|
||||
() => !!selectorData.value.voice_available && typeof MediaRecorder !== "undefined" && !!navigator.mediaDevices?.getUserMedia,
|
||||
);
|
||||
const recording = ref(false);
|
||||
const recordError = ref("");
|
||||
let recorder: MediaRecorder | null = null;
|
||||
async function toggleRecording() {
|
||||
|
||||
async function toggleRecording(): Promise<void> {
|
||||
if (recorder) {
|
||||
recorder.stop();
|
||||
return;
|
||||
@@ -94,16 +86,12 @@ async function toggleRecording() {
|
||||
recording.value = true;
|
||||
}
|
||||
|
||||
const field = ref<{ $el: HTMLTextAreaElement } | null>(null);
|
||||
|
||||
function focus(): void {
|
||||
field.value?.$el?.focus();
|
||||
prompt.focus({ at: "end" });
|
||||
}
|
||||
|
||||
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) => {
|
||||
@@ -111,90 +99,104 @@ watch(
|
||||
},
|
||||
);
|
||||
|
||||
// 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);
|
||||
let syncingFromInput = false;
|
||||
|
||||
function onValueChange(value: TokenInputValue): void {
|
||||
syncingFromInput = true;
|
||||
composerText.value = serializePromptValue(value);
|
||||
syncingFromInput = false;
|
||||
}
|
||||
|
||||
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. A task leaves no text behind: it becomes
|
||||
// a tag above the field.
|
||||
let edit: { text: string; cursor: number };
|
||||
if (menuTrigger.value === "#") {
|
||||
const task = taskForKey(item.key);
|
||||
if (!task) return;
|
||||
addTaskTag(task);
|
||||
edit = replaceToken(input.value, caret, "");
|
||||
function syncControllerFromText(text: string): void {
|
||||
if (syncingFromInput) return;
|
||||
if (serializePromptValue(prompt.getValue()) === text) return;
|
||||
if (!text) {
|
||||
prompt.clear();
|
||||
} else {
|
||||
edit = replaceToken(input.value, caret, item.label);
|
||||
prompt.setValue([text]);
|
||||
}
|
||||
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();
|
||||
}
|
||||
onMounted(() => {
|
||||
if (composerText.value) syncControllerFromText(composerText.value);
|
||||
});
|
||||
|
||||
watch(composerText, syncControllerFromText);
|
||||
|
||||
function onSubmit(): void {
|
||||
if (!composerText.value.trim()) return;
|
||||
void sendMessage();
|
||||
}
|
||||
|
||||
type MenuEntry = TriggerMenuDataItem & { detail?: string };
|
||||
|
||||
async function searchTasks(query: string): Promise<MenuEntry[]> {
|
||||
if (session.sections?.tasks === false) return [];
|
||||
const list = await api.tasks<TaskRef[] | { tasks?: TaskRef[] }>();
|
||||
const rows = Array.isArray(list) ? list : (list.tasks ?? []);
|
||||
const q = query.trim().toLowerCase();
|
||||
return rows
|
||||
.filter((task) => `${task.id} ${task.title ?? ""}`.toLowerCase().includes(q))
|
||||
.slice(0, 8)
|
||||
.map((task) => ({
|
||||
value: String(task.id),
|
||||
label: `#${task.id}`,
|
||||
keywords: task.title ? [task.title] : [],
|
||||
detail: task.title ?? "",
|
||||
}));
|
||||
}
|
||||
|
||||
async function searchWorkflows(query: string): Promise<MenuEntry[]> {
|
||||
const list = await api.workflowList();
|
||||
const q = query.trim().toLowerCase();
|
||||
return list
|
||||
.filter((workflow: WorkflowVersion) => `${workflow.name} ${workflow.id}`.toLowerCase().includes(q))
|
||||
.slice(0, 8)
|
||||
.map((workflow: WorkflowVersion) => ({
|
||||
value: workflow.id,
|
||||
label: workflow.name,
|
||||
keywords: [workflow.id],
|
||||
detail: workflow.enabled ? "enabled" : "disabled",
|
||||
}));
|
||||
}
|
||||
|
||||
const triggers = computed<TriggerDefinition[]>(() => [
|
||||
{
|
||||
char: "/",
|
||||
boundary: "start",
|
||||
type: "command",
|
||||
items: commandSpecs.value.map((spec) => ({
|
||||
value: spec.command,
|
||||
label: spec.command,
|
||||
keywords: spec.description ? [spec.description] : [],
|
||||
detail: spec.description || spec.usage || "",
|
||||
})),
|
||||
},
|
||||
{
|
||||
char: "@",
|
||||
type: "workflow",
|
||||
items: searchWorkflows,
|
||||
},
|
||||
...(session.sections?.tasks !== false
|
||||
? [
|
||||
{
|
||||
char: "#",
|
||||
type: "task",
|
||||
items: searchTasks,
|
||||
} satisfies TriggerDefinition,
|
||||
]
|
||||
: []),
|
||||
]);
|
||||
|
||||
function menuHeading(trigger: string | null): string {
|
||||
if (trigger === "/") return "Commands";
|
||||
if (trigger === "#") return "Tasks";
|
||||
if (trigger === "@") return "Workflows";
|
||||
return "Suggestions";
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -247,56 +249,76 @@ function onKeydown(event: KeyboardEvent): void {
|
||||
/></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
|
||||
<TokenInput
|
||||
:controller="prompt"
|
||||
submit-shortcut="enter"
|
||||
: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',
|
||||
)
|
||||
"
|
||||
@value-change="onValueChange"
|
||||
@submit="onSubmit"
|
||||
>
|
||||
<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'"
|
||||
|
||||
<TokenInputEditor
|
||||
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"
|
||||
:placeholder="placeholderHint || 'Message Archie (@ workflow, # task, / command)'"
|
||||
:class="
|
||||
cn(
|
||||
'max-h-40 min-w-0 flex-1 overflow-y-auto bg-transparent text-label pointer-coarse:text-base outline-none',
|
||||
flat ? 'min-h-10 py-2.5 text-base leading-5' : 'min-h-11 py-1 leading-6',
|
||||
)
|
||||
"
|
||||
/>
|
||||
|
||||
<ChatSlashPalette
|
||||
v-if="isCommandMenuOpen"
|
||||
:matches="commandMatches"
|
||||
:selection="commandSelection"
|
||||
:label="menuTrigger === '#' ? 'Tasks' : 'Commands'"
|
||||
:error="menuTrigger === '#' ? taskLoadError : ''"
|
||||
@choose="choose"
|
||||
@retry="retryTasks"
|
||||
/>
|
||||
<TriggerMenu :triggers="triggers">
|
||||
<TriggerMenuContent
|
||||
side="top"
|
||||
align="start"
|
||||
class="z-50 min-w-64 max-w-sm rounded-lg border border-border bg-popover p-1 text-popover-foreground shadow-lg"
|
||||
>
|
||||
<TriggerMenuList v-slot="{ state }" class="max-h-60 overflow-auto">
|
||||
<div class="px-2 py-1 text-caption font-medium text-fg-muted">
|
||||
{{ menuHeading(state.trigger) }}
|
||||
</div>
|
||||
<TriggerMenuEmpty class="px-2 py-2 text-label text-fg-muted">No matches</TriggerMenuEmpty>
|
||||
<TriggerMenuItem
|
||||
v-for="item in state.items as MenuEntry[]"
|
||||
:key="item.value"
|
||||
:value="item.value"
|
||||
:label="item.label"
|
||||
class="flex cursor-default items-baseline justify-between gap-3 rounded-md px-2 py-1.5 text-label outline-none data-highlighted:bg-accent data-highlighted:text-accent-foreground"
|
||||
>
|
||||
<span class="font-medium">{{ item.label }}</span>
|
||||
<span v-if="item.detail" class="truncate text-caption text-fg-muted">{{ item.detail }}</span>
|
||||
</TriggerMenuItem>
|
||||
</TriggerMenuList>
|
||||
</TriggerMenuContent>
|
||||
</TriggerMenu>
|
||||
|
||||
<template #token="{ token }">
|
||||
<TokenInputToken
|
||||
class="mx-0.5 inline-flex items-center gap-1 rounded-sm border border-primary/25 bg-primary/10 px-1.5 py-0.5 align-baseline text-caption font-medium text-primary"
|
||||
>
|
||||
<span>{{ token.type === "workflow" ? `@${token.label}` : token.label }}</span>
|
||||
<TokenInputTokenRemove
|
||||
:aria-label="`Remove ${token.label}`"
|
||||
class="cursor-pointer rounded-sm text-fg-muted hover:text-foreground"
|
||||
>
|
||||
<X aria-hidden="true" class="size-3" />
|
||||
</TokenInputTokenRemove>
|
||||
</TokenInputToken>
|
||||
</template>
|
||||
|
||||
<!-- 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 v-if="isSending" variant="outline" size="sm" @click="stopTurn">Stop</Button>
|
||||
<Button
|
||||
v-if="canRecord && !composerText.trim()"
|
||||
size="sm"
|
||||
@@ -315,6 +337,6 @@ function onKeydown(event: KeyboardEvent): void {
|
||||
>{{ isSending ? "Queue" : "Send" }}</Button
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
</TokenInput>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,72 +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 the server accepts
|
||||
* after `/`, the tasks that can be attached after `#`. The arrow keys and the
|
||||
* pointer both land here. A failed read shows in place of the rows.
|
||||
*/
|
||||
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,102 +0,0 @@
|
||||
import type { ChatCommandSpec, TaskRef } 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. Two
|
||||
* triggers share it: `/` completes a command, `#` picks a task.
|
||||
*/
|
||||
|
||||
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 || "",
|
||||
}));
|
||||
}
|
||||
|
||||
/** Tasks matched on id and title, so `#12` and a title word both find one. */
|
||||
export function taskCompletions(tasks: TaskRef[], query: string): Completion[] {
|
||||
return tasks
|
||||
.filter((task) =>
|
||||
`${task.id} ${task.title ?? ""}`.toLowerCase().includes(query),
|
||||
)
|
||||
.slice(0, MAX_MATCHES)
|
||||
.map((task) => ({
|
||||
key: String(task.id),
|
||||
label: `#${task.id}`,
|
||||
detail: task.title ?? "",
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { TokenInputValue } from "@ui-sdk/core/token-input";
|
||||
|
||||
/**
|
||||
* Serializes a TokenInputValue into the plain text sent in a chat turn.
|
||||
* Commands keep their slash label, tasks emit `#<id>`, and workflows emit `@<name>`.
|
||||
*/
|
||||
export function serializePromptValue(value: TokenInputValue): string {
|
||||
return value
|
||||
.map((segment) => {
|
||||
if (typeof segment === "string") return segment;
|
||||
if (segment.type === "task") return `#${segment.value}`;
|
||||
if (segment.type === "workflow") return `@${segment.label}`;
|
||||
return segment.label;
|
||||
})
|
||||
.join("");
|
||||
}
|
||||
@@ -4,8 +4,6 @@ import { errors } from "@/copy/errors";
|
||||
import { api, describeError, type ChatTurnRecord } from "@/lib/api";
|
||||
import { router } from "@/router";
|
||||
import { answerApproval } from "@/runs/answer";
|
||||
import { useSessionStore } from "@/stores/session";
|
||||
import { commandCompletions, detectTrigger, taskCompletions, type Completion, type Trigger } from "./commands";
|
||||
import {
|
||||
resolveTurn,
|
||||
retryChatTurn,
|
||||
@@ -291,13 +289,6 @@ export const selectedModel = ref("");
|
||||
export const chatModelReady = computed(() => !!selectorData.value.active_model);
|
||||
|
||||
export const commandSpecs = ref<ChatCommandSpec[]>([]);
|
||||
export const commandMatches = ref<Completion[]>([]);
|
||||
/** Which trigger the open menu was opened by. */
|
||||
export const menuTrigger = ref<Trigger>("/");
|
||||
/** Why the task list could not be read; shown in the menu, with a retry. */
|
||||
export const taskLoadError = ref("");
|
||||
export const commandSelection = ref(0);
|
||||
export const isCommandMenuOpen = ref(false);
|
||||
|
||||
/**
|
||||
* How many layers inside the panel currently own Escape -- an open popover, a
|
||||
@@ -657,91 +648,6 @@ export function editQueued(index: number): void {
|
||||
composerText.value = composerText.value.trim() ? `${composerText.value}\n${text}` : text;
|
||||
}
|
||||
|
||||
let taskChoices: TaskRef[] = [];
|
||||
let loadGeneration = 0;
|
||||
let lastInput = { value: "", caret: 0 };
|
||||
|
||||
async function loadTasks(): Promise<void> {
|
||||
const generation = ++loadGeneration;
|
||||
try {
|
||||
const page = await api.taskPage<TaskRef>({ limit: 100 });
|
||||
if (generation !== loadGeneration) return;
|
||||
taskChoices = page.tasks;
|
||||
taskLoadError.value = "";
|
||||
} catch (err) {
|
||||
if (generation !== loadGeneration) return;
|
||||
taskLoadError.value = describeError(err, errors.chat.tasks.load);
|
||||
}
|
||||
renderMenu();
|
||||
}
|
||||
|
||||
/** Reads the task list again after a failure, for the menu's Retry. */
|
||||
export function retryTasks(): void {
|
||||
taskLoadError.value = "";
|
||||
void loadTasks();
|
||||
}
|
||||
|
||||
/** Opens the palette for the trigger word the caret sits in, or closes it. */
|
||||
export function syncCommandMenu(value: string, caret: number): void {
|
||||
lastInput = { value, caret };
|
||||
// The list is read when # is first typed, so it is never older than the
|
||||
// moment the operator reached for it.
|
||||
if (
|
||||
tasksBacked() &&
|
||||
detectTrigger(value, caret)?.trigger === "#" &&
|
||||
(!isCommandMenuOpen.value || menuTrigger.value !== "#")
|
||||
) {
|
||||
taskLoadError.value = "";
|
||||
void loadTasks();
|
||||
}
|
||||
renderMenu();
|
||||
}
|
||||
|
||||
// # attaches a task, which needs the server's task list; without one the
|
||||
// trigger is plain text.
|
||||
function tasksBacked(): boolean {
|
||||
return useSessionStore().sections?.tasks !== false;
|
||||
}
|
||||
|
||||
function renderMenu(): void {
|
||||
const trigger = detectTrigger(lastInput.value, lastInput.caret);
|
||||
const found = trigger?.trigger === "#" && !tasksBacked() ? null : trigger;
|
||||
let matches: Completion[] = [];
|
||||
if (found?.trigger === "/") {
|
||||
matches = commandCompletions(commandSpecs.value, found.query);
|
||||
} else if (found?.trigger === "#") {
|
||||
matches = taskCompletions(taskChoices, found.query);
|
||||
}
|
||||
const showsError = found?.trigger === "#" && !!taskLoadError.value;
|
||||
if (!found || (!matches.length && !showsError)) {
|
||||
isCommandMenuOpen.value = false;
|
||||
commandMatches.value = [];
|
||||
return;
|
||||
}
|
||||
if (!isCommandMenuOpen.value || menuTrigger.value !== found.trigger) {
|
||||
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;
|
||||
}
|
||||
|
||||
/** The task a menu row stands for. */
|
||||
export function taskForKey(key: string): TaskRef | undefined {
|
||||
return taskChoices.find((task) => String(task.id) === key);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/** The page the operator is on, without the hash the server never sees. */
|
||||
function currentPage(): string {
|
||||
return router.currentRoute.value.fullPath.split("#")[0] || "/";
|
||||
@@ -803,11 +709,9 @@ export async function sendMessage(retryOpts?: RetryOptions): Promise<void> {
|
||||
}
|
||||
queuedMessages.value = [...queuedMessages.value, text];
|
||||
if (explicitText === undefined) clearDraft();
|
||||
closeCommandMenu();
|
||||
return;
|
||||
}
|
||||
|
||||
closeCommandMenu();
|
||||
isSending.value = true;
|
||||
statusText.value = isRetry ? "Retrying…" : "Thinking…";
|
||||
|
||||
|
||||
@@ -4,10 +4,12 @@
|
||||
// the UI calls, so the agent and the interface exercise one set of endpoints,
|
||||
// one CSRF header, and one error shape.
|
||||
import { api } from "./api";
|
||||
import { uiAgent, uiAgentWebMcpTools } from "./ui-agent";
|
||||
import { createWebMcpRegistrar } from "./webmcp";
|
||||
import { archieWebMcpTools } from "./webmcp-tools";
|
||||
|
||||
/** Registers the dashboard's tools, replacing any earlier registration. */
|
||||
export const registerArchieWebMcpTools = createWebMcpRegistrar(
|
||||
archieWebMcpTools(api),
|
||||
);
|
||||
/** Registers the dashboard's API and @ui-sdk component tools, replacing any earlier registration. */
|
||||
export const registerArchieWebMcpTools = createWebMcpRegistrar([
|
||||
...archieWebMcpTools(api),
|
||||
...uiAgentWebMcpTools(uiAgent),
|
||||
]);
|
||||
@@ -0,0 +1,118 @@
|
||||
import { agentTools, createAgent, type AgentAction, type AgentStep } from "@ui-sdk/vue/agent";
|
||||
|
||||
import type { WebMcpTool } from "./webmcp";
|
||||
|
||||
export type UiAgent = ReturnType<typeof createAgent>;
|
||||
|
||||
type ConfirmHandler = (
|
||||
step: AgentAction,
|
||||
context: { signal: AbortSignal },
|
||||
) => boolean | Promise<boolean>;
|
||||
|
||||
let confirmHandler: ConfirmHandler | null = null;
|
||||
|
||||
/** Registers an operator confirmation handler for steps marked with data-agent-confirm. */
|
||||
export function setUiAgentConfirmHandler(handler: ConfirmHandler | null): void {
|
||||
confirmHandler = handler;
|
||||
}
|
||||
|
||||
/** Creates a @ui-sdk agent bridge that refuses unconfirmed data-agent-confirm steps. */
|
||||
export function createUiAgent(allowConfirm?: ConfirmHandler): UiAgent {
|
||||
return createAgent({
|
||||
allow: (step, context) => {
|
||||
if (!step.confirm) return true;
|
||||
const handler = allowConfirm ?? confirmHandler;
|
||||
return handler ? handler(step, context) : false;
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared dashboard UI agent bridge. Instantiated at module load before the Vue
|
||||
* app mounts so every @ui-sdk component registers its contract as it mounts.
|
||||
*/
|
||||
export const uiAgent = createUiAgent();
|
||||
|
||||
function jsonEnvelope(value: unknown): { content: Array<{ type: "text"; text: string }> } {
|
||||
return { content: [{ type: "text", text: JSON.stringify(value, null, 2) }] };
|
||||
}
|
||||
|
||||
/** Exposes @ui-sdk's snapshot, query, and act bridge as WebMCP tools. */
|
||||
export function uiAgentWebMcpTools(agent: UiAgent = uiAgent): WebMcpTool[] {
|
||||
const byName = new Map(agentTools.map((tool) => [tool.name, tool]));
|
||||
const snapshotDef = byName.get("snapshot");
|
||||
const queryDef = byName.get("query");
|
||||
const actDef = byName.get("act");
|
||||
|
||||
return [
|
||||
{
|
||||
name: "ui_snapshot",
|
||||
description:
|
||||
snapshotDef?.description ??
|
||||
"List the mounted @ui-sdk dashboard components, their state, and their bounded actions. Read-only.",
|
||||
inputSchema: (snapshotDef?.inputSchema as Record<string, unknown>) ?? {
|
||||
type: "object",
|
||||
properties: {},
|
||||
additionalProperties: false,
|
||||
},
|
||||
annotations: { readOnlyHint: true, untrustedContentHint: true },
|
||||
execute: () => jsonEnvelope(agent.snapshot()),
|
||||
},
|
||||
{
|
||||
name: "ui_query",
|
||||
description:
|
||||
queryDef?.description ??
|
||||
"Find mounted @ui-sdk dashboard components or list items by label, text, or kind. Read-only.",
|
||||
inputSchema: (queryDef?.inputSchema as Record<string, unknown>) ?? {
|
||||
type: "object",
|
||||
properties: {
|
||||
text: { type: "string" },
|
||||
within: { type: "string" },
|
||||
kind: { type: "string" },
|
||||
},
|
||||
additionalProperties: false,
|
||||
},
|
||||
annotations: { readOnlyHint: true, untrustedContentHint: true },
|
||||
execute: async (input) =>
|
||||
jsonEnvelope(
|
||||
await agent.query({
|
||||
text: typeof input.text === "string" ? input.text : undefined,
|
||||
within: typeof input.within === "string" ? input.within : undefined,
|
||||
kind: typeof input.kind === "string" ? input.kind : undefined,
|
||||
}),
|
||||
),
|
||||
},
|
||||
{
|
||||
name: "ui_act",
|
||||
description:
|
||||
actDef?.description ??
|
||||
"Run bounded actions on mounted @ui-sdk dashboard components in order. Steps marked for confirmation require operator approval.",
|
||||
inputSchema: (actDef?.inputSchema as Record<string, unknown>) ?? {
|
||||
type: "object",
|
||||
properties: {
|
||||
steps: {
|
||||
type: "array",
|
||||
items: {
|
||||
type: "object",
|
||||
properties: {
|
||||
ref: { type: "string" },
|
||||
action: { type: "string" },
|
||||
args: { type: "array" },
|
||||
},
|
||||
required: ["ref", "action"],
|
||||
},
|
||||
},
|
||||
},
|
||||
required: ["steps"],
|
||||
additionalProperties: false,
|
||||
},
|
||||
annotations: { readOnlyHint: false, consequentialHint: true },
|
||||
execute: async (input) => {
|
||||
if (!Array.isArray(input.steps)) {
|
||||
throw new Error("ui_act: steps must be an array");
|
||||
}
|
||||
return jsonEnvelope(await agent.act({ steps: input.steps as AgentStep[] }));
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
<script setup lang="ts">
|
||||
import { CheckIcon } from "@lucide/vue";
|
||||
import { Checkbox, CheckboxGroup, CheckboxIndicator } from "@ui-sdk/vue/checkbox";
|
||||
import { Field, FieldLabel } from "@ui-sdk/vue/field";
|
||||
import { Input as SdkInput } from "@ui-sdk/vue/input";
|
||||
import { NumberInput, NumberInputControl, NumberInputGroup } from "@ui-sdk/vue/number-input";
|
||||
import { Radio, RadioGroup, RadioIndicator } from "@ui-sdk/vue/radio";
|
||||
import { TimeInput } from "@ui-sdk/vue/time-input";
|
||||
import { computed, ref, watch } from "vue";
|
||||
|
||||
import { cronForRule, parseCronRule } from "./cron-rule";
|
||||
import { cronWords } from "./schedule";
|
||||
|
||||
type Cadence = "daily" | "weekly" | "monthly" | "custom";
|
||||
|
||||
const model = defineModel<string>({ default: "0 9 * * 1-5" });
|
||||
|
||||
const cadence = ref<Cadence>("weekly");
|
||||
const time = ref<string | null>("09:00");
|
||||
const weekdays = ref<string[]>(["1", "2", "3", "4", "5"]);
|
||||
const monthDay = ref<number | null>(1);
|
||||
const customExpression = ref("");
|
||||
|
||||
const cadenceOptions: readonly { value: Cadence; label: string }[] = [
|
||||
{ value: "daily", label: "Daily" },
|
||||
{ value: "weekly", label: "Weekly" },
|
||||
{ value: "monthly", label: "Monthly" },
|
||||
{ value: "custom", label: "Custom" },
|
||||
];
|
||||
|
||||
const weekdayOptions = [
|
||||
{ value: "0", label: "Sun" },
|
||||
{ value: "1", label: "Mon" },
|
||||
{ value: "2", label: "Tue" },
|
||||
{ value: "3", label: "Wed" },
|
||||
{ value: "4", label: "Thu" },
|
||||
{ value: "5", label: "Fri" },
|
||||
{ value: "6", label: "Sat" },
|
||||
] as const;
|
||||
|
||||
let syncingFromModel = false;
|
||||
|
||||
function hydrateFromExpression(expression: string): void {
|
||||
syncingFromModel = true;
|
||||
const parsed = parseCronRule(expression);
|
||||
if (!parsed) {
|
||||
cadence.value = "custom";
|
||||
customExpression.value = expression;
|
||||
} else {
|
||||
cadence.value = parsed.cadence;
|
||||
time.value = parsed.time;
|
||||
if (parsed.cadence === "weekly") {
|
||||
weekdays.value = parsed.weekdays.map(String);
|
||||
} else if (parsed.cadence === "monthly") {
|
||||
monthDay.value = parsed.day;
|
||||
}
|
||||
customExpression.value = expression;
|
||||
}
|
||||
syncingFromModel = false;
|
||||
}
|
||||
|
||||
watch(
|
||||
model,
|
||||
(value) => {
|
||||
if (value === generatedExpression.value) return;
|
||||
hydrateFromExpression(value ?? "");
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const generatedExpression = computed<string | null>(() => {
|
||||
if (cadence.value === "custom") {
|
||||
return customExpression.value.trim() || null;
|
||||
}
|
||||
const clock = time.value;
|
||||
if (!clock) return null;
|
||||
if (cadence.value === "weekly") {
|
||||
return cronForRule({ cadence: "weekly", time: clock, weekdays: weekdays.value.map(Number) });
|
||||
}
|
||||
if (cadence.value === "monthly") {
|
||||
return monthDay.value === null ? null : cronForRule({ cadence: "monthly", time: clock, day: monthDay.value });
|
||||
}
|
||||
return cronForRule({ cadence: "daily", time: clock });
|
||||
});
|
||||
|
||||
watch(generatedExpression, (expr) => {
|
||||
if (syncingFromModel || expr === null) return;
|
||||
if (model.value !== expr) {
|
||||
model.value = expr;
|
||||
}
|
||||
});
|
||||
|
||||
function onCadenceChange(value: string | null): void {
|
||||
if (!value) return;
|
||||
const next = value as Cadence;
|
||||
cadence.value = next;
|
||||
if (next === "custom") {
|
||||
customExpression.value = model.value || "0 9 * * 1-5";
|
||||
} else if (!time.value) {
|
||||
time.value = "09:00";
|
||||
}
|
||||
}
|
||||
|
||||
const previewWords = computed(() => {
|
||||
const expr = generatedExpression.value;
|
||||
if (!expr) return "";
|
||||
const words = cronWords(expr);
|
||||
return words === expr ? "" : words;
|
||||
});
|
||||
|
||||
const validationHint = computed(() => {
|
||||
if (cadence.value === "custom") return customExpression.value.trim() ? "" : "Enter a five-field cron expression.";
|
||||
if (!time.value) return "Choose a valid time.";
|
||||
if (cadence.value === "weekly" && weekdays.value.length === 0) return "Select at least one day.";
|
||||
if (cadence.value === "monthly" && (monthDay.value === null || monthDay.value < 1 || monthDay.value > 31)) {
|
||||
return "Choose a day from 1 to 31.";
|
||||
}
|
||||
return "";
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="space-y-3">
|
||||
<Field class="flex flex-col gap-1.5">
|
||||
<FieldLabel class="text-caption font-medium text-fg-muted">Repeats</FieldLabel>
|
||||
<RadioGroup :value="cadence" class="grid grid-cols-2 gap-1.5 sm:grid-cols-4" @update:value="onCadenceChange">
|
||||
<label
|
||||
v-for="option in cadenceOptions"
|
||||
:key="option.value"
|
||||
class="flex cursor-pointer items-center gap-2 rounded-md border border-border bg-background px-2.5 py-2 text-label font-medium transition-colors hover:bg-muted/50 focus-within:ring-2 focus-within:ring-ring has-[[data-checked]]:border-primary has-[[data-checked]]:bg-primary/5 has-[[data-checked]]:text-primary motion-reduce:transition-none"
|
||||
>
|
||||
<Radio
|
||||
:value="option.value"
|
||||
class="grid size-3.5 shrink-0 place-items-center rounded-full border border-input bg-background text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring data-checked:border-primary"
|
||||
>
|
||||
<RadioIndicator class="size-1.5 rounded-full bg-current" />
|
||||
</Radio>
|
||||
{{ option.label }}
|
||||
</label>
|
||||
</RadioGroup>
|
||||
</Field>
|
||||
|
||||
<div v-if="cadence !== 'custom'" class="grid gap-3 sm:grid-cols-2">
|
||||
<Field class="flex flex-col gap-1.5">
|
||||
<FieldLabel class="text-caption font-medium text-fg-muted">Time</FieldLabel>
|
||||
<TimeInput
|
||||
v-model:value="time"
|
||||
:hour-cycle="24"
|
||||
class="inline-flex h-9 w-fit items-center gap-1 rounded-md border border-input bg-background px-2.5 font-mono text-label shadow-xs focus-within:ring-2 focus-within:ring-ring/40"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<Field v-if="cadence === 'monthly'" class="flex flex-col gap-1.5">
|
||||
<FieldLabel class="text-caption font-medium text-fg-muted">Day of month</FieldLabel>
|
||||
<NumberInput v-model:value="monthDay" :min="1" :max="31" class="w-28">
|
||||
<NumberInputGroup class="flex h-9 items-center rounded-md border border-input bg-background shadow-xs focus-within:ring-2 focus-within:ring-ring/40">
|
||||
<NumberInputControl aria-label="Day of month" class="h-9 w-full bg-transparent px-2.5 font-mono text-label outline-none" />
|
||||
</NumberInputGroup>
|
||||
</NumberInput>
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
<Field v-if="cadence === 'weekly'" class="flex flex-col gap-1.5">
|
||||
<FieldLabel class="text-caption font-medium text-fg-muted">Days</FieldLabel>
|
||||
<CheckboxGroup v-model:value="weekdays" class="grid grid-cols-4 gap-1.5 sm:grid-cols-7">
|
||||
<label
|
||||
v-for="day in weekdayOptions"
|
||||
:key="day.value"
|
||||
class="flex cursor-pointer items-center justify-center gap-1 rounded-md border border-border bg-background px-1.5 py-1.5 text-caption font-medium transition-colors hover:bg-muted/50 focus-within:ring-2 focus-within:ring-ring has-[[data-checked]]:border-primary has-[[data-checked]]:bg-primary/5 has-[[data-checked]]:text-primary motion-reduce:transition-none"
|
||||
>
|
||||
<Checkbox
|
||||
:value="day.value"
|
||||
class="grid size-3.5 shrink-0 place-items-center rounded border border-input bg-background text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring data-checked:border-primary"
|
||||
>
|
||||
<CheckboxIndicator class="size-2.5"><CheckIcon aria-hidden="true" class="size-2.5" /></CheckboxIndicator>
|
||||
</Checkbox>
|
||||
{{ day.label }}
|
||||
</label>
|
||||
</CheckboxGroup>
|
||||
</Field>
|
||||
|
||||
<Field v-if="cadence === 'custom'" class="flex flex-col gap-1.5">
|
||||
<FieldLabel class="text-caption font-medium text-fg-muted">Cron expression</FieldLabel>
|
||||
<SdkInput
|
||||
v-model:value="customExpression"
|
||||
placeholder="0 9 * * 1-5"
|
||||
class="h-9 w-56 rounded-md border border-input bg-background px-2.5 font-mono text-label shadow-xs outline-none focus-visible:ring-2 focus-visible:ring-ring/40"
|
||||
/>
|
||||
</Field>
|
||||
|
||||
<div class="flex flex-wrap items-baseline justify-between gap-2 rounded-md border border-border bg-muted/40 px-3 py-2">
|
||||
<output aria-live="polite" class="font-mono text-label font-medium text-foreground">
|
||||
{{ generatedExpression ?? "— — — — —" }}
|
||||
</output>
|
||||
<span v-if="previewWords" class="text-caption text-fg-muted">{{ previewWords }}</span>
|
||||
<span v-else-if="validationHint" class="text-caption text-danger" role="status">{{ validationHint }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -11,7 +11,8 @@ import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
|
||||
import { api, describeError } from "@/lib/api";
|
||||
import { errors } from "@/copy/errors";
|
||||
import { useAppearanceStore } from "@/stores/appearance";
|
||||
import { cronWords, fromWallTime, toWallTime, type Schedule, type ScheduleTiming } from "./schedule";
|
||||
import CronRuleBuilder from "./CronRuleBuilder.vue";
|
||||
import { fromWallTime, toWallTime, type Schedule, type ScheduleTiming } from "./schedule";
|
||||
|
||||
/**
|
||||
* Creates or edits one schedule. A built-in schedule keeps its name; only its
|
||||
@@ -54,10 +55,6 @@ const wallTime = computed({
|
||||
get: () => toWallTime(timing.value.at, appearance.timeZone),
|
||||
set: (value: string) => (timing.value.at = fromWallTime(value, appearance.timeZone)),
|
||||
});
|
||||
const cronPreview = computed(() => {
|
||||
const words = cronWords(timing.value.cron);
|
||||
return words === timing.value.cron ? "" : words;
|
||||
});
|
||||
|
||||
async function save(): Promise<void> {
|
||||
if (!props.schedule) return;
|
||||
@@ -93,10 +90,7 @@ async function save(): Promise<void> {
|
||||
<ToggleGroupItem v-for="option in kinds" :key="option.value" :value="option.value">{{ option.label }}</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
<DurationInput v-if="timing.kind === 'interval'" v-model="timing.interval!" :units="['m', 'h']" />
|
||||
<div v-else-if="timing.kind === 'cron'" class="space-y-1">
|
||||
<Input v-model="timing.cron" class="w-48 font-mono" placeholder="0 9 * * 1-5" aria-label="Cron expression" />
|
||||
<p v-if="cronPreview" class="text-caption text-fg-muted">{{ cronPreview }}</p>
|
||||
</div>
|
||||
<CronRuleBuilder v-else-if="timing.kind === 'cron'" v-model="timing.cron" />
|
||||
<Input v-else v-model="wallTime" type="datetime-local" class="w-60 font-mono" aria-label="Run at" required />
|
||||
</div>
|
||||
</SettingRow>
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
export type CronRule =
|
||||
| { cadence: "daily"; time: string }
|
||||
| { cadence: "weekly"; time: string; weekdays: readonly number[] }
|
||||
| { cadence: "monthly"; time: string; day: number };
|
||||
|
||||
const NUMBER = /^\d+$/;
|
||||
|
||||
function clockFields(time: string): [number, number] | null {
|
||||
const match = /^(\d{2}):(\d{2})$/.exec(time);
|
||||
if (!match) return null;
|
||||
const hour = Number(match[1]);
|
||||
const minute = Number(match[2]);
|
||||
if (hour > 23 || minute > 59) return null;
|
||||
return [hour, minute];
|
||||
}
|
||||
|
||||
function weekdayField(values: readonly number[]): string | null {
|
||||
if (!values.length || values.some((day) => !Number.isInteger(day) || day < 0 || day > 6)) {
|
||||
return null;
|
||||
}
|
||||
const days = [...new Set(values)].sort((a, b) => a - b);
|
||||
if (days.length === 7) return "*";
|
||||
if (days.join(",") === "1,2,3,4,5") return "1-5";
|
||||
if (days.join(",") === "0,6") return "0,6";
|
||||
return days.join(",");
|
||||
}
|
||||
|
||||
function parseWeekdays(field: string): number[] | null {
|
||||
if (field === "1-5") return [1, 2, 3, 4, 5];
|
||||
const parts = field.split(",");
|
||||
if (!parts.length) return null;
|
||||
const days: number[] = [];
|
||||
for (const part of parts) {
|
||||
if (!NUMBER.test(part)) return null;
|
||||
const value = Number(part);
|
||||
if (value < 0 || value > 7) return null;
|
||||
days.push(value % 7);
|
||||
}
|
||||
return [...new Set(days)].sort((a, b) => a - b);
|
||||
}
|
||||
|
||||
/** Emits a canonical 5-field cron expression for a guided recurrence rule. */
|
||||
export function cronForRule(rule: CronRule): string | null {
|
||||
const clock = clockFields(rule.time);
|
||||
if (!clock) return null;
|
||||
const [hour, minute] = clock;
|
||||
if (rule.cadence === "daily") return `${minute} ${hour} * * *`;
|
||||
if (rule.cadence === "weekly") {
|
||||
const weekdays = weekdayField(rule.weekdays);
|
||||
return weekdays === null ? null : `${minute} ${hour} * * ${weekdays}`;
|
||||
}
|
||||
if (rule.cadence === "monthly") {
|
||||
return Number.isInteger(rule.day) && rule.day >= 1 && rule.day <= 31
|
||||
? `${minute} ${hour} ${rule.day} * *`
|
||||
: null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Parses a 5-field cron expression into a guided recurrence rule, or null if custom. */
|
||||
export function parseCronRule(expression: string | undefined): CronRule | null {
|
||||
const fields = (expression ?? "").trim().split(/\s+/);
|
||||
if (fields.length !== 5) return null;
|
||||
const [minuteField, hourField, domField, monthField, dowField] = fields as [
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
string,
|
||||
];
|
||||
if (monthField !== "*" || !NUMBER.test(minuteField) || !NUMBER.test(hourField)) return null;
|
||||
const minute = Number(minuteField);
|
||||
const hour = Number(hourField);
|
||||
if (minute > 59 || hour > 23) return null;
|
||||
const time = `${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`;
|
||||
|
||||
if (domField !== "*") {
|
||||
if (dowField !== "*" || !NUMBER.test(domField)) return null;
|
||||
const day = Number(domField);
|
||||
return day >= 1 && day <= 31 ? { cadence: "monthly", time, day } : null;
|
||||
}
|
||||
if (dowField === "*") return { cadence: "daily", time };
|
||||
const weekdays = parseWeekdays(dowField);
|
||||
return weekdays?.length ? { cadence: "weekly", time, weekdays } : null;
|
||||
}
|
||||
@@ -48,6 +48,8 @@
|
||||
unicode-range: U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF;
|
||||
}
|
||||
|
||||
@layer ui-sdk;
|
||||
|
||||
@import "tailwindcss";
|
||||
@import "tw-animate-css";
|
||||
@import "./shadcn.css";
|
||||
@@ -350,6 +352,12 @@
|
||||
animation-duration: 0.01ms !important;
|
||||
transition-duration: 0.01ms !important;
|
||||
}
|
||||
|
||||
[data-slot="token-input-editor"][data-empty]::before {
|
||||
content: attr(data-placeholder);
|
||||
color: var(--muted-foreground);
|
||||
pointer-events: none;
|
||||
}
|
||||
}
|
||||
|
||||
/* Widens a control's tap area to 44px on a phone without changing how it looks
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import { serializePromptValue } from "../src/chat/prompt-tokens.ts";
|
||||
|
||||
test("serializePromptValue maps text and tokens into the chat wire format", () => {
|
||||
const cases = [
|
||||
[["Review the retry policy"], "Review the retry policy"],
|
||||
[
|
||||
[
|
||||
"Check ",
|
||||
{ id: "1", type: "task", value: "42", label: "#42" },
|
||||
" in ",
|
||||
{ id: "2", type: "workflow", value: "wf-1", label: "Event triage" },
|
||||
],
|
||||
"Check #42 in @Event triage",
|
||||
],
|
||||
[
|
||||
[{ id: "3", type: "command", value: "/help", label: "/help" }, " schedules"],
|
||||
"/help schedules",
|
||||
],
|
||||
] as const;
|
||||
|
||||
for (const [value, expected] of cases) {
|
||||
assert.equal(serializePromptValue([...value]), expected);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,53 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import { cronForRule, parseCronRule } from "../src/schedules/cron-rule.ts";
|
||||
|
||||
test("cronForRule emits canonical cron for guided recurrence patterns", () => {
|
||||
const cases = [
|
||||
[{ cadence: "daily", time: "09:05" }, "5 9 * * *"],
|
||||
[{ cadence: "weekly", time: "08:00", weekdays: [1, 2, 3, 4, 5] }, "0 8 * * 1-5"],
|
||||
[{ cadence: "weekly", time: "23:15", weekdays: [0, 6] }, "15 23 * * 0,6"],
|
||||
[{ cadence: "weekly", time: "08:00", weekdays: [6, 0, 2, 2] }, "0 8 * * 0,2,6"],
|
||||
[{ cadence: "weekly", time: "07:30", weekdays: [0, 1, 2, 3, 4, 5, 6] }, "30 7 * * *"],
|
||||
[{ cadence: "monthly", time: "09:30", day: 31 }, "30 9 31 * *"],
|
||||
] as const;
|
||||
|
||||
for (const [rule, expected] of cases) {
|
||||
assert.equal(cronForRule(rule), expected, JSON.stringify(rule));
|
||||
}
|
||||
});
|
||||
|
||||
test("cronForRule rejects invalid times and incomplete patterns", () => {
|
||||
const cases = [
|
||||
{ cadence: "daily", time: "9:05" },
|
||||
{ cadence: "daily", time: "24:00" },
|
||||
{ cadence: "daily", time: "09:60" },
|
||||
{ cadence: "weekly", time: "09:00", weekdays: [] },
|
||||
{ cadence: "weekly", time: "09:00", weekdays: [7] },
|
||||
{ cadence: "monthly", time: "09:00", day: 0 },
|
||||
{ cadence: "monthly", time: "09:00", day: 32 },
|
||||
] as const;
|
||||
|
||||
for (const rule of cases) {
|
||||
assert.equal(cronForRule(rule), null, JSON.stringify(rule));
|
||||
}
|
||||
});
|
||||
|
||||
test("parseCronRule round-trips guided expressions and leaves custom ones untouched", () => {
|
||||
const cases = [
|
||||
["5 9 * * *", { cadence: "daily", time: "09:05" }],
|
||||
["0 8 * * 1-5", { cadence: "weekly", time: "08:00", weekdays: [1, 2, 3, 4, 5] }],
|
||||
["15 23 * * 0,6", { cadence: "weekly", time: "23:15", weekdays: [0, 6] }],
|
||||
["0 9 * * 7", { cadence: "weekly", time: "09:00", weekdays: [0] }],
|
||||
["30 9 15 * *", { cadence: "monthly", time: "09:30", day: 15 }],
|
||||
["*/15 * * * *", null],
|
||||
["0 9 * 1 *", null],
|
||||
["0 9 1 * 1", null],
|
||||
["not-a-cron", null],
|
||||
] as const;
|
||||
|
||||
for (const [expression, expected] of cases) {
|
||||
assert.deepEqual(parseCronRule(expression), expected, expression);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
import { uiAgentWebMcpTools, type UiAgent } from "../src/lib/ui-agent.ts";
|
||||
|
||||
function fakeUiAgent(): {
|
||||
calls: Array<{ method: string; args: unknown[] }>;
|
||||
agent: UiAgent;
|
||||
} {
|
||||
const calls: Array<{ method: string; args: unknown[] }> = [];
|
||||
const agent = {
|
||||
snapshot: () => {
|
||||
calls.push({ method: "snapshot", args: [] });
|
||||
return [{ ref: "c1", component: "radio-group", label: "Repeats", value: "weekly", actions: ["setValue"] }];
|
||||
},
|
||||
query: async (input: { text?: string; within?: string; kind?: string }) => {
|
||||
calls.push({ method: "query", args: [input] });
|
||||
return [];
|
||||
},
|
||||
act: async (input: { steps: unknown[] }) => {
|
||||
calls.push({ method: "act", args: [input] });
|
||||
return { ok: true, appeared: [], values: {}, steps: [] };
|
||||
},
|
||||
subscribe: () => () => {},
|
||||
} as unknown as UiAgent;
|
||||
return { calls, agent };
|
||||
}
|
||||
|
||||
test("uiAgentWebMcpTools publishes snapshot, query, and act with expected annotations", async () => {
|
||||
const { calls, agent } = fakeUiAgent();
|
||||
const tools = uiAgentWebMcpTools(agent);
|
||||
assert.deepEqual(
|
||||
tools.map((tool) => tool.name),
|
||||
["ui_snapshot", "ui_query", "ui_act"],
|
||||
);
|
||||
|
||||
const snapshot = tools[0]!;
|
||||
const query = tools[1]!;
|
||||
const act = tools[2]!;
|
||||
|
||||
assert.equal(snapshot.annotations.readOnlyHint, true);
|
||||
assert.equal(query.annotations.readOnlyHint, true);
|
||||
assert.equal(act.annotations.readOnlyHint, false);
|
||||
assert.equal(act.annotations.consequentialHint, true);
|
||||
|
||||
await snapshot.execute({});
|
||||
await query.execute({ text: "Repeats", kind: "radio-group" });
|
||||
await act.execute({ steps: [{ ref: "Repeats", action: "setValue", args: ["daily"] }] });
|
||||
|
||||
assert.deepEqual(
|
||||
calls.map((c) => c.method),
|
||||
["snapshot", "query", "act"],
|
||||
);
|
||||
|
||||
await assert.rejects(
|
||||
async () => act.execute({ steps: "not-an-array" }),
|
||||
/steps must be an array/,
|
||||
);
|
||||
});
|
||||
Reference in new issue
Block a user