Add CalDAV calendar integration, LLM-suggested tags, and settings refinements
- CalDAV integration: per-user calendar config, create/list/search events via caldav library, LLM tools for calendar operations from chat - LLM-suggested tags: new tag_suggestions service prompts LLM with existing tags and note content to suggest 3-5 relevant tags; exposed via API endpoints (suggest-tags, append-tag); integrated into editor views (suggest button + clickable pills) and chat tool calls (pills in ToolCallCard with one-click apply) - Settings/model UI refinements, generation task improvements Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,17 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, watch, nextTick } from "vue";
|
||||
import { ref, nextTick } from "vue";
|
||||
import { apiGet } from "@/api/client";
|
||||
import { useChatStore } from "@/stores/chat";
|
||||
import ModelSelector from "@/components/ModelSelector.vue";
|
||||
import type { Note } from "@/types/note";
|
||||
|
||||
const emit = defineEmits<{
|
||||
submit: [payload: { content: string; model: string; contextNoteId?: number }];
|
||||
submit: [payload: { content: string; contextNoteId?: number }];
|
||||
}>();
|
||||
|
||||
const store = useChatStore();
|
||||
|
||||
const selectedModel = ref(store.defaultModel || "");
|
||||
const messageInput = ref("");
|
||||
const inputEl = ref<HTMLTextAreaElement | null>(null);
|
||||
|
||||
@@ -23,20 +21,11 @@ const noteSearchResults = ref<{ id: number; title: string }[]>([]);
|
||||
const noteSearchLoading = ref(false);
|
||||
let noteSearchTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
// Sync default model when store updates
|
||||
watch(
|
||||
() => store.defaultModel,
|
||||
(v) => {
|
||||
if (!selectedModel.value && v) selectedModel.value = v;
|
||||
}
|
||||
);
|
||||
|
||||
function onSubmit() {
|
||||
const content = messageInput.value.trim();
|
||||
if (!content) return;
|
||||
emit("submit", {
|
||||
content,
|
||||
model: selectedModel.value,
|
||||
contextNoteId: attachedNote.value?.id,
|
||||
});
|
||||
messageInput.value = "";
|
||||
@@ -127,8 +116,6 @@ function removeAttachedNote() {
|
||||
</div>
|
||||
|
||||
<div class="chat-input-bar">
|
||||
<ModelSelector v-model="selectedModel" :disabled="!store.chatReady" />
|
||||
|
||||
<div class="note-picker-wrapper">
|
||||
<button
|
||||
class="btn-attach"
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, computed } from "vue";
|
||||
import { useChatStore } from "@/stores/chat";
|
||||
|
||||
defineProps<{
|
||||
modelValue: string;
|
||||
disabled?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
"update:modelValue": [value: string];
|
||||
}>();
|
||||
|
||||
const store = useChatStore();
|
||||
|
||||
function normalize(name: string): string {
|
||||
return name.replace(/:latest$/, "");
|
||||
}
|
||||
|
||||
const hotNames = computed(() => {
|
||||
return new Set(store.runningModels.map((m) => normalize(m.name)));
|
||||
});
|
||||
|
||||
function isHot(modelName: string): boolean {
|
||||
return hotNames.value.has(normalize(modelName));
|
||||
}
|
||||
|
||||
function onChange(e: Event) {
|
||||
const val = (e.target as HTMLSelectElement).value;
|
||||
emit("update:modelValue", val);
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
if (!store.models.length) store.fetchModels();
|
||||
store.fetchRunningModels();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<select
|
||||
class="model-selector"
|
||||
:value="modelValue"
|
||||
:disabled="disabled"
|
||||
@change="onChange"
|
||||
>
|
||||
<option v-if="!modelValue" value="" disabled>Select model</option>
|
||||
<option
|
||||
v-for="m in store.models"
|
||||
:key="m.name"
|
||||
:value="m.name"
|
||||
>
|
||||
{{ isHot(m.name) ? "🟢 " : "🔴 " }}{{ m.name }}
|
||||
</option>
|
||||
</select>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.model-selector {
|
||||
padding: 0.3rem 0.5rem;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--color-bg-secondary);
|
||||
color: var(--color-text);
|
||||
font-size: 0.85rem;
|
||||
font-family: inherit;
|
||||
cursor: pointer;
|
||||
max-width: 220px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.model-selector:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: default;
|
||||
}
|
||||
.model-selector:focus {
|
||||
outline: 2px solid var(--color-primary);
|
||||
outline-offset: 1px;
|
||||
}
|
||||
</style>
|
||||
@@ -1,11 +1,15 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from "vue";
|
||||
import { computed, ref } from "vue";
|
||||
import { apiPost } from "@/api/client";
|
||||
import type { ToolCallRecord } from "@/types/chat";
|
||||
|
||||
const props = defineProps<{
|
||||
toolCall: ToolCallRecord;
|
||||
}>();
|
||||
|
||||
const appliedTags = ref<Set<string>>(new Set());
|
||||
const applyingTag = ref<string | null>(null);
|
||||
|
||||
const label = computed(() => {
|
||||
if (!props.toolCall.result.success) return "Error";
|
||||
switch (props.toolCall.result.type) {
|
||||
@@ -15,6 +19,10 @@ const label = computed(() => {
|
||||
return "Created note";
|
||||
case "search":
|
||||
return "Searched notes";
|
||||
case "event":
|
||||
return "Created event";
|
||||
case "events":
|
||||
return "Found events";
|
||||
default:
|
||||
return "Tool call";
|
||||
}
|
||||
@@ -33,12 +41,70 @@ const linkTo = computed(() => {
|
||||
return `/notes/${data.id}`;
|
||||
});
|
||||
|
||||
const noteId = computed(() => {
|
||||
const data = props.toolCall.result.data;
|
||||
if (!data || typeof data.id !== "number") return null;
|
||||
return data.id;
|
||||
});
|
||||
|
||||
const suggestedTags = computed(() => {
|
||||
return props.toolCall.result.suggested_tags ?? [];
|
||||
});
|
||||
|
||||
const eventData = computed(() => {
|
||||
const data = props.toolCall.result.data;
|
||||
if (!data || props.toolCall.result.type !== "event") return null;
|
||||
return data as { title: string; start: string; end: string };
|
||||
});
|
||||
|
||||
const eventList = computed(() => {
|
||||
const data = props.toolCall.result.data;
|
||||
if (!data || props.toolCall.result.type !== "events") return null;
|
||||
const events = data.events as Array<{ title: string; start: string; end: string; location?: string }> | undefined;
|
||||
return events ?? [];
|
||||
});
|
||||
|
||||
const eventCount = computed(() => {
|
||||
const data = props.toolCall.result.data;
|
||||
if (!data || props.toolCall.result.type !== "events") return 0;
|
||||
return (data.count as number) ?? 0;
|
||||
});
|
||||
|
||||
function formatEventTime(iso: string): string {
|
||||
if (!iso) return "";
|
||||
try {
|
||||
const d = new Date(iso);
|
||||
return d.toLocaleString(undefined, {
|
||||
weekday: "short",
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "numeric",
|
||||
minute: "2-digit",
|
||||
});
|
||||
} catch {
|
||||
return iso;
|
||||
}
|
||||
}
|
||||
|
||||
const searchResults = computed(() => {
|
||||
const data = props.toolCall.result.data;
|
||||
if (!data || props.toolCall.result.type !== "search") return null;
|
||||
const results = data.results as Array<{ id: number; title: string; type: string }> | undefined;
|
||||
return results && results.length > 0 ? results : null;
|
||||
});
|
||||
|
||||
async function applyTag(tag: string) {
|
||||
if (!noteId.value || appliedTags.value.has(tag) || applyingTag.value) return;
|
||||
applyingTag.value = tag;
|
||||
try {
|
||||
await apiPost(`/api/notes/${noteId.value}/append-tag`, { tag });
|
||||
appliedTags.value.add(tag);
|
||||
} catch {
|
||||
// silently fail
|
||||
} finally {
|
||||
applyingTag.value = null;
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -60,9 +126,40 @@ const searchResults = computed(() => {
|
||||
</router-link>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="eventData">
|
||||
<span class="tool-event-title">{{ eventData.title }}</span>
|
||||
<span class="tool-event-time">{{ formatEventTime(eventData.start) }}</span>
|
||||
</template>
|
||||
<template v-else-if="eventList !== null">
|
||||
<span class="tool-search-info">{{ eventCount }} found</span>
|
||||
<div v-if="eventList.length > 0" class="tool-event-list">
|
||||
<div v-for="(ev, i) in eventList.slice(0, 5)" :key="i" class="tool-event-item">
|
||||
<span class="tool-event-item-title">{{ ev.title }}</span>
|
||||
<span class="tool-event-item-time">{{ formatEventTime(ev.start) }}</span>
|
||||
</div>
|
||||
<div v-if="eventList.length > 5" class="tool-event-more">
|
||||
+{{ eventList.length - 5 }} more
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
<template v-else-if="linkTo">
|
||||
<router-link :to="linkTo" class="tool-link">{{ title }}</router-link>
|
||||
</template>
|
||||
|
||||
<!-- Suggested tags pills -->
|
||||
<div v-if="suggestedTags.length > 0" class="tag-suggestions">
|
||||
<span class="tag-suggestions-label">Suggested tags:</span>
|
||||
<button
|
||||
v-for="tag in suggestedTags"
|
||||
:key="tag"
|
||||
:class="['tag-pill', { applied: appliedTags.has(tag) }]"
|
||||
:disabled="appliedTags.has(tag) || applyingTag === tag"
|
||||
@click="applyTag(tag)"
|
||||
>
|
||||
#{{ tag }}
|
||||
<span v-if="appliedTags.has(tag)" class="tag-check">✓</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -121,4 +218,85 @@ const searchResults = computed(() => {
|
||||
color: var(--color-text-muted);
|
||||
margin-right: 0.1rem;
|
||||
}
|
||||
.tool-event-title {
|
||||
font-weight: 600;
|
||||
color: var(--color-text);
|
||||
}
|
||||
.tool-event-time {
|
||||
color: var(--color-text-muted);
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.tool-event-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.2rem;
|
||||
width: 100%;
|
||||
}
|
||||
.tool-event-item {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: baseline;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
.tool-event-item-title {
|
||||
color: var(--color-text);
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.tool-event-item-time {
|
||||
color: var(--color-text-muted);
|
||||
font-size: 0.75rem;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.tool-event-more {
|
||||
color: var(--color-text-muted);
|
||||
font-size: 0.75rem;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
/* Tag suggestions */
|
||||
.tag-suggestions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
width: 100%;
|
||||
margin-top: 0.25rem;
|
||||
padding-top: 0.3rem;
|
||||
border-top: 1px solid var(--color-border);
|
||||
}
|
||||
.tag-suggestions-label {
|
||||
font-size: 0.7rem;
|
||||
color: var(--color-text-muted);
|
||||
font-weight: 500;
|
||||
}
|
||||
.tag-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.2rem;
|
||||
padding: 0.15rem 0.5rem;
|
||||
border: 1px solid var(--color-primary);
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
color: var(--color-primary);
|
||||
font-size: 0.75rem;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
.tag-pill:hover:not(:disabled) {
|
||||
background: var(--color-primary);
|
||||
color: #fff;
|
||||
}
|
||||
.tag-pill.applied {
|
||||
background: var(--color-success, #2ecc71);
|
||||
border-color: var(--color-success, #2ecc71);
|
||||
color: #fff;
|
||||
cursor: default;
|
||||
}
|
||||
.tag-pill:disabled:not(.applied) {
|
||||
opacity: 0.6;
|
||||
cursor: wait;
|
||||
}
|
||||
.tag-check {
|
||||
font-size: 0.65rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -13,9 +13,7 @@ import type {
|
||||
ConversationDetail,
|
||||
ContextMeta,
|
||||
Message,
|
||||
OllamaModel,
|
||||
OllamaStatus,
|
||||
RunningModel,
|
||||
SendMessageResponse,
|
||||
ToolCallRecord,
|
||||
} from "@/types/chat";
|
||||
@@ -29,8 +27,6 @@ export const useChatStore = defineStore("chat", () => {
|
||||
const streamingContent = ref("");
|
||||
const streamingToolCalls = ref<ToolCallRecord[]>([]);
|
||||
const lastContextMeta = ref<ContextMeta | null>(null);
|
||||
const models = ref<OllamaModel[]>([]);
|
||||
const runningModels = ref<RunningModel[]>([]);
|
||||
const ollamaStatus = ref<"checking" | "available" | "unavailable">("checking");
|
||||
const modelStatus = ref<"checking" | "ready" | "not_found">("checking");
|
||||
const defaultModel = ref("");
|
||||
@@ -56,14 +52,10 @@ export const useChatStore = defineStore("chat", () => {
|
||||
}
|
||||
}
|
||||
|
||||
async function createConversation(
|
||||
title = "",
|
||||
model = ""
|
||||
): Promise<Conversation> {
|
||||
async function createConversation(title = ""): Promise<Conversation> {
|
||||
try {
|
||||
const conv = await apiPost<Conversation>("/api/chat/conversations", {
|
||||
title,
|
||||
model,
|
||||
});
|
||||
conversations.value.unshift(conv);
|
||||
return conv;
|
||||
@@ -319,24 +311,6 @@ export const useChatStore = defineStore("chat", () => {
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchModels() {
|
||||
try {
|
||||
const data = await apiGet<{ models: OllamaModel[] }>("/api/chat/models");
|
||||
models.value = data.models;
|
||||
} catch {
|
||||
models.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchRunningModels() {
|
||||
try {
|
||||
const data = await apiGet<{ models: RunningModel[] }>("/api/chat/ps");
|
||||
runningModels.value = data.models;
|
||||
} catch {
|
||||
runningModels.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
async function warmModel(model: string) {
|
||||
try {
|
||||
await apiPost("/api/chat/warm", { model });
|
||||
@@ -345,25 +319,6 @@ export const useChatStore = defineStore("chat", () => {
|
||||
}
|
||||
}
|
||||
|
||||
async function updateConversationModel(id: number, model: string) {
|
||||
try {
|
||||
const updated = await apiPatch<Conversation>(
|
||||
`/api/chat/conversations/${id}`,
|
||||
{ model }
|
||||
);
|
||||
const idx = conversations.value.findIndex((c) => c.id === id);
|
||||
if (idx !== -1) {
|
||||
conversations.value[idx] = { ...conversations.value[idx], ...updated };
|
||||
}
|
||||
if (currentConversation.value?.id === id) {
|
||||
currentConversation.value.model = updated.model;
|
||||
}
|
||||
} catch (e) {
|
||||
useToastStore().show("Failed to update model", "error");
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
conversations,
|
||||
currentConversation,
|
||||
@@ -373,8 +328,6 @@ export const useChatStore = defineStore("chat", () => {
|
||||
streamingContent,
|
||||
streamingToolCalls,
|
||||
lastContextMeta,
|
||||
models,
|
||||
runningModels,
|
||||
ollamaStatus,
|
||||
modelStatus,
|
||||
defaultModel,
|
||||
@@ -388,10 +341,7 @@ export const useChatStore = defineStore("chat", () => {
|
||||
cancelGeneration,
|
||||
saveMessageAsNote,
|
||||
summarizeAsNote,
|
||||
fetchModels,
|
||||
fetchRunningModels,
|
||||
warmModel,
|
||||
updateConversationModel,
|
||||
fetchStatus,
|
||||
startStatusPolling,
|
||||
stopStatusPolling,
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
import { ref, computed } from "vue";
|
||||
import { defineStore } from "pinia";
|
||||
import { apiGet, apiPut, apiPost, apiStreamPost } from "@/api/client";
|
||||
import { apiGet, apiPut } from "@/api/client";
|
||||
import { useToastStore } from "@/stores/toast";
|
||||
import type { AppSettings } from "@/types/settings";
|
||||
|
||||
export const useSettingsStore = defineStore("settings", () => {
|
||||
const settings = ref<AppSettings>({});
|
||||
const loading = ref(false);
|
||||
const installedModels = ref<string[]>([]);
|
||||
|
||||
const assistantName = computed(
|
||||
() => settings.value.assistant_name || "Fable"
|
||||
@@ -40,44 +39,12 @@ export const useSettingsStore = defineStore("settings", () => {
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchInstalledModels() {
|
||||
try {
|
||||
const data = await apiGet<{ models: { name: string }[] }>("/api/chat/models");
|
||||
installedModels.value = data.models.map((m) => m.name);
|
||||
} catch {
|
||||
installedModels.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
async function pullModel(
|
||||
model: string,
|
||||
onProgress?: (data: Record<string, unknown>) => void,
|
||||
) {
|
||||
await apiStreamPost("/api/chat/models/pull", { model }, (data) => {
|
||||
if (onProgress) onProgress(data);
|
||||
});
|
||||
}
|
||||
|
||||
async function deleteModel(model: string) {
|
||||
try {
|
||||
await apiPost("/api/chat/models/delete", { model });
|
||||
await fetchInstalledModels();
|
||||
} catch (e) {
|
||||
useToastStore().show("Failed to delete model", "error");
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
settings,
|
||||
loading,
|
||||
installedModels,
|
||||
assistantName,
|
||||
defaultModel,
|
||||
fetchSettings,
|
||||
updateSettings,
|
||||
fetchInstalledModels,
|
||||
pullModel,
|
||||
deleteModel,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
export interface ToolCallRecord {
|
||||
function: string;
|
||||
arguments: Record<string, unknown>;
|
||||
result: { success: boolean; type?: string; data?: Record<string, unknown>; error?: string };
|
||||
result: { success: boolean; type?: string; data?: Record<string, unknown>; error?: string; suggested_tags?: string[] };
|
||||
status: "success" | "error";
|
||||
}
|
||||
|
||||
@@ -34,18 +34,6 @@ export interface ConversationDetail extends Conversation {
|
||||
messages: Message[];
|
||||
}
|
||||
|
||||
export interface OllamaModel {
|
||||
name: string;
|
||||
size: number;
|
||||
}
|
||||
|
||||
export interface RunningModel {
|
||||
name: string;
|
||||
size: number;
|
||||
size_vram: number;
|
||||
expires_at: string;
|
||||
}
|
||||
|
||||
export interface ContextMeta {
|
||||
context_note_id: number | null;
|
||||
context_note_title: string | null;
|
||||
|
||||
@@ -3,11 +3,3 @@ export interface AppSettings {
|
||||
default_model?: string;
|
||||
[key: string]: string | undefined;
|
||||
}
|
||||
|
||||
export interface ModelInfo {
|
||||
name: string;
|
||||
description: string;
|
||||
size: string;
|
||||
bestFor: string;
|
||||
category: string;
|
||||
}
|
||||
|
||||
@@ -6,7 +6,6 @@ import { useSettingsStore } from "@/stores/settings";
|
||||
import { apiGet } from "@/api/client";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import ChatMessage from "@/components/ChatMessage.vue";
|
||||
import ModelSelector from "@/components/ModelSelector.vue";
|
||||
import ToolCallCard from "@/components/ToolCallCard.vue";
|
||||
import type { Note } from "@/types/note";
|
||||
|
||||
@@ -30,9 +29,6 @@ const noteSearchResults = ref<{ id: number; title: string }[]>([]);
|
||||
const noteSearchLoading = ref(false);
|
||||
let noteSearchTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
// Model selection
|
||||
const selectedModel = ref("");
|
||||
|
||||
// Exclude tracking (session-scoped per conversation)
|
||||
const excludedNoteIds = ref<Set<number>>(new Set());
|
||||
|
||||
@@ -76,12 +72,6 @@ onMounted(async () => {
|
||||
await store.fetchConversations();
|
||||
if (convId.value) {
|
||||
await store.fetchConversation(convId.value);
|
||||
if (store.currentConversation?.model) {
|
||||
selectedModel.value = store.currentConversation.model;
|
||||
}
|
||||
}
|
||||
if (!selectedModel.value) {
|
||||
selectedModel.value = store.defaultModel;
|
||||
}
|
||||
nextTick(() => inputEl.value?.focus());
|
||||
});
|
||||
@@ -112,26 +102,6 @@ watch(convId, async (newId) => {
|
||||
nextTick(() => inputEl.value?.focus());
|
||||
});
|
||||
|
||||
// Sync selectedModel from loaded conversation
|
||||
watch(
|
||||
() => store.currentConversation?.model,
|
||||
(model) => {
|
||||
if (model) selectedModel.value = model;
|
||||
}
|
||||
);
|
||||
|
||||
// Persist model changes to backend
|
||||
watch(selectedModel, (newModel, oldModel) => {
|
||||
if (
|
||||
newModel &&
|
||||
oldModel &&
|
||||
newModel !== oldModel &&
|
||||
store.currentConversation
|
||||
) {
|
||||
store.updateConversationModel(store.currentConversation.id, newModel);
|
||||
}
|
||||
});
|
||||
|
||||
watch(
|
||||
() => store.streamingContent,
|
||||
() => scrollToBottom()
|
||||
@@ -155,7 +125,7 @@ async function selectConversation(id: number) {
|
||||
}
|
||||
|
||||
async function newConversation() {
|
||||
const conv = await store.createConversation("", selectedModel.value);
|
||||
const conv = await store.createConversation();
|
||||
await store.fetchConversation(conv.id);
|
||||
router.push(`/chat/${conv.id}`);
|
||||
}
|
||||
@@ -344,10 +314,6 @@ function excludeAutoNote(noteId: number) {
|
||||
<line x1="3" y1="18" x2="21" y2="18"/>
|
||||
</svg>
|
||||
</button>
|
||||
<ModelSelector
|
||||
v-model="selectedModel"
|
||||
:disabled="store.streaming"
|
||||
/>
|
||||
<h2>{{ store.currentConversation.title || "New Chat" }}</h2>
|
||||
<button
|
||||
v-if="store.currentConversation.messages.length"
|
||||
|
||||
@@ -178,10 +178,9 @@ chatStore.fetchStatus().then(() => {
|
||||
|
||||
async function onChatSubmit(payload: {
|
||||
content: string;
|
||||
model: string;
|
||||
contextNoteId?: number;
|
||||
}) {
|
||||
const conv = await chatStore.createConversation("", payload.model);
|
||||
const conv = await chatStore.createConversation();
|
||||
await chatStore.fetchConversation(conv.id);
|
||||
router.push(`/chat/${conv.id}`);
|
||||
await chatStore.sendMessage(payload.content, payload.contextNoteId);
|
||||
|
||||
@@ -5,6 +5,7 @@ import { useNotesStore } from "@/stores/notes";
|
||||
import { useToastStore } from "@/stores/toast";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { useAssist } from "@/composables/useAssist";
|
||||
import { apiPost } from "@/api/client";
|
||||
import type { Editor } from "@tiptap/vue-3";
|
||||
import MarkdownToolbar from "@/components/MarkdownToolbar.vue";
|
||||
import TiptapEditor from "@/components/TiptapEditor.vue";
|
||||
@@ -55,6 +56,41 @@ function truncateTarget(text: string, max = 60): string {
|
||||
return first.length > max ? first.slice(0, max) + "..." : first;
|
||||
}
|
||||
|
||||
// Tag suggestions
|
||||
const suggestedTags = ref<string[]>([]);
|
||||
const appliedTags = ref<Set<string>>(new Set());
|
||||
const suggestingTags = ref(false);
|
||||
|
||||
async function fetchTagSuggestions() {
|
||||
if (suggestingTags.value) return;
|
||||
suggestingTags.value = true;
|
||||
suggestedTags.value = [];
|
||||
appliedTags.value = new Set();
|
||||
try {
|
||||
const res = await apiPost<{ suggested_tags: string[] }>("/api/notes/suggest-tags", {
|
||||
title: title.value,
|
||||
body: body.value,
|
||||
});
|
||||
suggestedTags.value = res.suggested_tags;
|
||||
} catch {
|
||||
toast.show("Failed to get tag suggestions", "error");
|
||||
} finally {
|
||||
suggestingTags.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function applyTagSuggestion(tag: string) {
|
||||
if (appliedTags.value.has(tag)) return;
|
||||
body.value = body.value.trimEnd() + `\n#${tag}`;
|
||||
appliedTags.value.add(tag);
|
||||
markDirty();
|
||||
}
|
||||
|
||||
function dismissTagSuggestions() {
|
||||
suggestedTags.value = [];
|
||||
appliedTags.value = new Set();
|
||||
}
|
||||
|
||||
// Track saved state for dirty detection
|
||||
let savedTitle = "";
|
||||
let savedBody = "";
|
||||
@@ -178,6 +214,25 @@ onUnmounted(() => window.removeEventListener("beforeunload", onBeforeUnload));
|
||||
@input="markDirty"
|
||||
/>
|
||||
|
||||
<div class="tag-suggest-row">
|
||||
<button class="btn-suggest-tags" @click="fetchTagSuggestions" :disabled="suggestingTags">
|
||||
{{ suggestingTags ? "Suggesting..." : "Suggest tags" }}
|
||||
</button>
|
||||
<template v-if="suggestedTags.length > 0">
|
||||
<button
|
||||
v-for="tag in suggestedTags"
|
||||
:key="tag"
|
||||
:class="['tag-pill', { applied: appliedTags.has(tag) }]"
|
||||
:disabled="appliedTags.has(tag)"
|
||||
@click="applyTagSuggestion(tag)"
|
||||
>
|
||||
#{{ tag }}
|
||||
<span v-if="appliedTags.has(tag)" class="tag-check">✓</span>
|
||||
</button>
|
||||
<button class="btn-dismiss-tags" @click="dismissTagSuggestions">×</button>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="editor-tabs">
|
||||
<button
|
||||
:class="['tab', { active: !showPreview }]"
|
||||
@@ -385,6 +440,69 @@ onUnmounted(() => window.removeEventListener("beforeunload", onBeforeUnload));
|
||||
background: var(--color-bg-card);
|
||||
}
|
||||
|
||||
/* ── Tag suggestions ── */
|
||||
.tag-suggest-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
.btn-suggest-tags {
|
||||
padding: 0.3rem 0.7rem;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--color-bg-card);
|
||||
color: var(--color-text-secondary);
|
||||
cursor: pointer;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.btn-suggest-tags:hover:not(:disabled) {
|
||||
border-color: var(--color-primary);
|
||||
color: var(--color-primary);
|
||||
}
|
||||
.btn-suggest-tags:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: wait;
|
||||
}
|
||||
.tag-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.2rem;
|
||||
padding: 0.2rem 0.55rem;
|
||||
border: 1px solid var(--color-primary);
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
color: var(--color-primary);
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
.tag-pill:hover:not(:disabled) {
|
||||
background: var(--color-primary);
|
||||
color: #fff;
|
||||
}
|
||||
.tag-pill.applied {
|
||||
background: var(--color-success, #2ecc71);
|
||||
border-color: var(--color-success, #2ecc71);
|
||||
color: #fff;
|
||||
cursor: default;
|
||||
}
|
||||
.tag-check {
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
.btn-dismiss-tags {
|
||||
padding: 0.1rem 0.4rem;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--color-text-muted);
|
||||
cursor: pointer;
|
||||
font-size: 1rem;
|
||||
line-height: 1;
|
||||
}
|
||||
.btn-dismiss-tags:hover {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
/* ── Assist panel ── */
|
||||
.assist-panel {
|
||||
flex: 0 0 33.33%;
|
||||
|
||||
+145
-572
@@ -1,10 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, computed, onMounted } from "vue";
|
||||
import { ref, onMounted } from "vue";
|
||||
import { useSettingsStore } from "@/stores/settings";
|
||||
import { useAuthStore } from "@/stores/auth";
|
||||
import { useToastStore } from "@/stores/toast";
|
||||
import { apiGet, apiPost, apiPut } from "@/api/client";
|
||||
import type { ModelInfo } from "@/types/settings";
|
||||
|
||||
const store = useSettingsStore();
|
||||
const authStore = useAuthStore();
|
||||
@@ -16,9 +15,6 @@ const confirmNewPassword = ref("");
|
||||
const changingPassword = ref(false);
|
||||
const saving = ref(false);
|
||||
const saved = ref(false);
|
||||
const pullProgress = ref<{ model: string; percent: number } | null>(null);
|
||||
const deleting = ref<string | null>(null);
|
||||
const confirmDelete = ref<string | null>(null);
|
||||
const exporting = ref(false);
|
||||
const restoring = ref(false);
|
||||
const restoreFileInput = ref<HTMLInputElement | null>(null);
|
||||
@@ -29,6 +25,18 @@ const notifySecurityAlerts = ref(true);
|
||||
const savingNotifications = ref(false);
|
||||
const notificationsSaved = ref(false);
|
||||
|
||||
// CalDAV settings (per-user)
|
||||
const caldav = ref({
|
||||
caldav_url: "",
|
||||
caldav_username: "",
|
||||
caldav_password: "",
|
||||
caldav_calendar_name: "",
|
||||
});
|
||||
const savingCaldav = ref(false);
|
||||
const caldavSaved = ref(false);
|
||||
const testingCaldav = ref(false);
|
||||
const caldavTestResult = ref<{ success: boolean; message?: string; error?: string; calendars?: string[] } | null>(null);
|
||||
|
||||
// SMTP settings (admin only)
|
||||
const smtp = ref({
|
||||
smtp_host: "",
|
||||
@@ -44,187 +52,14 @@ const smtpSaved = ref(false);
|
||||
const testRecipient = ref("");
|
||||
const sendingTest = ref(false);
|
||||
|
||||
const MODEL_CATALOG: ModelInfo[] = [
|
||||
// — General Purpose —
|
||||
{
|
||||
name: "llama3.2",
|
||||
description: "Meta's Llama 3.2 — lightweight models (1B/3B) with 128K context. Great for low-resource setups.",
|
||||
size: "2.0 GB",
|
||||
bestFor: "Light tasks, fast responses, low RAM",
|
||||
category: "General Purpose",
|
||||
},
|
||||
{
|
||||
name: "llama3.1",
|
||||
description: "Meta's Llama 3.1 8B — strong general-purpose model with good instruction following. 128K context.",
|
||||
size: "4.9 GB",
|
||||
bestFor: "General chat, writing, Q&A",
|
||||
category: "General Purpose",
|
||||
},
|
||||
{
|
||||
name: "llama3.3",
|
||||
description: "Meta's Llama 3.3 70B — 405B-level performance in a 70B model. 128K context. Top tier open model.",
|
||||
size: "43 GB",
|
||||
bestFor: "Complex reasoning, detailed analysis",
|
||||
category: "General Purpose",
|
||||
},
|
||||
{
|
||||
name: "gemma3",
|
||||
description: "Google's Gemma 3 — multimodal (vision + text), 1B to 27B. 128K context, 140+ languages.",
|
||||
size: "5.2 GB",
|
||||
bestFor: "Multilingual, vision, general tasks",
|
||||
category: "General Purpose",
|
||||
},
|
||||
{
|
||||
name: "qwen3",
|
||||
description: "Alibaba's Qwen 3 — latest generation, 0.6B to 235B. Up to 256K context. Hybrid thinking modes.",
|
||||
size: "4.7 GB",
|
||||
bestFor: "Multilingual, reasoning, code, math",
|
||||
category: "General Purpose",
|
||||
},
|
||||
{
|
||||
name: "qwen2.5",
|
||||
description: "Alibaba's Qwen 2.5 7B — multilingual model with strong coding and math skills. 32K context.",
|
||||
size: "4.7 GB",
|
||||
bestFor: "Multilingual, code, math",
|
||||
category: "General Purpose",
|
||||
},
|
||||
{
|
||||
name: "mistral",
|
||||
description: "Mistral 7B v0.3 — fast and efficient with function calling support. 32K context.",
|
||||
size: "4.1 GB",
|
||||
bestFor: "Fast responses, general tasks",
|
||||
category: "General Purpose",
|
||||
},
|
||||
{
|
||||
name: "phi4",
|
||||
description: "Microsoft Phi-4 14B — strong reasoning and math for its size. Successor to Phi-3.",
|
||||
size: "9.1 GB",
|
||||
bestFor: "Reasoning, math, structured tasks",
|
||||
category: "General Purpose",
|
||||
},
|
||||
{
|
||||
name: "command-r",
|
||||
description: "Cohere's Command R 35B — enterprise-grade model with 128K context and light content filtering.",
|
||||
size: "20 GB",
|
||||
bestFor: "RAG, conversation, creative tasks",
|
||||
category: "General Purpose",
|
||||
},
|
||||
// — Reasoning —
|
||||
{
|
||||
name: "deepseek-r1",
|
||||
description: "DeepSeek R1 — chain-of-thought reasoning model. Distilled versions from 1.5B to 70B run locally.",
|
||||
size: "4.7 GB",
|
||||
bestFor: "Step-by-step reasoning, math, logic",
|
||||
category: "Reasoning",
|
||||
},
|
||||
// — Coding —
|
||||
{
|
||||
name: "qwen2.5-coder",
|
||||
description: "Alibaba's Qwen 2.5 Coder — 0.5B to 32B. 32B version rivals GPT-4o on coding benchmarks.",
|
||||
size: "4.7 GB",
|
||||
bestFor: "Code generation, refactoring, debugging",
|
||||
category: "Coding",
|
||||
},
|
||||
{
|
||||
name: "deepseek-coder-v2",
|
||||
description: "DeepSeek Coder V2 16B — strong coding model with 160K context and math ability.",
|
||||
size: "8.9 GB",
|
||||
bestFor: "Code, math, technical problem solving",
|
||||
category: "Coding",
|
||||
},
|
||||
// — Uncensored / Creative Writing —
|
||||
{
|
||||
name: "dolphin3",
|
||||
description: "Eric Hartford's Dolphin 3 — next-gen uncensored model based on Llama 3.1 8B. 128K context.",
|
||||
size: "4.9 GB",
|
||||
bestFor: "Uncensored chat, coding, creative writing",
|
||||
category: "Uncensored / Creative Writing",
|
||||
},
|
||||
{
|
||||
name: "dolphin-mistral",
|
||||
description: "Dolphin fine-tune of Mistral 7B. Safety/refusal data removed from training. 32K context.",
|
||||
size: "4.1 GB",
|
||||
bestFor: "Uncensored general chat, creative writing",
|
||||
category: "Uncensored / Creative Writing",
|
||||
},
|
||||
{
|
||||
name: "dolphin-llama3",
|
||||
description: "Dolphin fine-tune of Llama 3 8B. Uncensored training on a strong base model.",
|
||||
size: "4.7 GB",
|
||||
bestFor: "Uncensored chat, strong reasoning",
|
||||
category: "Uncensored / Creative Writing",
|
||||
},
|
||||
{
|
||||
name: "dolphin-mixtral",
|
||||
description: "Dolphin fine-tune of Mixtral 8x7B MoE. Uncensored with mixture-of-experts architecture.",
|
||||
size: "26 GB",
|
||||
bestFor: "Uncensored + high capability (needs RAM)",
|
||||
category: "Uncensored / Creative Writing",
|
||||
},
|
||||
{
|
||||
name: "nous-hermes2",
|
||||
description: "Nous Research's Hermes 2 — trained on diverse synthetic data with minimal refusal behavior.",
|
||||
size: "4.1 GB",
|
||||
bestFor: "Instruction following, few refusals",
|
||||
category: "Uncensored / Creative Writing",
|
||||
},
|
||||
{
|
||||
name: "openhermes",
|
||||
description: "Community fine-tune focused on helpfulness. Based on Mistral 7B without refusal patterns.",
|
||||
size: "4.1 GB",
|
||||
bestFor: "Helpful assistant, minimal filtering",
|
||||
category: "Uncensored / Creative Writing",
|
||||
},
|
||||
];
|
||||
|
||||
const selectedModel = ref("");
|
||||
const modelTab = ref<"installed" | "available">("installed");
|
||||
|
||||
// Base URL setting (admin only)
|
||||
const baseUrl = ref("");
|
||||
const savingBaseUrl = ref(false);
|
||||
const baseUrlSaved = ref(false);
|
||||
|
||||
const modelStatuses = computed(() => {
|
||||
const installed = new Set(
|
||||
store.installedModels.map((m) => m.replace(/:latest$/, ""))
|
||||
);
|
||||
return MODEL_CATALOG.map((m) => ({
|
||||
...m,
|
||||
installed: installed.has(m.name) || installed.has(m.name.replace(/:.*$/, "")),
|
||||
active: isActiveModel(m.name),
|
||||
}));
|
||||
});
|
||||
|
||||
const installedModels = computed(() =>
|
||||
modelStatuses.value.filter((m) => m.installed)
|
||||
);
|
||||
|
||||
const categories = computed(() => {
|
||||
const cats: string[] = [];
|
||||
for (const m of modelStatuses.value) {
|
||||
if (!cats.includes(m.category)) cats.push(m.category);
|
||||
}
|
||||
return cats;
|
||||
});
|
||||
|
||||
function modelsInCategory(category: string) {
|
||||
return modelStatuses.value.filter((m) => m.category === category);
|
||||
}
|
||||
|
||||
function isActiveModel(name: string): boolean {
|
||||
const current = selectedModel.value || store.defaultModel;
|
||||
if (!current) return false;
|
||||
const cleanCurrent = current.replace(/:latest$/, "");
|
||||
const cleanName = name.replace(/:latest$/, "");
|
||||
return cleanCurrent === cleanName;
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await store.fetchSettings();
|
||||
assistantName.value = store.assistantName;
|
||||
selectedModel.value = store.defaultModel;
|
||||
store.fetchInstalledModels();
|
||||
|
||||
// Load notification preferences from user settings
|
||||
const allSettings = await apiGet<Record<string, string>>("/api/settings");
|
||||
@@ -235,6 +70,14 @@ onMounted(async () => {
|
||||
notifySecurityAlerts.value = allSettings.notify_security_alerts !== "false";
|
||||
}
|
||||
|
||||
// Load CalDAV settings
|
||||
try {
|
||||
const caldavConfig = await apiGet<Record<string, string>>("/api/settings/caldav");
|
||||
caldav.value = { ...caldav.value, ...caldavConfig };
|
||||
} catch {
|
||||
// CalDAV not configured yet
|
||||
}
|
||||
|
||||
// Load admin settings
|
||||
if (authStore.isAdmin) {
|
||||
try {
|
||||
@@ -291,63 +134,6 @@ async function saveAssistant() {
|
||||
}
|
||||
}
|
||||
|
||||
async function selectModel(name: string) {
|
||||
selectedModel.value = name;
|
||||
saving.value = true;
|
||||
try {
|
||||
await store.updateSettings({ default_model: name });
|
||||
} finally {
|
||||
saving.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function pullModel(name: string) {
|
||||
pullProgress.value = { model: name, percent: 0 };
|
||||
try {
|
||||
await store.pullModel(name, (data) => {
|
||||
if (data.error) {
|
||||
pullProgress.value = null;
|
||||
return;
|
||||
}
|
||||
const completed = data.completed as number | undefined;
|
||||
const total = data.total as number | undefined;
|
||||
if (completed != null && total && total > 0) {
|
||||
pullProgress.value = {
|
||||
model: name,
|
||||
percent: Math.round((completed / total) * 100),
|
||||
};
|
||||
}
|
||||
});
|
||||
await store.fetchInstalledModels();
|
||||
} catch {
|
||||
// error already handled
|
||||
} finally {
|
||||
pullProgress.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeModel(name: string) {
|
||||
if (confirmDelete.value !== name) {
|
||||
confirmDelete.value = name;
|
||||
return;
|
||||
}
|
||||
confirmDelete.value = null;
|
||||
deleting.value = name;
|
||||
try {
|
||||
await store.deleteModel(name);
|
||||
// If the deleted model was active, clear the selection
|
||||
if (isActiveModel(name)) {
|
||||
selectedModel.value = "";
|
||||
}
|
||||
} finally {
|
||||
deleting.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
function cancelDelete() {
|
||||
confirmDelete.value = null;
|
||||
}
|
||||
|
||||
async function exportData(scope: "user" | "full") {
|
||||
exporting.value = true;
|
||||
try {
|
||||
@@ -393,6 +179,38 @@ async function saveNotifications() {
|
||||
}
|
||||
}
|
||||
|
||||
async function saveCaldav() {
|
||||
savingCaldav.value = true;
|
||||
caldavSaved.value = false;
|
||||
try {
|
||||
await apiPut("/api/settings/caldav", caldav.value);
|
||||
caldavSaved.value = true;
|
||||
setTimeout(() => (caldavSaved.value = false), 2000);
|
||||
} catch {
|
||||
toastStore.show("Failed to save CalDAV settings", "error");
|
||||
} finally {
|
||||
savingCaldav.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function testCaldav() {
|
||||
testingCaldav.value = true;
|
||||
caldavTestResult.value = null;
|
||||
try {
|
||||
const result = await apiPost<{ success: boolean; message?: string; error?: string; calendars?: string[] }>("/api/settings/caldav/test", {});
|
||||
caldavTestResult.value = result;
|
||||
} catch (e: unknown) {
|
||||
if (e && typeof e === "object" && "body" in e) {
|
||||
const body = (e as { body?: { error?: string } }).body;
|
||||
caldavTestResult.value = { success: false, error: body?.error || "Connection test failed" };
|
||||
} else {
|
||||
caldavTestResult.value = { success: false, error: "Connection test failed" };
|
||||
}
|
||||
} finally {
|
||||
testingCaldav.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSmtp() {
|
||||
savingSmtp.value = true;
|
||||
smtpSaved.value = false;
|
||||
@@ -576,6 +394,55 @@ async function handleRestoreFile(event: Event) {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="settings-section">
|
||||
<h2>Calendar (CalDAV)</h2>
|
||||
<p class="section-desc">
|
||||
Connect to a CalDAV server (Nextcloud, iCloud, Radicale, Baikal) to create and view calendar events from chat.
|
||||
</p>
|
||||
|
||||
<div class="caldav-grid">
|
||||
<div class="field">
|
||||
<label for="caldav-url">CalDAV URL</label>
|
||||
<input id="caldav-url" v-model="caldav.caldav_url" type="url" placeholder="https://cloud.example.com/remote.php/dav" class="input" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="caldav-username">Username</label>
|
||||
<input id="caldav-username" v-model="caldav.caldav_username" type="text" class="input" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="caldav-password">Password</label>
|
||||
<input id="caldav-password" v-model="caldav.caldav_password" type="password" class="input" />
|
||||
</div>
|
||||
<div class="field">
|
||||
<label for="caldav-calendar-name">Calendar Name</label>
|
||||
<input id="caldav-calendar-name" v-model="caldav.caldav_calendar_name" type="text" placeholder="Leave empty to use first available" class="input" />
|
||||
<p class="field-hint">Optional. The exact name of the calendar to use.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="actions" style="margin-bottom: 1rem;">
|
||||
<button class="btn-save" @click="saveCaldav" :disabled="savingCaldav">
|
||||
{{ savingCaldav ? "Saving..." : "Save" }}
|
||||
</button>
|
||||
<span v-if="caldavSaved" class="saved-msg">Saved!</span>
|
||||
<button class="btn-save btn-test" @click="testCaldav" :disabled="testingCaldav">
|
||||
{{ testingCaldav ? "Testing..." : "Test Connection" }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="caldavTestResult" class="test-result" :class="{ success: caldavTestResult.success, error: !caldavTestResult.success }">
|
||||
<template v-if="caldavTestResult.success">
|
||||
{{ caldavTestResult.message }}
|
||||
<div v-if="caldavTestResult.calendars?.length" class="test-calendars">
|
||||
Calendars: {{ caldavTestResult.calendars.join(", ") }}
|
||||
</div>
|
||||
</template>
|
||||
<template v-else>
|
||||
{{ caldavTestResult.error }}
|
||||
</template>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-if="authStore.isAdmin" class="settings-section">
|
||||
<h2>Application URL</h2>
|
||||
<p class="section-desc">
|
||||
@@ -664,126 +531,6 @@ async function handleRestoreFile(event: Event) {
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="settings-section">
|
||||
<h2>Model</h2>
|
||||
|
||||
<div class="model-tabs">
|
||||
<button
|
||||
class="model-tab"
|
||||
:class="{ active: modelTab === 'installed' }"
|
||||
@click="modelTab = 'installed'"
|
||||
>
|
||||
Installed
|
||||
</button>
|
||||
<button
|
||||
class="model-tab"
|
||||
:class="{ active: modelTab === 'available' }"
|
||||
@click="modelTab = 'available'"
|
||||
>
|
||||
Available
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<!-- Installed tab -->
|
||||
<template v-if="modelTab === 'installed'">
|
||||
<p class="section-desc">
|
||||
Models currently downloaded and ready to use.
|
||||
</p>
|
||||
<div v-if="installedModels.length === 0" class="empty-state">
|
||||
No models installed. Browse the Available tab to download one.
|
||||
</div>
|
||||
<div v-else class="model-list">
|
||||
<div
|
||||
v-for="model in installedModels"
|
||||
:key="model.name"
|
||||
class="model-card"
|
||||
:class="{ active: model.active }"
|
||||
>
|
||||
<div class="model-info">
|
||||
<div class="model-name-row">
|
||||
<span class="model-name">{{ model.name }}</span>
|
||||
<span class="model-size">{{ model.size }}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="model-actions">
|
||||
<button
|
||||
v-if="!model.active"
|
||||
class="btn-select"
|
||||
@click="selectModel(model.name)"
|
||||
:disabled="saving"
|
||||
>
|
||||
Select
|
||||
</button>
|
||||
<span v-else class="active-badge">Active</span>
|
||||
<template v-if="confirmDelete === model.name">
|
||||
<button
|
||||
class="btn-confirm-delete"
|
||||
@click="removeModel(model.name)"
|
||||
:disabled="deleting !== null"
|
||||
>
|
||||
{{ deleting === model.name ? "Removing..." : "Confirm" }}
|
||||
</button>
|
||||
<button class="btn-cancel-delete" @click="cancelDelete">
|
||||
Cancel
|
||||
</button>
|
||||
</template>
|
||||
<button
|
||||
v-else
|
||||
class="btn-remove"
|
||||
@click="removeModel(model.name)"
|
||||
:disabled="deleting !== null || model.active"
|
||||
:title="model.active ? 'Cannot remove the active model' : 'Remove model'"
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- Available tab -->
|
||||
<template v-if="modelTab === 'available'">
|
||||
<p class="section-desc">
|
||||
Browse and download models. Models need to be downloaded before use.
|
||||
</p>
|
||||
<div v-for="cat in categories" :key="cat" class="model-category">
|
||||
<h3 class="category-label">{{ cat }}</h3>
|
||||
<div class="model-list">
|
||||
<div
|
||||
v-for="model in modelsInCategory(cat)"
|
||||
:key="model.name"
|
||||
class="model-card"
|
||||
:class="{ active: model.active }"
|
||||
>
|
||||
<div class="model-info">
|
||||
<div class="model-name-row">
|
||||
<span class="model-name">{{ model.name }}</span>
|
||||
<span class="model-size">{{ model.size }}</span>
|
||||
</div>
|
||||
<p class="model-desc">{{ model.description }}</p>
|
||||
<p class="model-best-for">
|
||||
<strong>Best for:</strong> {{ model.bestFor }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="model-actions">
|
||||
<template v-if="model.installed">
|
||||
<span class="installed-badge">Installed</span>
|
||||
</template>
|
||||
<button
|
||||
v-else
|
||||
class="btn-pull"
|
||||
@click="pullModel(model.name)"
|
||||
:disabled="pullProgress !== null"
|
||||
>
|
||||
{{ pullProgress?.model === model.name ? `Downloading ${pullProgress.percent}%` : "Download" }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
|
||||
<section class="settings-section">
|
||||
<h2>Data</h2>
|
||||
<p class="section-desc">Export your data or restore from a backup.</p>
|
||||
@@ -917,223 +664,6 @@ async function handleRestoreFile(event: Event) {
|
||||
color: var(--color-danger);
|
||||
}
|
||||
|
||||
/* Model list */
|
||||
.model-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
.model-card {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: flex-start;
|
||||
gap: 1rem;
|
||||
padding: 1rem;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
background: var(--color-bg);
|
||||
transition: border-color 0.15s;
|
||||
}
|
||||
.model-card.active {
|
||||
border-color: var(--color-primary);
|
||||
background: color-mix(in srgb, var(--color-primary) 5%, var(--color-bg));
|
||||
}
|
||||
.model-info {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
.model-name-row {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 0.3rem;
|
||||
}
|
||||
.model-name {
|
||||
font-weight: 600;
|
||||
font-size: 0.95rem;
|
||||
font-family: monospace;
|
||||
}
|
||||
.model-size {
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-text-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
.model-desc {
|
||||
margin: 0 0 0.25rem;
|
||||
font-size: 0.85rem;
|
||||
color: var(--color-text-secondary);
|
||||
line-height: 1.4;
|
||||
}
|
||||
.model-best-for {
|
||||
margin: 0;
|
||||
font-size: 0.8rem;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
.model-best-for strong {
|
||||
color: var(--color-text-secondary);
|
||||
}
|
||||
.btn-select {
|
||||
padding: 0.35rem 0.9rem;
|
||||
background: var(--color-primary);
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: pointer;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.btn-select:hover:not(:disabled) {
|
||||
opacity: 0.9;
|
||||
}
|
||||
.btn-select:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
.btn-pull {
|
||||
padding: 0.35rem 0.9rem;
|
||||
background: var(--color-bg-secondary);
|
||||
color: var(--color-text);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: pointer;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
.btn-pull:hover:not(:disabled) {
|
||||
border-color: var(--color-primary);
|
||||
color: var(--color-primary);
|
||||
}
|
||||
.btn-pull:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
.active-badge {
|
||||
padding: 0.25rem 0.75rem;
|
||||
background: var(--color-primary);
|
||||
color: #fff;
|
||||
border-radius: var(--radius-lg);
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* Model tabs */
|
||||
.model-tabs {
|
||||
display: flex;
|
||||
gap: 0.5rem;
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
.model-tab {
|
||||
padding: 0.4rem 1rem;
|
||||
background: transparent;
|
||||
color: var(--color-text-muted);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: pointer;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
.model-tab.active {
|
||||
background: var(--color-primary);
|
||||
color: #fff;
|
||||
border-color: var(--color-primary);
|
||||
}
|
||||
.model-tab:hover:not(.active) {
|
||||
border-color: var(--color-text-muted);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
/* Installed badge on available tab */
|
||||
.installed-badge {
|
||||
padding: 0.25rem 0.75rem;
|
||||
background: var(--color-success);
|
||||
color: #fff;
|
||||
border-radius: var(--radius-lg);
|
||||
font-size: 0.8rem;
|
||||
font-weight: 600;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Empty state */
|
||||
.empty-state {
|
||||
padding: 2rem 1rem;
|
||||
text-align: center;
|
||||
color: var(--color-text-muted);
|
||||
font-size: 0.9rem;
|
||||
border: 1px dashed var(--color-border);
|
||||
border-radius: var(--radius-md);
|
||||
}
|
||||
|
||||
/* Category headers */
|
||||
.model-category {
|
||||
margin-bottom: 1.5rem;
|
||||
}
|
||||
.model-category:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.category-label {
|
||||
margin: 0 0 0.5rem;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
/* Model actions layout */
|
||||
.model-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-shrink: 0;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
/* Remove button */
|
||||
.btn-remove {
|
||||
padding: 0.25rem 0.6rem;
|
||||
background: transparent;
|
||||
color: var(--color-text-muted);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: pointer;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.btn-remove:hover:not(:disabled) {
|
||||
border-color: var(--color-danger);
|
||||
color: var(--color-danger);
|
||||
}
|
||||
.btn-remove:disabled {
|
||||
opacity: 0.4;
|
||||
cursor: default;
|
||||
}
|
||||
.btn-confirm-delete {
|
||||
padding: 0.25rem 0.6rem;
|
||||
background: var(--color-danger);
|
||||
color: #fff;
|
||||
border: none;
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: pointer;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
.btn-confirm-delete:hover:not(:disabled) {
|
||||
filter: brightness(0.9);
|
||||
}
|
||||
.btn-confirm-delete:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: default;
|
||||
}
|
||||
.btn-cancel-delete {
|
||||
padding: 0.25rem 0.6rem;
|
||||
background: transparent;
|
||||
color: var(--color-text-muted);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-sm);
|
||||
cursor: pointer;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
.btn-cancel-delete:hover {
|
||||
color: var(--color-text);
|
||||
border-color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
/* Data section */
|
||||
.data-actions {
|
||||
display: flex;
|
||||
@@ -1196,6 +726,49 @@ async function handleRestoreFile(event: Event) {
|
||||
accent-color: var(--color-primary);
|
||||
}
|
||||
|
||||
/* CalDAV grid */
|
||||
.caldav-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 0 1rem;
|
||||
}
|
||||
@media (max-width: 480px) {
|
||||
.caldav-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
.btn-test {
|
||||
background: var(--color-bg-secondary);
|
||||
color: var(--color-text);
|
||||
border: 1px solid var(--color-border);
|
||||
}
|
||||
.btn-test:hover:not(:disabled) {
|
||||
border-color: var(--color-primary);
|
||||
color: var(--color-primary);
|
||||
opacity: 1;
|
||||
}
|
||||
.test-result {
|
||||
padding: 0.75rem 1rem;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
.test-result.success {
|
||||
background: color-mix(in srgb, var(--color-success) 10%, var(--color-bg));
|
||||
border: 1px solid var(--color-success);
|
||||
color: var(--color-success);
|
||||
}
|
||||
.test-result.error {
|
||||
background: color-mix(in srgb, var(--color-danger) 10%, var(--color-bg));
|
||||
border: 1px solid var(--color-danger);
|
||||
color: var(--color-danger);
|
||||
}
|
||||
.test-calendars {
|
||||
margin-top: 0.35rem;
|
||||
font-size: 0.85rem;
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
/* SMTP grid */
|
||||
.smtp-grid {
|
||||
display: grid;
|
||||
|
||||
@@ -6,6 +6,7 @@ import { useNotesStore } from "@/stores/notes";
|
||||
import { useToastStore } from "@/stores/toast";
|
||||
import { renderMarkdown } from "@/utils/markdown";
|
||||
import { useAssist } from "@/composables/useAssist";
|
||||
import { apiPost } from "@/api/client";
|
||||
import type { TaskStatus, TaskPriority } from "@/types/task";
|
||||
import type { Editor } from "@tiptap/vue-3";
|
||||
import MarkdownToolbar from "@/components/MarkdownToolbar.vue";
|
||||
@@ -61,6 +62,41 @@ function truncateTarget(text: string, max = 60): string {
|
||||
return first.length > max ? first.slice(0, max) + "..." : first;
|
||||
}
|
||||
|
||||
// Tag suggestions
|
||||
const suggestedTags = ref<string[]>([]);
|
||||
const appliedTags = ref<Set<string>>(new Set());
|
||||
const suggestingTags = ref(false);
|
||||
|
||||
async function fetchTagSuggestions() {
|
||||
if (suggestingTags.value) return;
|
||||
suggestingTags.value = true;
|
||||
suggestedTags.value = [];
|
||||
appliedTags.value = new Set();
|
||||
try {
|
||||
const res = await apiPost<{ suggested_tags: string[] }>("/api/notes/suggest-tags", {
|
||||
title: title.value,
|
||||
body: body.value,
|
||||
});
|
||||
suggestedTags.value = res.suggested_tags;
|
||||
} catch {
|
||||
toast.show("Failed to get tag suggestions", "error");
|
||||
} finally {
|
||||
suggestingTags.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function applyTagSuggestion(tag: string) {
|
||||
if (appliedTags.value.has(tag)) return;
|
||||
body.value = body.value.trimEnd() + `\n#${tag}`;
|
||||
appliedTags.value.add(tag);
|
||||
markDirty();
|
||||
}
|
||||
|
||||
function dismissTagSuggestions() {
|
||||
suggestedTags.value = [];
|
||||
appliedTags.value = new Set();
|
||||
}
|
||||
|
||||
let savedTitle = "";
|
||||
let savedBody = "";
|
||||
let savedStatus: TaskStatus = "todo";
|
||||
@@ -227,6 +263,25 @@ onUnmounted(() => window.removeEventListener("beforeunload", onBeforeUnload));
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="tag-suggest-row">
|
||||
<button class="btn-suggest-tags" @click="fetchTagSuggestions" :disabled="suggestingTags">
|
||||
{{ suggestingTags ? "Suggesting..." : "Suggest tags" }}
|
||||
</button>
|
||||
<template v-if="suggestedTags.length > 0">
|
||||
<button
|
||||
v-for="tag in suggestedTags"
|
||||
:key="tag"
|
||||
:class="['tag-pill', { applied: appliedTags.has(tag) }]"
|
||||
:disabled="appliedTags.has(tag)"
|
||||
@click="applyTagSuggestion(tag)"
|
||||
>
|
||||
#{{ tag }}
|
||||
<span v-if="appliedTags.has(tag)" class="tag-check">✓</span>
|
||||
</button>
|
||||
<button class="btn-dismiss-tags" @click="dismissTagSuggestions">×</button>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="editor-tabs">
|
||||
<button
|
||||
:class="['tab', { active: !showPreview }]"
|
||||
@@ -460,6 +515,69 @@ onUnmounted(() => window.removeEventListener("beforeunload", onBeforeUnload));
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
/* ── Tag suggestions ── */
|
||||
.tag-suggest-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
.btn-suggest-tags {
|
||||
padding: 0.3rem 0.7rem;
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: var(--radius-sm);
|
||||
background: var(--color-bg-card);
|
||||
color: var(--color-text-secondary);
|
||||
cursor: pointer;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
.btn-suggest-tags:hover:not(:disabled) {
|
||||
border-color: var(--color-primary);
|
||||
color: var(--color-primary);
|
||||
}
|
||||
.btn-suggest-tags:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: wait;
|
||||
}
|
||||
.tag-pill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.2rem;
|
||||
padding: 0.2rem 0.55rem;
|
||||
border: 1px solid var(--color-primary);
|
||||
border-radius: 999px;
|
||||
background: transparent;
|
||||
color: var(--color-primary);
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s, color 0.15s;
|
||||
}
|
||||
.tag-pill:hover:not(:disabled) {
|
||||
background: var(--color-primary);
|
||||
color: #fff;
|
||||
}
|
||||
.tag-pill.applied {
|
||||
background: var(--color-success, #2ecc71);
|
||||
border-color: var(--color-success, #2ecc71);
|
||||
color: #fff;
|
||||
cursor: default;
|
||||
}
|
||||
.tag-check {
|
||||
font-size: 0.7rem;
|
||||
}
|
||||
.btn-dismiss-tags {
|
||||
padding: 0.1rem 0.4rem;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--color-text-muted);
|
||||
cursor: pointer;
|
||||
font-size: 1rem;
|
||||
line-height: 1;
|
||||
}
|
||||
.btn-dismiss-tags:hover {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
/* ── Assist panel ── */
|
||||
.assist-panel {
|
||||
flex: 0 0 33.33%;
|
||||
|
||||
@@ -16,6 +16,8 @@ dependencies = [
|
||||
"hypercorn>=0.17",
|
||||
"bcrypt>=4.0",
|
||||
"aiosmtplib>=3.0",
|
||||
"caldav>=1.3",
|
||||
"icalendar>=5.0",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
|
||||
@@ -23,7 +23,7 @@ class Config:
|
||||
"postgresql+asyncpg://fabled:fabled@localhost:5432/fabledassistant",
|
||||
)
|
||||
OLLAMA_URL: str = os.environ.get("OLLAMA_URL", "http://localhost:11434")
|
||||
OLLAMA_MODEL: str = os.environ.get("OLLAMA_MODEL", "llama3.1")
|
||||
OLLAMA_MODEL: str = os.environ.get("OLLAMA_MODEL", "mistral")
|
||||
SECRET_KEY: str = _read_secret("SECRET_KEY", "SECRET_KEY_FILE", "dev-secret-change-me")
|
||||
SECURE_COOKIES: bool = os.environ.get("SECURE_COOKIES", "").lower() in ("1", "true", "yes")
|
||||
LOG_LEVEL: str = os.environ.get("LOG_LEVEL", "INFO")
|
||||
|
||||
@@ -27,6 +27,7 @@ from fabledassistant.services.notes import (
|
||||
update_note,
|
||||
)
|
||||
from fabledassistant.services.settings import get_setting
|
||||
from fabledassistant.services.tag_suggestions import suggest_tags
|
||||
from fabledassistant.utils.tags import extract_tags
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -95,6 +96,37 @@ async def list_tags_route():
|
||||
return jsonify({"tags": tags})
|
||||
|
||||
|
||||
@notes_bp.route("/suggest-tags", methods=["POST"])
|
||||
@login_required
|
||||
async def suggest_tags_route():
|
||||
uid = get_current_user_id()
|
||||
data = await request.get_json()
|
||||
title = data.get("title", "")
|
||||
body = data.get("body", "")
|
||||
tags = await suggest_tags(uid, title, body)
|
||||
return jsonify({"suggested_tags": tags})
|
||||
|
||||
|
||||
@notes_bp.route("/<int:note_id>/append-tag", methods=["POST"])
|
||||
@login_required
|
||||
async def append_tag_route(note_id: int):
|
||||
uid = get_current_user_id()
|
||||
data = await request.get_json()
|
||||
tag = data.get("tag", "").strip()
|
||||
if not tag:
|
||||
return jsonify({"error": "tag is required"}), 400
|
||||
|
||||
note = await get_note(uid, note_id)
|
||||
if note is None:
|
||||
return jsonify({"error": "Note not found"}), 404
|
||||
|
||||
# Append #tag to body
|
||||
new_body = note.body.rstrip() + f"\n#{tag}" if note.body else f"#{tag}"
|
||||
tags = extract_tags(new_body)
|
||||
updated = await update_note(uid, note_id, body=new_body, tags=tags)
|
||||
return jsonify(updated.to_dict())
|
||||
|
||||
|
||||
@notes_bp.route("/by-title", methods=["GET"])
|
||||
@login_required
|
||||
async def get_note_by_title_route():
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
from quart import Blueprint, jsonify, request
|
||||
|
||||
from fabledassistant.auth import login_required, get_current_user_id
|
||||
from fabledassistant.services.caldav import CALDAV_SETTING_KEYS, get_caldav_config, test_connection
|
||||
from fabledassistant.services.llm import get_installed_models
|
||||
from fabledassistant.services.settings import get_all_settings, set_settings_batch
|
||||
|
||||
@@ -32,3 +33,39 @@ async def update_settings_route():
|
||||
await set_settings_batch(uid, {k: str(v) for k, v in data.items()})
|
||||
settings = await get_all_settings(uid)
|
||||
return jsonify(settings)
|
||||
|
||||
|
||||
@settings_bp.route("/caldav", methods=["GET"])
|
||||
@login_required
|
||||
async def get_caldav():
|
||||
uid = get_current_user_id()
|
||||
config = await get_caldav_config(uid)
|
||||
if config.get("caldav_password"):
|
||||
config["caldav_password"] = "********"
|
||||
return jsonify(config)
|
||||
|
||||
|
||||
@settings_bp.route("/caldav", methods=["PUT"])
|
||||
@login_required
|
||||
async def update_caldav():
|
||||
uid = get_current_user_id()
|
||||
data = await request.get_json()
|
||||
|
||||
settings_to_save = {}
|
||||
for key in CALDAV_SETTING_KEYS:
|
||||
if key in data:
|
||||
if key == "caldav_password" and data[key] == "********":
|
||||
continue
|
||||
settings_to_save[key] = str(data[key])
|
||||
|
||||
if settings_to_save:
|
||||
await set_settings_batch(uid, settings_to_save)
|
||||
return jsonify({"status": "ok"})
|
||||
|
||||
|
||||
@settings_bp.route("/caldav/test", methods=["POST"])
|
||||
@login_required
|
||||
async def test_caldav():
|
||||
uid = get_current_user_id()
|
||||
result = await test_connection(uid)
|
||||
return jsonify(result)
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
"""CalDAV calendar integration service."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import caldav
|
||||
import icalendar
|
||||
|
||||
from fabledassistant.services.settings import get_all_settings
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CALDAV_SETTING_KEYS = ["caldav_url", "caldav_username", "caldav_password", "caldav_calendar_name"]
|
||||
|
||||
|
||||
async def get_caldav_config(user_id: int) -> dict[str, str]:
|
||||
"""Read CalDAV settings for the given user."""
|
||||
all_settings = await get_all_settings(user_id)
|
||||
return {k: all_settings.get(k, "") for k in CALDAV_SETTING_KEYS}
|
||||
|
||||
|
||||
async def is_caldav_configured(user_id: int) -> bool:
|
||||
"""Check if CalDAV URL, username, and password are all set."""
|
||||
config = await get_caldav_config(user_id)
|
||||
return bool(config.get("caldav_url") and config.get("caldav_username") and config.get("caldav_password"))
|
||||
|
||||
|
||||
def _get_calendar(client: caldav.DAVClient, calendar_name: str) -> caldav.Calendar:
|
||||
"""Get a named calendar or the first available one (synchronous)."""
|
||||
principal = client.principal()
|
||||
calendars = principal.calendars()
|
||||
if not calendars:
|
||||
raise ValueError("No calendars found on the CalDAV server.")
|
||||
if calendar_name:
|
||||
for cal in calendars:
|
||||
if cal.name == calendar_name:
|
||||
return cal
|
||||
names = [c.name for c in calendars]
|
||||
raise ValueError(f"Calendar '{calendar_name}' not found. Available: {', '.join(names)}")
|
||||
return calendars[0]
|
||||
|
||||
|
||||
def _make_client(config: dict[str, str]) -> caldav.DAVClient:
|
||||
"""Create a CalDAV client from config dict."""
|
||||
return caldav.DAVClient(
|
||||
url=config["caldav_url"],
|
||||
username=config["caldav_username"],
|
||||
password=config["caldav_password"],
|
||||
)
|
||||
|
||||
|
||||
def _parse_vevent(component) -> dict | None:
|
||||
"""Extract event data from a VEVENT component."""
|
||||
if component.name != "VEVENT":
|
||||
return None
|
||||
title = str(component.get("SUMMARY", ""))
|
||||
dtstart = component.get("DTSTART")
|
||||
dtend = component.get("DTEND")
|
||||
location = str(component.get("LOCATION", ""))
|
||||
start_str = dtstart.dt.isoformat() if dtstart else ""
|
||||
end_str = dtend.dt.isoformat() if dtend else ""
|
||||
return {
|
||||
"title": title,
|
||||
"start": start_str,
|
||||
"end": end_str,
|
||||
"location": location,
|
||||
}
|
||||
|
||||
|
||||
async def create_event(
|
||||
user_id: int,
|
||||
title: str,
|
||||
start: str,
|
||||
end: str | None = None,
|
||||
duration: int | None = None,
|
||||
description: str | None = None,
|
||||
location: str | None = None,
|
||||
) -> dict:
|
||||
"""Create a calendar event. start/end are ISO datetime strings."""
|
||||
config = await get_caldav_config(user_id)
|
||||
if not (config.get("caldav_url") and config.get("caldav_username") and config.get("caldav_password")):
|
||||
raise ValueError("CalDAV is not configured. Go to Settings → Calendar to set it up.")
|
||||
|
||||
dt_start = datetime.fromisoformat(start)
|
||||
if end:
|
||||
dt_end = datetime.fromisoformat(end)
|
||||
else:
|
||||
dt_end = dt_start + timedelta(minutes=duration or 60)
|
||||
|
||||
cal = icalendar.Calendar()
|
||||
cal.add("prodid", "-//FabledAssistant//EN")
|
||||
cal.add("version", "2.0")
|
||||
|
||||
event = icalendar.Event()
|
||||
event.add("summary", title)
|
||||
event.add("dtstart", dt_start)
|
||||
event.add("dtend", dt_end)
|
||||
if description:
|
||||
event.add("description", description)
|
||||
if location:
|
||||
event.add("location", location)
|
||||
cal.add_component(event)
|
||||
|
||||
ical_str = cal.to_ical().decode("utf-8")
|
||||
|
||||
def _save():
|
||||
client = _make_client(config)
|
||||
calendar = _get_calendar(client, config.get("caldav_calendar_name", ""))
|
||||
calendar.save_event(ical_str)
|
||||
|
||||
await asyncio.to_thread(_save)
|
||||
|
||||
return {
|
||||
"title": title,
|
||||
"start": dt_start.isoformat(),
|
||||
"end": dt_end.isoformat(),
|
||||
}
|
||||
|
||||
|
||||
async def list_events(user_id: int, date_from: str, date_to: str) -> list[dict]:
|
||||
"""List calendar events in a date range. Dates are ISO datetime strings."""
|
||||
config = await get_caldav_config(user_id)
|
||||
if not (config.get("caldav_url") and config.get("caldav_username") and config.get("caldav_password")):
|
||||
raise ValueError("CalDAV is not configured. Go to Settings → Calendar to set it up.")
|
||||
|
||||
dt_from = datetime.fromisoformat(date_from)
|
||||
dt_to = datetime.fromisoformat(date_to)
|
||||
|
||||
def _search():
|
||||
client = _make_client(config)
|
||||
calendar = _get_calendar(client, config.get("caldav_calendar_name", ""))
|
||||
return calendar.date_search(dt_from, dt_to)
|
||||
|
||||
results = await asyncio.to_thread(_search)
|
||||
|
||||
events = []
|
||||
for result in results:
|
||||
cal = icalendar.Calendar.from_ical(result.data)
|
||||
for component in cal.walk():
|
||||
parsed = _parse_vevent(component)
|
||||
if parsed:
|
||||
events.append(parsed)
|
||||
return events
|
||||
|
||||
|
||||
async def search_events(user_id: int, query: str, days_ahead: int = 90) -> list[dict]:
|
||||
"""Search events by keyword in the next N days."""
|
||||
now = datetime.now()
|
||||
date_from = now.isoformat()
|
||||
date_to = (now + timedelta(days=days_ahead)).isoformat()
|
||||
|
||||
all_events = await list_events(user_id, date_from, date_to)
|
||||
q = query.lower()
|
||||
return [
|
||||
e for e in all_events
|
||||
if q in e["title"].lower() or q in e.get("location", "").lower()
|
||||
]
|
||||
|
||||
|
||||
async def test_connection(user_id: int) -> dict:
|
||||
"""Test the CalDAV connection and return status."""
|
||||
config = await get_caldav_config(user_id)
|
||||
if not (config.get("caldav_url") and config.get("caldav_username") and config.get("caldav_password")):
|
||||
return {"success": False, "error": "CalDAV is not configured. Please fill in URL, username, and password."}
|
||||
|
||||
def _test():
|
||||
client = _make_client(config)
|
||||
principal = client.principal()
|
||||
calendars = principal.calendars()
|
||||
return [c.name for c in calendars]
|
||||
|
||||
try:
|
||||
calendar_names = await asyncio.to_thread(_test)
|
||||
return {
|
||||
"success": True,
|
||||
"calendars": calendar_names,
|
||||
"message": f"Connected successfully. Found {len(calendar_names)} calendar(s).",
|
||||
}
|
||||
except Exception as e:
|
||||
error_msg = str(e)
|
||||
if "401" in error_msg or "403" in error_msg or "Unauthorized" in error_msg:
|
||||
error_msg = "Authentication failed. Check your username and password."
|
||||
elif "404" in error_msg or "Not Found" in error_msg:
|
||||
error_msg = "CalDAV endpoint not found. Check your URL."
|
||||
elif "Connection" in error_msg or "resolve" in error_msg:
|
||||
error_msg = f"Connection failed: {error_msg}"
|
||||
return {"success": False, "error": error_msg}
|
||||
@@ -6,6 +6,7 @@ Runs independently of any HTTP connection.
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
|
||||
from sqlalchemy import update
|
||||
@@ -15,10 +16,13 @@ from fabledassistant.models.conversation import Message
|
||||
from fabledassistant.services.generation_buffer import GenerationBuffer, GenerationState
|
||||
from fabledassistant.services.llm import ChatChunk, generate_completion, stream_chat, stream_chat_with_tools
|
||||
from fabledassistant.services.chat import update_conversation_title
|
||||
from fabledassistant.services.tools import TOOL_DEFINITIONS, execute_tool
|
||||
from fabledassistant.services.tools import get_tools_for_user, execute_tool
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Mistral prefixes tool-call responses with "[TOOL_CALLS]" as visible text
|
||||
_TOOL_CALL_MARKER = re.compile(r"^\s*\[TOOL_CALLS\]\s*", re.IGNORECASE)
|
||||
|
||||
DB_FLUSH_INTERVAL = 5.0 # seconds between partial DB flushes
|
||||
|
||||
|
||||
@@ -87,20 +91,28 @@ async def run_generation(
|
||||
last_flush = time.monotonic()
|
||||
all_tool_calls: list[dict] = []
|
||||
|
||||
# Resolve tools based on user's configured integrations
|
||||
tools = await get_tools_for_user(user_id)
|
||||
logger.info("Starting generation for conv %d: model=%s, tools=%d", conv_id, model, len(tools))
|
||||
|
||||
try:
|
||||
cancelled = False
|
||||
|
||||
for _round in range(MAX_TOOL_ROUNDS + 1):
|
||||
round_tool_calls: list[dict] = []
|
||||
logger.info("Generation round %d started for conv %d (model=%s)", _round, conv_id, model)
|
||||
|
||||
async for chunk in stream_chat_with_tools(messages, model, tools=TOOL_DEFINITIONS):
|
||||
async for chunk in stream_chat_with_tools(messages, model, tools=tools):
|
||||
if buf.cancel_event.is_set():
|
||||
cancelled = True
|
||||
break
|
||||
|
||||
if chunk.type == "content":
|
||||
buf.content_so_far += chunk.content
|
||||
buf.append_event("chunk", {"chunk": chunk.content})
|
||||
# Filter out "[TOOL_CALLS]" marker from streaming output
|
||||
clean = _TOOL_CALL_MARKER.sub("", chunk.content)
|
||||
if clean:
|
||||
buf.append_event("chunk", {"chunk": clean})
|
||||
|
||||
# Periodic DB flush
|
||||
now = time.monotonic()
|
||||
@@ -112,13 +124,16 @@ async def run_generation(
|
||||
last_flush = now
|
||||
|
||||
elif chunk.type == "tool_calls" and chunk.tool_calls:
|
||||
logger.info("Round %d: model returned %d tool call(s)", _round, len(chunk.tool_calls))
|
||||
# Process each tool call
|
||||
for tc in chunk.tool_calls:
|
||||
fn = tc.get("function", {})
|
||||
tool_name = fn.get("name", "")
|
||||
arguments = fn.get("arguments", {})
|
||||
logger.info("Executing tool: %s(%s)", tool_name, json.dumps(arguments)[:200])
|
||||
|
||||
result = await execute_tool(user_id, tool_name, arguments)
|
||||
logger.info("Tool %s result: success=%s", tool_name, result.get("success"))
|
||||
|
||||
tool_record = {
|
||||
"function": tool_name,
|
||||
@@ -133,12 +148,19 @@ async def run_generation(
|
||||
buf.append_event("tool_call", {"tool_call": tool_record})
|
||||
|
||||
if cancelled:
|
||||
logger.info("Generation cancelled for conv %d", conv_id)
|
||||
break
|
||||
|
||||
# If no tool calls this round, the LLM gave its final text response
|
||||
if not round_tool_calls:
|
||||
logger.info("Round %d: no tool calls, final content length=%d", _round, len(buf.content_so_far))
|
||||
break
|
||||
|
||||
logger.info("Round %d: %d tool call(s) executed, starting next round", _round, len(round_tool_calls))
|
||||
|
||||
# Strip model artifacts like "[TOOL_CALLS]" from content
|
||||
buf.content_so_far = _TOOL_CALL_MARKER.sub("", buf.content_so_far)
|
||||
|
||||
# Append assistant tool_call message and tool results to conversation
|
||||
# for the next round
|
||||
messages.append({
|
||||
@@ -159,7 +181,12 @@ async def run_generation(
|
||||
# Reset content for the next round (LLM will produce a new response)
|
||||
buf.content_so_far = ""
|
||||
|
||||
# Strip model artifacts from final content
|
||||
buf.content_so_far = _TOOL_CALL_MARKER.sub("", buf.content_so_far)
|
||||
|
||||
# Final save
|
||||
logger.info("Generation complete for conv %d: content_length=%d, tool_calls=%d",
|
||||
conv_id, len(buf.content_so_far), len(all_tool_calls))
|
||||
await _update_message(
|
||||
msg_id,
|
||||
buf.content_so_far,
|
||||
|
||||
@@ -8,6 +8,7 @@ from typing import Literal
|
||||
import httpx
|
||||
|
||||
from fabledassistant.config import Config
|
||||
from fabledassistant.services.caldav import is_caldav_configured
|
||||
from fabledassistant.services.notes import get_note, search_notes_for_context
|
||||
from fabledassistant.services.settings import get_setting
|
||||
|
||||
@@ -79,9 +80,10 @@ async def stream_chat(
|
||||
options: dict | None = None,
|
||||
) -> AsyncGenerator[str, None]:
|
||||
"""Stream chat completion from Ollama, yielding content chunks."""
|
||||
payload: dict = {"model": model, "messages": messages, "stream": True}
|
||||
merged_options = {"num_ctx": 16384}
|
||||
if options:
|
||||
payload["options"] = options
|
||||
merged_options.update(options)
|
||||
payload: dict = {"model": model, "messages": messages, "stream": True, "options": merged_options}
|
||||
async with httpx.AsyncClient(timeout=httpx.Timeout(1800.0, connect=30.0, read=300.0)) as client:
|
||||
async with client.stream(
|
||||
"POST",
|
||||
@@ -119,7 +121,17 @@ async def stream_chat_with_tools(
|
||||
ChatChunk(type="tool_calls") is yielded. Always ends with
|
||||
ChatChunk(type="done").
|
||||
"""
|
||||
payload: dict = {"model": model, "messages": messages, "stream": True}
|
||||
options: dict = {"num_ctx": 16384}
|
||||
# Disable thinking mode for models like qwen3 — it interferes with tool calling
|
||||
if tools:
|
||||
options["num_predict"] = 4096
|
||||
payload: dict = {
|
||||
"model": model,
|
||||
"messages": messages,
|
||||
"stream": True,
|
||||
"options": options,
|
||||
"think": False,
|
||||
}
|
||||
if tools:
|
||||
payload["tools"] = tools
|
||||
async with httpx.AsyncClient(timeout=httpx.Timeout(1800.0, connect=30.0, read=300.0)) as client:
|
||||
@@ -129,6 +141,7 @@ async def stream_chat_with_tools(
|
||||
json=payload,
|
||||
) as resp:
|
||||
resp.raise_for_status()
|
||||
accumulated_tool_calls: list[dict] = []
|
||||
async for line in resp.aiter_lines():
|
||||
if not line.strip():
|
||||
continue
|
||||
@@ -140,11 +153,22 @@ async def stream_chat_with_tools(
|
||||
if chunk:
|
||||
yield ChatChunk(type="content", content=chunk)
|
||||
|
||||
# Check for tool calls on done
|
||||
# Collect tool calls from any message (some models
|
||||
# emit them before the done flag)
|
||||
tc = msg.get("tool_calls")
|
||||
if tc:
|
||||
accumulated_tool_calls.extend(tc)
|
||||
|
||||
if data.get("done"):
|
||||
tool_calls = msg.get("tool_calls")
|
||||
if tool_calls:
|
||||
yield ChatChunk(type="tool_calls", tool_calls=tool_calls)
|
||||
if accumulated_tool_calls:
|
||||
logger.info(
|
||||
"Ollama returned %d tool call(s): %s",
|
||||
len(accumulated_tool_calls),
|
||||
json.dumps(accumulated_tool_calls)[:500],
|
||||
)
|
||||
yield ChatChunk(type="tool_calls", tool_calls=accumulated_tool_calls)
|
||||
else:
|
||||
logger.debug("Ollama done with no tool calls")
|
||||
yield ChatChunk(type="done")
|
||||
break
|
||||
|
||||
@@ -220,14 +244,19 @@ async def build_context(
|
||||
from datetime import date as date_type
|
||||
assistant_name = await get_setting(user_id, "assistant_name", "Fable")
|
||||
today = date_type.today().isoformat()
|
||||
has_caldav = await is_caldav_configured(user_id)
|
||||
date_guidance = "For relative dates like 'Friday' or 'next week', resolve them to YYYY-MM-DD format."
|
||||
if has_caldav:
|
||||
date_guidance += " For calendar events, use ISO 8601 datetime format (e.g. 2025-01-15T14:00:00)."
|
||||
|
||||
system_parts = [
|
||||
f"You are a helpful assistant named {assistant_name}, integrated into a note-taking and task-tracking app called Fabled Assistant. "
|
||||
"Help users with their notes, tasks, and general questions. "
|
||||
"When note context is provided, use it to give relevant answers. "
|
||||
f"Today's date is {today}. "
|
||||
"You have tools available to create tasks, create notes, and search the user's notes. "
|
||||
"Use them when the user asks you to create, add, or find tasks and notes. "
|
||||
"For relative dates like 'Friday' or 'next week', resolve them to YYYY-MM-DD format."
|
||||
"When the user asks you to create, add, or find something, use the provided tool functions. "
|
||||
"Do not describe or write out function calls as text — actually invoke the tools. "
|
||||
f"{date_guidance}"
|
||||
]
|
||||
|
||||
context_meta: dict = {
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
"""LLM-powered tag suggestions for notes and tasks."""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
|
||||
from fabledassistant.config import Config
|
||||
from fabledassistant.services.llm import generate_completion
|
||||
from fabledassistant.services.notes import get_all_tags
|
||||
from fabledassistant.services.settings import get_setting
|
||||
from fabledassistant.utils.tags import extract_tags
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def suggest_tags(user_id: int, title: str, body: str) -> list[str]:
|
||||
"""Suggest relevant tags for a note/task based on its content.
|
||||
|
||||
Returns a list of tag strings (without # prefix), excluding tags
|
||||
already present in the body.
|
||||
"""
|
||||
if not title.strip() and not body.strip():
|
||||
return []
|
||||
|
||||
existing_tags = await get_all_tags(user_id)
|
||||
model = await get_setting(user_id, "default_model", Config.OLLAMA_MODEL)
|
||||
|
||||
existing_list = ", ".join(f"#{t}" for t in existing_tags) if existing_tags else "(none yet)"
|
||||
|
||||
messages = [
|
||||
{
|
||||
"role": "system",
|
||||
"content": (
|
||||
"You are a tag suggestion assistant. Given a note's title and body, "
|
||||
"suggest 3-5 relevant tags. Prefer reusing existing tags when they fit, "
|
||||
"but you may suggest new ones too. Reply with ONLY a JSON array of tag "
|
||||
'strings (without # prefix). Example: ["meeting", "project/alpha", "followup"]\n\n'
|
||||
f"Existing tags: {existing_list}"
|
||||
),
|
||||
},
|
||||
{
|
||||
"role": "user",
|
||||
"content": f"Title: {title}\n\nBody:\n{body[:2000]}",
|
||||
},
|
||||
]
|
||||
|
||||
try:
|
||||
response = await generate_completion(messages, model)
|
||||
except Exception:
|
||||
logger.warning("Tag suggestion LLM call failed", exc_info=True)
|
||||
return []
|
||||
|
||||
tags = _parse_tag_list(response)
|
||||
|
||||
# Filter out tags already in the body
|
||||
body_tags = set(extract_tags(body))
|
||||
tags = [t for t in tags if t not in body_tags]
|
||||
|
||||
return tags[:5]
|
||||
|
||||
|
||||
def _parse_tag_list(response: str) -> list[str]:
|
||||
"""Parse a JSON array of tags from LLM response, with fallback for markdown wrapping."""
|
||||
text = response.strip()
|
||||
|
||||
# Try direct JSON parse
|
||||
try:
|
||||
parsed = json.loads(text)
|
||||
if isinstance(parsed, list):
|
||||
return [str(t).strip().lstrip("#") for t in parsed if t]
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
# Fallback: extract JSON array from markdown code block
|
||||
match = re.search(r"\[.*?\]", text, re.DOTALL)
|
||||
if match:
|
||||
try:
|
||||
parsed = json.loads(match.group())
|
||||
if isinstance(parsed, list):
|
||||
return [str(t).strip().lstrip("#") for t in parsed if t]
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
logger.warning("Could not parse tag suggestions from LLM response: %s", text[:200])
|
||||
return []
|
||||
@@ -3,11 +3,19 @@
|
||||
import logging
|
||||
from datetime import date, datetime
|
||||
|
||||
from fabledassistant.services.caldav import (
|
||||
create_event,
|
||||
is_caldav_configured,
|
||||
list_events,
|
||||
search_events,
|
||||
)
|
||||
from fabledassistant.services.notes import create_note, list_notes
|
||||
from fabledassistant.services.tag_suggestions import suggest_tags
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TOOL_DEFINITIONS = [
|
||||
# Core tools — always available
|
||||
_CORE_TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
@@ -78,6 +86,94 @@ TOOL_DEFINITIONS = [
|
||||
},
|
||||
]
|
||||
|
||||
# CalDAV tools — only included when user has CalDAV configured
|
||||
_CALDAV_TOOLS = [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "create_event",
|
||||
"description": "Create a calendar event for the user. Use this when the user asks to schedule, add, or create a meeting, appointment, or event.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"title": {
|
||||
"type": "string",
|
||||
"description": "The event title",
|
||||
},
|
||||
"start": {
|
||||
"type": "string",
|
||||
"description": "Start date/time in ISO 8601 format (e.g. 2025-01-15T14:00:00)",
|
||||
},
|
||||
"end": {
|
||||
"type": "string",
|
||||
"description": "Optional end date/time in ISO 8601 format",
|
||||
},
|
||||
"duration": {
|
||||
"type": "integer",
|
||||
"description": "Optional duration in minutes (default 60, ignored if end is set)",
|
||||
},
|
||||
"description": {
|
||||
"type": "string",
|
||||
"description": "Optional event description",
|
||||
},
|
||||
"location": {
|
||||
"type": "string",
|
||||
"description": "Optional event location",
|
||||
},
|
||||
},
|
||||
"required": ["title", "start"],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "list_events",
|
||||
"description": "List calendar events in a date range. Use this when the user asks what events or meetings they have.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"date_from": {
|
||||
"type": "string",
|
||||
"description": "Start of range in ISO 8601 format (e.g. 2025-01-15T00:00:00)",
|
||||
},
|
||||
"date_to": {
|
||||
"type": "string",
|
||||
"description": "End of range in ISO 8601 format (e.g. 2025-01-22T23:59:59)",
|
||||
},
|
||||
},
|
||||
"required": ["date_from", "date_to"],
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "search_events",
|
||||
"description": "Search calendar events by keyword. Use this when the user asks to find a specific event or meeting.",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {
|
||||
"type": "string",
|
||||
"description": "Search keyword to match against event titles and locations",
|
||||
},
|
||||
},
|
||||
"required": ["query"],
|
||||
},
|
||||
},
|
||||
},
|
||||
]
|
||||
|
||||
|
||||
async def get_tools_for_user(user_id: int) -> list[dict]:
|
||||
"""Build the tool list for a user based on their configured integrations."""
|
||||
tools = list(_CORE_TOOLS)
|
||||
if await is_caldav_configured(user_id):
|
||||
tools.extend(_CALDAV_TOOLS)
|
||||
logger.debug("User %d: %d tools available", user_id, len(tools))
|
||||
return tools
|
||||
|
||||
|
||||
def _parse_due_date(value: str | None) -> date | None:
|
||||
"""Parse a due date string, returning None on failure."""
|
||||
@@ -94,14 +190,17 @@ async def execute_tool(user_id: int, tool_name: str, arguments: dict) -> dict:
|
||||
"""Execute a tool call and return the result."""
|
||||
try:
|
||||
if tool_name == "create_task":
|
||||
task_title = arguments.get("title", "Untitled Task")
|
||||
task_body = arguments.get("body", "")
|
||||
note = await create_note(
|
||||
user_id=user_id,
|
||||
title=arguments.get("title", "Untitled Task"),
|
||||
body=arguments.get("body", ""),
|
||||
title=task_title,
|
||||
body=task_body,
|
||||
status="todo",
|
||||
priority=arguments.get("priority", "none"),
|
||||
due_date=_parse_due_date(arguments.get("due_date")),
|
||||
)
|
||||
suggested = await suggest_tags(user_id, task_title, task_body)
|
||||
return {
|
||||
"success": True,
|
||||
"type": "task",
|
||||
@@ -112,14 +211,18 @@ async def execute_tool(user_id: int, tool_name: str, arguments: dict) -> dict:
|
||||
"priority": note.priority,
|
||||
"due_date": str(note.due_date) if note.due_date else None,
|
||||
},
|
||||
"suggested_tags": suggested,
|
||||
}
|
||||
|
||||
elif tool_name == "create_note":
|
||||
note_title = arguments.get("title", "Untitled Note")
|
||||
note_body = arguments.get("body", "")
|
||||
note = await create_note(
|
||||
user_id=user_id,
|
||||
title=arguments.get("title", "Untitled Note"),
|
||||
body=arguments.get("body", ""),
|
||||
title=note_title,
|
||||
body=note_body,
|
||||
)
|
||||
suggested = await suggest_tags(user_id, note_title, note_body)
|
||||
return {
|
||||
"success": True,
|
||||
"type": "note",
|
||||
@@ -127,6 +230,7 @@ async def execute_tool(user_id: int, tool_name: str, arguments: dict) -> dict:
|
||||
"id": note.id,
|
||||
"title": note.title,
|
||||
},
|
||||
"suggested_tags": suggested,
|
||||
}
|
||||
|
||||
elif tool_name == "search_notes":
|
||||
@@ -151,6 +255,52 @@ async def execute_tool(user_id: int, tool_name: str, arguments: dict) -> dict:
|
||||
},
|
||||
}
|
||||
|
||||
elif tool_name == "create_event":
|
||||
result = await create_event(
|
||||
user_id=user_id,
|
||||
title=arguments.get("title", "Untitled Event"),
|
||||
start=arguments["start"],
|
||||
end=arguments.get("end"),
|
||||
duration=arguments.get("duration"),
|
||||
description=arguments.get("description"),
|
||||
location=arguments.get("location"),
|
||||
)
|
||||
return {
|
||||
"success": True,
|
||||
"type": "event",
|
||||
"data": result,
|
||||
}
|
||||
|
||||
elif tool_name == "list_events":
|
||||
events = await list_events(
|
||||
user_id=user_id,
|
||||
date_from=arguments["date_from"],
|
||||
date_to=arguments["date_to"],
|
||||
)
|
||||
return {
|
||||
"success": True,
|
||||
"type": "events",
|
||||
"data": {
|
||||
"count": len(events),
|
||||
"events": events,
|
||||
},
|
||||
}
|
||||
|
||||
elif tool_name == "search_events":
|
||||
events = await search_events(
|
||||
user_id=user_id,
|
||||
query=arguments.get("query", ""),
|
||||
)
|
||||
return {
|
||||
"success": True,
|
||||
"type": "events",
|
||||
"data": {
|
||||
"query": arguments.get("query", ""),
|
||||
"count": len(events),
|
||||
"events": events,
|
||||
},
|
||||
}
|
||||
|
||||
else:
|
||||
return {"success": False, "error": f"Unknown tool: {tool_name}"}
|
||||
|
||||
|
||||
+22
-8
@@ -12,7 +12,7 @@
|
||||
> Include file-level details in the commit body when the change is non-trivial.
|
||||
|
||||
## Last Updated
|
||||
2026-02-14 — Phase 7: LLM tool calling (create tasks, create notes, search notes from chat)
|
||||
2026-02-15 — Phase 8: CalDAV calendar integration, LLM-suggested tags, settings/model UI refinements
|
||||
|
||||
## Project Overview
|
||||
Fabled Assistant is a self-hosted note-taking and task-tracking application with
|
||||
@@ -212,7 +212,7 @@ for AI-assisted features.
|
||||
```
|
||||
fabledassistant/
|
||||
├── summary.md # This file — canonical project context
|
||||
├── pyproject.toml # Python project config
|
||||
├── pyproject.toml # Python project config (deps include caldav, icalendar)
|
||||
├── Dockerfile # Multi-stage build (Node → Python)
|
||||
├── docker-compose.yml # Dev compose (app, PostgreSQL, Ollama)
|
||||
├── docker-compose.prod.yml # Production stack (Docker Swarm, secrets, network isolation)
|
||||
@@ -253,7 +253,7 @@ fabledassistant/
|
||||
│ │ ├── auth.py # /api/auth blueprint: register, login, logout, me, status, password reset, invitation registration
|
||||
│ │ ├── admin.py # /api/admin blueprint: backup, restore, user management, registration toggle, invitations, base URL, SMTP (admin only)
|
||||
│ │ ├── chat.py # /api/chat blueprint: conversations CRUD, SSE message streaming (all @login_required)
|
||||
│ │ ├── notes.py # /api/notes CRUD + wikilinks + backlinks (all @login_required)
|
||||
│ │ ├── notes.py # /api/notes CRUD + wikilinks + backlinks + tag suggestions (all @login_required)
|
||||
│ │ ├── tasks.py # /api/tasks CRUD + PATCH status (all @login_required)
|
||||
│ │ └── settings.py # /api/settings GET/PUT — per-user settings (@login_required)
|
||||
│ ├── services/
|
||||
@@ -264,7 +264,9 @@ fabledassistant/
|
||||
│ │ ├── chat.py # Conversation CRUD with user_id isolation, add_message, save/summarize as note (LLM-titled, chat-tagged)
|
||||
│ │ ├── generation_buffer.py # In-memory SSE event buffer with cancel_event, reconnect support, auto-cleanup; supports chat (int keys) and assist (string keys)
|
||||
│ │ ├── generation_task.py # Background asyncio tasks: run_generation (chat, DB flush, titles, tool loop) + run_assist_generation (lightweight, no DB)
|
||||
│ │ ├── tools.py # LLM tool definitions (create_task, create_note, search_notes) + execute_tool dispatcher
|
||||
│ │ ├── tools.py # LLM tool definitions (create_task, create_note, search_notes, CalDAV events) + execute_tool dispatcher
|
||||
│ │ ├── tag_suggestions.py # LLM-powered tag suggestions: suggest_tags() builds prompt with existing tags, calls generate_completion, parses JSON response
|
||||
│ │ ├── caldav.py # CalDAV integration: create/list/search calendar events via caldav library (per-user config from settings)
|
||||
│ │ ├── settings.py # Settings CRUD with user_id isolation: get_setting, set_setting, set_settings_batch, get_all_settings
|
||||
│ │ ├── logging.py # App logging: log_audit, log_usage, log_error, get_logs, get_log_stats, delete_old_logs, start_log_retention_loop
|
||||
│ │ ├── email.py # SMTP email service: get_smtp_config, is_smtp_configured, send_email, send_test_email
|
||||
@@ -320,10 +322,10 @@ fabledassistant/
|
||||
│ │ ├── HomeView.vue # Actionable dashboard: overdue, due today, due this week, high priority, in progress tasks; recent chats with inline chat input; recently edited notes; model warming on mount
|
||||
│ │ ├── SettingsView.vue # Settings page: assistant name, model catalog, data export/restore (admin)
|
||||
│ │ ├── NotesListView.vue # Note list: search, sort, tag filter pills, pagination
|
||||
│ │ ├── NoteEditorView.vue # Create/edit: Tiptap editor, sticky toolbar, AI Assist panel (bottom 1/3), Ctrl+S, unsaved guard
|
||||
│ │ ├── NoteEditorView.vue # Create/edit: Tiptap editor, sticky toolbar, AI Assist panel (bottom 1/3), LLM tag suggestions, Ctrl+S, unsaved guard
|
||||
│ │ ├── NoteViewerView.vue # Markdown render, wikilink auto-create, convert-to-task, backlinks, table of contents sidebar
|
||||
│ │ ├── TasksListView.vue # Task list: search, status/priority filters, sort, pagination
|
||||
│ │ ├── TaskEditorView.vue # Create/edit task: Tiptap editor, sticky toolbar, AI Assist panel, Ctrl+S, dirty guard
|
||||
│ │ ├── TaskEditorView.vue # Create/edit task: Tiptap editor, sticky toolbar, AI Assist panel, LLM tag suggestions, Ctrl+S, dirty guard
|
||||
│ │ └── TaskViewerView.vue # Task detail: rendered markdown, badges, convert-to-note, backlinks, table of contents sidebar
|
||||
│ ├── components/
|
||||
│ │ ├── LogsView.vue # Admin log viewer: stats summary, category/search/date filters, paginated table with expandable detail rows
|
||||
@@ -331,7 +333,7 @@ fabledassistant/
|
||||
│ │ ├── ChatPanel.vue # Slide-out chat panel (right side overlay, receives contextNoteId prop), bubble-style messages, floating dark input, note picker, context pills with promote/exclude
|
||||
│ │ ├── ModelSelector.vue # Model dropdown (v-model pattern): fetches installed + running models, hot/cold indicators
|
||||
│ │ ├── DashboardChatInput.vue # Inline chat bar: ModelSelector + note picker + textarea + send button; emits submit event
|
||||
│ │ ├── ToolCallCard.vue # Compact card for tool call results (created task/note link, search results, errors)
|
||||
│ │ ├── ToolCallCard.vue # Compact card for tool call results (created task/note link, search results, errors) + suggested tag pills with apply-on-click
|
||||
│ │ ├── ChatMessage.vue # Message bubble: markdown rendering, tool call cards, configurable assistant name label, "Save as Note" action on assistant messages
|
||||
│ │ ├── NoteCard.vue # Card with rendered markdown preview (v-html), TagPill, tag-click emit, hover edit button
|
||||
│ │ ├── TaskCard.vue # Card with rendered preview (body not description), StatusBadge (clickable), PriorityBadge, due date, tags, hover edit button
|
||||
@@ -372,6 +374,8 @@ fabledassistant/
|
||||
| GET | `/api/notes` | List notes (params: `q`, `tag`, `sort`, `order`, `limit`, `offset`; defaults to `is_task=false` — plain notes only; `?is_task=true` for tasks, `?all=true` for everything) |
|
||||
| POST | `/api/notes` | Create note (body: `{title, body, status?, priority?, due_date?}` — tags auto-extracted) |
|
||||
| GET | `/api/notes/tags` | List all tags from notes table (param: `q` for filter) |
|
||||
| POST | `/api/notes/suggest-tags` | LLM-suggest tags for content (body: `{title, body}`, returns `{suggested_tags: [...]}`) |
|
||||
| POST | `/api/notes/:id/append-tag` | Append `#tag` to note body (body: `{tag}`, returns updated note) |
|
||||
| GET | `/api/notes/by-title?title=...` | Resolve note by exact title (case-insensitive) |
|
||||
| POST | `/api/notes/resolve-title` | Get-or-create note by title (for wikilink clicks) |
|
||||
| GET | `/api/notes/:id` | Get single note (response includes `is_task`, `status`, `priority`, `due_date`) |
|
||||
@@ -542,6 +546,15 @@ When adding a new migration, follow these conventions:
|
||||
components (linked titles for created items, search result lists). SSE emits `tool_call` events
|
||||
for real-time rendering during streaming. System prompt includes today's date for relative date
|
||||
resolution. Graceful degradation: models without tool support respond normally.
|
||||
- **CalDAV calendar integration:** Per-user CalDAV settings (URL, username, password, calendar name).
|
||||
LLM tools: `create_event`, `list_events`, `search_events`. Runs synchronous caldav library calls
|
||||
in asyncio executor. Settings UI for CalDAV configuration.
|
||||
- **LLM-suggested tags:** Backend service (`tag_suggestions.py`) prompts LLM with existing user tags
|
||||
and note content, returns 3-5 relevant tag suggestions. Tags already in body are filtered out.
|
||||
Exposed via `POST /api/notes/suggest-tags` and `POST /api/notes/:id/append-tag`. Integrated in:
|
||||
(1) Editor views — "Suggest tags" button shows clickable pills that insert `#tag` into body;
|
||||
(2) Chat tool calls — `create_note`/`create_task` results include `suggested_tags`, rendered as
|
||||
pills in ToolCallCard with one-click apply via append-tag API.
|
||||
|
||||
### Authentication & User Management
|
||||
- Session cookie auth with bcrypt, first-user-is-admin, orphaned data claiming
|
||||
@@ -594,9 +607,10 @@ When adding a new migration, follow these conventions:
|
||||
- To reset database: `docker compose down -v && docker compose up --build`
|
||||
|
||||
## Backlog
|
||||
- Tagging/labeling system with LLM-suggested tags
|
||||
- Calendar/timeline view for tasks
|
||||
- Import/export (Markdown files, JSON)
|
||||
- Email integration (read/send emails from chat via IMAP/SMTP tools)
|
||||
- Web search support (LLM tool to search the web and summarize results)
|
||||
- Application-level rate limiting on auth endpoints
|
||||
- Security headers middleware (CSP, X-Frame-Options, etc.) — currently handled at reverse proxy level
|
||||
- Session invalidation on user deletion
|
||||
|
||||
Reference in New Issue
Block a user