Files
veridian/app/components/Sidenav/NavAgent.vue
T

278 lines
12 KiB
Vue

<script setup lang="ts">
import { assert } from '~~/utils/assert';
import RowVirtualizerFixed from '~/components/RowVirtualizerFixed.vue';
import { useFloating, offset, flip, shift, autoUpdate } from '@floating-ui/vue';
const dropdownOpen = ref(false);
const dropdownTrigger = ref<HTMLElement | null>(null);
const dropdownContent = ref(null);
const activeMenuTopicId = ref<string | null>(null);
const route = useRoute();
const { getAgent } = useAgents();
const triplit = useTriplitClient();
const navRef = ref<HTMLElement | null>(null);
const agentId = computed(() => route.params.id as string);
const activeAgent = getAgent(agentId);
watch(agentId, () => {
if (navRef.value) {
navRef.value.scrollTo({ top: 0, behavior: 'instant' });
}
}, { immediate: true });
const topics = computed(() => {
return activeAgent.value?.topics || [];
})
const { floatingStyles, placement } = useFloating(dropdownTrigger, dropdownContent, {
placement: 'bottom-end',
whileElementsMounted: autoUpdate,
middleware: [offset(6), flip(), shift({ padding: 10 })],
transform: false,
});
const transformOrigin = computed(() =>
placement.value.startsWith('top')
? 'transform-origin-bottom-center'
: 'transform-origin-top-center'
);
const closeDropdown = () => {
dropdownOpen.value = false;
activeMenuTopicId.value = null;
dropdownTrigger.value = null;
};
// Computed to get the topic data for the currently open menu
const menuTopic = computed(() =>
topics.value.find(t => t.id === activeMenuTopicId.value)
);
const topicsOpen = ref(true);
let activeAutoRenames = reactive(new Map<string, string>());
const autoRenameTopic = async (topicId: string) => {
const { setPage } = useSettings();
const { autoRename, AutoRenameError } = useChat(agentId.value);
const firstMessage = await triplit.fetchOne(triplit.query('messages').Where('topicId', '=', topicId).Order('createdAt', 'ASC').Limit(1));
if (!firstMessage) return;
const res = await autoRename(topicId, firstMessage.content);
if (res.ok) {
activeAutoRenames.set(topicId, res.data);
return;
}
switch (res.error) {
case AutoRenameError.NoModelSelected:
case AutoRenameError.ModelDisabled:
case AutoRenameError.AutoRenameDisabled: {
setPage('systemAssistants');
} break;
case AutoRenameError.NoModelFound:
case AutoRenameError.DatabaseOperationFailed:
case AutoRenameError.FailedToGenerate:
case AutoRenameError.FailedToDecryptProviderApiKey: {
console.error('Failed to auto-rename:', res.error);
await triplit.update('topics', topicId, {
renaming: false,
});
assert('flush' in triplit);
await triplit.flush();
} break;
}
}
const cancelAutoRename = async (topicId: string) => {
await triplit.update('topics', topicId, {
renaming: false,
});
const renameId = activeAutoRenames.get(topicId);
if (!renameId) return;
await $fetch(`/api/auto-rename/cancel`, {
body: {
renameId,
},
method: 'POST',
});
activeAutoRenames.delete(topicId);
}
const renameTopicId = ref<string | null>(null);
const newTopicName = ref('');
const startRename = (topicId: string, currentName: string) => {
renameTopicId.value = topicId;
newTopicName.value = currentName;
nextTick(() => {
const input = document.getElementById('topic-rename-input') as HTMLInputElement | null;
if (input) {
input.focus();
}
})
};
const saveRename = async () => {
if (renameTopicId.value && newTopicName.value.trim()) {
await triplit.update('topics', renameTopicId.value, {
name: newTopicName.value.trim()
});
}
cancelRename();
};
const cancelRename = () => {
renameTopicId.value = null;
newTopicName.value = '';
};
const deleteTopic = async (topicId: string) => {
if (route.params.topicId === topicId) {
if (agentId.value) {
await navigateTo(`/agent/${agentId.value}`);
} else {
await navigateTo('/');
}
}
await triplit.delete('topics', topicId);
// TODO: deeply delete all messages, generations, and message_parts in the topic
};
const handleNavClick = (e: MouseEvent) => {
const trigger = (e.target as HTMLElement).closest('[data-action]') as HTMLElement | null;
if (!trigger) return;
const topicId = trigger.dataset.topicId || (trigger.closest('[data-topic-id]') as HTMLElement | null)?.dataset.topicId;
if (!topicId) return;
const action = trigger.dataset.action;
switch (action) {
case 'navigate':
if (e.metaKey || e.ctrlKey || e.shiftKey) return;
e.preventDefault();
return navigateTo(`/agent/${agentId.value}/topic/${topicId}`);
case 'toggle-dropdown':
e.preventDefault();
e.stopPropagation();
if (activeMenuTopicId.value === topicId && dropdownOpen.value) {
closeDropdown();
return;
}
activeMenuTopicId.value = topicId;
dropdownTrigger.value = trigger;
dropdownOpen.value = true;
break;
}
}
onMounted(() => {
// simply preload the topic page
preloadRouteComponents(`/agent/${agentId.value}/topic/42`);
})
</script>
<template>
<nav ref="navRef"
class="max-h-full h-full overflow-auto [scrollbar-color:#888_transparent] [scrollbar-width:thin] [scrollbar-gutter:stable]">
<!-- Agent Info Link -->
<div class="mt-2 flex flex-col">
<SidenavItem :to="`/agent/${agentId}/profile`" name="Agent Info" icon="i-mynaui-info-square"
:active="route.path.endsWith('/profile')" />
<!-- Topics Section -->
<button @click="topicsOpen = !topicsOpen"
class="flex items-center justify-between gap-2 px-2 py-2 rounded-lg bg-transparent hover:bg-[var(--color-hover)] focus-visible:bg-[var(--color-hover)] transition-colors w-full text-left">
<span class="text-sm font-medium">Topics</span>
<span
class="i-mynaui-chevron-down inline-block text-4 transition-transform duration-200 ease-[cubic-bezier(0.5,_1,_0.89,_1)]"
:class="topicsOpen ? '' : '-rotate-90'"></span>
</button>
<Collapsible :is-open="topicsOpen">
<div @click="handleNavClick" class="mt-1 flex flex-col transform-origin-center-top">
<RowVirtualizerFixed :scroll-element="navRef" key-field="id" :prerender="50" :items="topics"
:item-size="40" :overscan="20">
<template v-slot="{ item: topic }">
<a :key="topic.id" data-action="navigate" :data-topic-id="topic.id"
:href="`/agent/${agentId}/topic/${topic.id}`" :aria-label="topic.name"
class="mt-1 group px-2 decoration-none flex justify-between items-center shrink-0 rounded-lg transition-colors cursor-pointer h-9 text-[var(--text-secondary)] hover:bg-[var(--color-hover)] focus-visible:bg-[var(--color-hover)] focus:text-[var(--text-primary)]"
:class="{ 'bg-[var(--color-hover)]': route.params.topicId === topic.id }">
<input v-if="renameTopicId === topic.id && !topic.renaming" id="topic-rename-input"
v-model="newTopicName" @keydown.enter="saveRename" @keydown.escape="cancelRename"
@blur="saveRename"
class="flex-1 bg-transparent border-none outline-none text-sm font-medium text-[var(--text-primary)] px-0 min-w-0" />
<div v-else-if="topic.renaming" class="flex w-full">
<span class="i-svg-spinners-3-dots-fade text-6"></span>
</div>
<span v-else
class="text-sm font-medium overflow-hidden text-ellipsis whitespace-nowrap">
{{ topic.name }}
</span>
<div data-action="toggle-dropdown"
class="text-[var(--text-secondary)] shrink-0 opacity-0 group-hover:opacity-100 p-1 flex items-center justify-center rounded-md hover:bg-[var(--color-hover)] focus-visible:bg-[var(--color-hover)] transition-opacity duration-200 ease-[cubic-bezier(0.5,_1,_0.89,_1)]">
<span class="pointer-events-none h-4.5 w-4.5 i-tabler-dots"></span>
</div>
</a>
</template>
</RowVirtualizerFixed>
</div>
</Collapsible>
</div>
<Teleport to="body">
<Transition
enter-active-class="transition-[opacity,transform] duration-150 ease-[cubic-bezier(0.5,_1,_0.89,_1)]"
enter-from-class="opacity-0 scale-95 translate-y-1" enter-to-class="opacity-100 scale-100 translate-y-0"
leave-active-class="transition-[opacity,transform] duration-100 ease-[cubic-bezier(0.5,_1,_0.89,_1)]"
leave-from-class="opacity-100 scale-100 translate-y-0"
leave-to-class="opacity-0 scale-95 translate-y-1">
<div v-if="dropdownOpen" ref="dropdownContent" :style="floatingStyles" class="fixed z-15"
:class="transformOrigin">
<div v-click-outside="closeDropdown"
class="bg-[var(--bg-surface)] border border-[var(--color-border)] rounded-xl p-1.5 shadow-xl flex flex-col gap-1 min-w-40">
<!-- Dynamic content based on menuTopic -->
<template v-if="menuTopic">
<button v-if="menuTopic.renaming" @click="cancelAutoRename(menuTopic.id); closeDropdown()"
class="text-left px-3 py-1.5 text-sm rounded-lg hover:bg-[var(--color-hover)] transition-colors disabled:opacity-50">
Cancel Auto Rename
</button>
<button v-else @click="autoRenameTopic(menuTopic.id); closeDropdown()"
class="text-left px-3 py-1.5 text-sm rounded-lg hover:bg-[var(--color-hover)] transition-colors disabled:opacity-50">
Auto Rename
</button>
<button :disabled="menuTopic.renaming ?? false"
@click="startRename(menuTopic.id, menuTopic.name); closeDropdown()"
class="text-left px-3 py-1.5 text-sm rounded-lg hover:bg-[var(--color-hover)] transition-colors disabled:opacity-50">
Rename
</button>
<div class="h-px bg-[var(--color-border)] my-1" />
<button @click="deleteTopic(menuTopic.id); closeDropdown()"
class="text-left px-3 py-1.5 text-sm rounded-lg hover:bg-[var(--color-hover)] transition-colors disabled:opacity-50 text-red-500">
Delete
</button>
</template>
</div>
</div>
</Transition>
</Teleport>
</nav>
</template>