bug fixes, and performance improvements, and drawer
This commit is contained in:
@@ -318,16 +318,19 @@ button.accent:hover {
|
||||
mask-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' width='18' height='18'%3E%3Cpath fill='none' stroke='black' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M4 12a1 1 0 1 0 2 0a1 1 0 1 0-2 0m7 0a1 1 0 1 0 2 0a1 1 0 1 0-2 0m7 0a1 1 0 1 0 2 0a1 1 0 1 0-2 0'/%3E%3C/svg%3E");
|
||||
}
|
||||
|
||||
.reasoning-container.middle {
|
||||
mask-image: linear-gradient(#000, #000, transparent 0, #000 12%, #000 88%, transparent)
|
||||
.reasoning-container.top {
|
||||
-webkit-mask-image: linear-gradient(to bottom, #000 0%, #000 calc(100% - 24px), transparent 100%);
|
||||
mask-image: linear-gradient(to bottom, #000 0%, #000 calc(100% - 24px), transparent 100%);
|
||||
}
|
||||
|
||||
.reasoning-container.top {
|
||||
mask-image: linear-gradient(#000, transparent, #000 0, #000 12%, #000 88%, transparent)
|
||||
.reasoning-container.middle {
|
||||
-webkit-mask-image: linear-gradient(to bottom, transparent 0%, #000 24px, #000 calc(100% - 24px), transparent 100%);
|
||||
mask-image: linear-gradient(to bottom, transparent 0%, #000 24px, #000 calc(100% - 24px), transparent 100%);
|
||||
}
|
||||
|
||||
.reasoning-container.bottom {
|
||||
mask-image: linear-gradient(transparent, #000, transparent 0, #000 12%, #000 88%, #000)
|
||||
-webkit-mask-image: linear-gradient(to bottom, transparent 0%, #000 24px, #000 100%);
|
||||
mask-image: linear-gradient(to bottom, transparent 0%, #000 24px, #000 100%);
|
||||
}
|
||||
|
||||
/* Markdown renderer */
|
||||
|
||||
+151
-98
@@ -4,11 +4,17 @@ import { computed, onMounted, ref, watch, onUnmounted, nextTick, type Ref } from
|
||||
import type { ModelWithProvider, ProviderWithModels } from '~/composables/useModels';
|
||||
import type { Agent } from '~/composables/useAgents';
|
||||
import type FileSelector from './FileSelector.vue';
|
||||
import { getComposerHeight } from '~/utils/composer-size';
|
||||
|
||||
const { allModels } = await useModels();
|
||||
const { updateAgent, patchAgentLocally } = await useAgents();
|
||||
|
||||
const inputHeight: Ref<string> = ref('auto');
|
||||
const isDrawerOpen = useCookie<boolean>("chat:tools-drawer", { default: () => false });
|
||||
watch(isDrawerOpen, () => {
|
||||
emit("resize");
|
||||
});
|
||||
|
||||
const inputHeight: Ref<string> = ref('48px');
|
||||
const fileSelectorRef = ref<InstanceType<typeof FileSelector> | null>(null);
|
||||
const inputRef = ref<HTMLTextAreaElement | null>(null);
|
||||
let tempInput = '';
|
||||
@@ -303,47 +309,57 @@ const handleWindowKeyDown = async (event: KeyboardEvent) => {
|
||||
};
|
||||
|
||||
const mirrorRef = ref<HTMLDivElement | null>(null);
|
||||
const MIRROR_PROPERTIES = [
|
||||
'box-sizing', 'font-family', 'font-size', 'font-weight', 'font-style',
|
||||
'line-height', 'letter-spacing', 'word-spacing', 'text-align', 'text-indent',
|
||||
'text-transform', 'tab-size', 'padding-top', 'padding-bottom', 'padding-left',
|
||||
'padding-right', 'border-top-width', 'border-bottom-width', 'border-left-width',
|
||||
'border-right-width', 'border-style', 'white-space', 'overflow-wrap', 'word-break',
|
||||
] as const;
|
||||
let sizingRaf: number | undefined;
|
||||
let sizingObserver: ResizeObserver | undefined;
|
||||
let typographyObserver: MutationObserver | undefined;
|
||||
let sizingDirty = true;
|
||||
let mirrorWidth = '';
|
||||
let lineHeight = 24;
|
||||
let padding = 0;
|
||||
let borders = 0;
|
||||
let borderBox = true;
|
||||
|
||||
const resizeTextArea = () => {
|
||||
const textarea = inputRef.value;
|
||||
const mirror = mirrorRef.value;
|
||||
if (!textarea || !mirror) return;
|
||||
if (import.meta.server || sizingRaf !== undefined) return;
|
||||
sizingRaf = requestAnimationFrame(() => {
|
||||
sizingRaf = undefined;
|
||||
const textarea = inputRef.value;
|
||||
const mirror = mirrorRef.value;
|
||||
if (!textarea || !mirror) return;
|
||||
|
||||
emit('resize');
|
||||
nextTick().then(() => {
|
||||
mirror.textContent = (textarea.value || '\u200b') + '\n';
|
||||
if (sizingDirty) {
|
||||
// Finish style reads before changing the isolated measurement box.
|
||||
const styles = getComputedStyle(textarea);
|
||||
const values = MIRROR_PROPERTIES.map(property => styles.getPropertyValue(property));
|
||||
mirrorWidth = styles.width;
|
||||
lineHeight = Number.parseFloat(styles.lineHeight) || Number.parseFloat(styles.fontSize) * 1.2;
|
||||
padding = Number.parseFloat(styles.paddingTop) + Number.parseFloat(styles.paddingBottom);
|
||||
borders = Number.parseFloat(styles.borderTopWidth) + Number.parseFloat(styles.borderBottomWidth);
|
||||
borderBox = styles.boxSizing === 'border-box';
|
||||
MIRROR_PROPERTIES.forEach((property, index) => mirror.style.setProperty(property, values[index]!));
|
||||
mirror.style.width = mirrorWidth;
|
||||
sizingDirty = false;
|
||||
}
|
||||
|
||||
const textareaStyles = getComputedStyle(textarea);
|
||||
mirror.style.width = textareaStyles.width;
|
||||
mirror.style.fontFamily = textareaStyles.fontFamily;
|
||||
mirror.style.fontSize = textareaStyles.fontSize;
|
||||
mirror.style.lineHeight = textareaStyles.lineHeight;
|
||||
mirror.style.letterSpacing = textareaStyles.letterSpacing;
|
||||
mirror.style.wordSpacing = textareaStyles.wordSpacing;
|
||||
mirror.style.textAlign = textareaStyles.textAlign;
|
||||
mirror.style.paddingTop = textareaStyles.paddingTop;
|
||||
mirror.style.paddingBottom = textareaStyles.paddingBottom;
|
||||
mirror.style.paddingLeft = textareaStyles.paddingLeft;
|
||||
mirror.style.paddingRight = textareaStyles.paddingRight;
|
||||
mirror.style.borderTopWidth = textareaStyles.borderTopWidth;
|
||||
mirror.style.borderBottomWidth = textareaStyles.borderBottomWidth;
|
||||
mirror.style.borderLeftWidth = textareaStyles.borderLeftWidth;
|
||||
mirror.style.borderRightWidth = textareaStyles.borderRightWidth;
|
||||
mirror.style.whiteSpace = 'pre-wrap';
|
||||
mirror.style.wordWrap = 'break-word';
|
||||
mirror.style.overflow = 'hidden';
|
||||
// Preserve the final empty line without adding an extra line to ordinary text.
|
||||
mirror.textContent = textarea.value + '\u200b';
|
||||
const height = `${getComposerHeight(mirror.scrollHeight, lineHeight, padding, borders, borderBox)}px`;
|
||||
if (height === inputHeight.value) return;
|
||||
|
||||
const lineHeight = 24;
|
||||
const minLines = 2;
|
||||
const maxLines = 10;
|
||||
const minHeight = minLines * lineHeight;
|
||||
const maxHeight = maxLines * lineHeight;
|
||||
const height = Math.min(Math.max(mirror.scrollHeight, minHeight), maxHeight);
|
||||
inputHeight.value = `${height}px`;
|
||||
// Capture bottom-follow intent before applying the new height.
|
||||
emit('resize');
|
||||
inputHeight.value = height;
|
||||
});
|
||||
};
|
||||
|
||||
watch(textAreaValue, resizeTextArea, { immediate: true });
|
||||
watch(textAreaValue, resizeTextArea, { flush: 'post' });
|
||||
|
||||
let hasCommandKey = false;
|
||||
if (import.meta.server) {
|
||||
@@ -357,41 +373,51 @@ onBeforeMount(() => {
|
||||
tempInput = (document.getElementById('chat') as HTMLInputElement)?.value ?? '';
|
||||
});
|
||||
|
||||
let resizeRafId: number | undefined;
|
||||
const handleWindowResize = () => {
|
||||
if (resizeRafId) return;
|
||||
resizeRafId = requestAnimationFrame(() => {
|
||||
resizeRafId = undefined;
|
||||
resizeTextArea();
|
||||
});
|
||||
}
|
||||
sizingDirty = true;
|
||||
resizeTextArea();
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
textAreaValue.value = tempInput;
|
||||
document.addEventListener('keydown', handleWindowKeyDown);
|
||||
window.addEventListener('resize', handleWindowResize);
|
||||
inputRef.value?.addEventListener('paste', handlePaste);
|
||||
let observedWidth: number | undefined;
|
||||
sizingObserver = new ResizeObserver(([entry]) => {
|
||||
if (!entry || entry.contentRect.width === observedWidth) return;
|
||||
observedWidth = entry.contentRect.width;
|
||||
handleWindowResize();
|
||||
});
|
||||
if (inputRef.value) sizingObserver.observe(inputRef.value);
|
||||
typographyObserver = new MutationObserver(handleWindowResize);
|
||||
typographyObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style'] });
|
||||
document.fonts.addEventListener('loadingdone', handleWindowResize);
|
||||
handleWindowResize();
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener('keydown', handleWindowKeyDown);
|
||||
window.removeEventListener('resize', handleWindowResize);
|
||||
if (resizeRafId !== undefined) cancelAnimationFrame(resizeRafId);
|
||||
if (sizingRaf !== undefined) cancelAnimationFrame(sizingRaf);
|
||||
sizingObserver?.disconnect();
|
||||
typographyObserver?.disconnect();
|
||||
document.fonts.removeEventListener('loadingdone', handleWindowResize);
|
||||
inputRef.value?.removeEventListener('paste', handlePaste);
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div :class="['w-full flex max-h-full', $attrs.class]">
|
||||
<div ref="mirrorRef" aria-hidden="true"
|
||||
class="absolute top-0 left-0 pointer-events-none invisible overflow-hidden h-0"></div>
|
||||
<div class="relative w-full flex flex-shrink-1 flex-col gap-3 p-2 rounded-2xl border transition-border ease-in-out duration-300 bg-[var(--bg-container)]
|
||||
<div :class="['w-full flex flex-col max-h-full', $attrs.class]">
|
||||
<div ref="mirrorRef" data-chat-measurement aria-hidden="true"
|
||||
class="fixed top-0 left-0 pointer-events-none invisible overflow-hidden h-0 [contain:layout_style_paint]"></div>
|
||||
<div class="relative z-10 w-full flex flex-shrink-1 flex-col gap-3 p-2 rounded-2xl border transition-border ease-in-out duration-300 bg-[var(--bg-container)]
|
||||
border-[var(--color-border)] focus-within:border-[var(--color-border-active)]">
|
||||
<div v-if="files.length > 0"
|
||||
class="flex-shrink-0 flex flex-nowrap gap-2 pt-2 px-2 pb-1 overflow-x-auto overflow-y-hidden [scrollbar-width:thin]">
|
||||
<!-- TODO: show attachment previews -->
|
||||
<AttachmentPreview v-for="file in files" @delete="files = files.filter((f) => f.id !== file.id)"
|
||||
@retry="fileSelectorRef?.retryFile(file.id)" :key="file.id" :file="file" />
|
||||
@retry="fileSelectorRef?.retryFile(file.id)" :key="file.id" :file="file"></AttachmentPreview>
|
||||
</div>
|
||||
<div class="min-w-0 max-h-full">
|
||||
<!-- Grammarly literally breaks everything, go fuck yourself -->
|
||||
@@ -404,20 +430,76 @@ onUnmounted(() => {
|
||||
|
||||
<div class="flex items-center justify-between gap-2">
|
||||
<!-- TODO: since we dont want to model selector dropdown to potentially overflow, it has max-width: 100%, so, we need to maake the trigger large enough to fit the entire width of the dropdown -->
|
||||
<div class="flex flex-1 gap-1 min-w-0">
|
||||
<div class="flex flex-1 items-center gap-1 min-w-0">
|
||||
<button v-if="selectedModel?.capabilities.includes('tools')"
|
||||
type="button"
|
||||
@click="isDrawerOpen = !isDrawerOpen"
|
||||
class="sm:hidden relative flex items-center justify-center h-8.5 w-8.5 shrink-0 @hover:bg-[var(--color-hover)] rounded-lg transition-colors duration-200"
|
||||
:aria-label="isDrawerOpen ? 'Close tools drawer' : 'Open tools drawer'"
|
||||
:aria-expanded="isDrawerOpen">
|
||||
<span class="i-mynaui-chevron-down text-5 text-[var(--text-secondary)] transition-transform duration-200"
|
||||
:class="{ 'rotate-180': isDrawerOpen }"></span>
|
||||
<span v-if="!isDrawerOpen && (searchConfig.enabled || toolsConfig.python)"
|
||||
class="absolute top-1.5 right-1.5 w-2 h-2 rounded-full bg-[var(--color-accent)]"></span>
|
||||
</button>
|
||||
<ModelSelector v-if="providers !== undefined" :add-hotkey="true" v-model="selectedModel"
|
||||
:providers="providers" />
|
||||
<SearchSelector v-if="selectedModel?.capabilities.includes('tools')" :enabled="searchConfig.enabled"
|
||||
@update:enabled="(v: boolean) => { searchConfig.enabled = v; saveSearchConfig() }" />
|
||||
<ToolSelector v-if="selectedModel?.capabilities.includes('tools')" :python="toolsConfig.python"
|
||||
@update:python="(v: boolean) => { toolsConfig.python = v; saveToolsConfig() }" />
|
||||
<FileSelector ref="fileSelectorRef" :selected-model="selectedModel" v-model="files" />
|
||||
:providers="providers"></ModelSelector>
|
||||
<div v-if="selectedModel?.capabilities.includes('tools')" class="hidden sm:flex items-center gap-1">
|
||||
<SearchSelector :enabled="searchConfig.enabled"
|
||||
@update:enabled="(v: boolean) => { searchConfig.enabled = v; saveSearchConfig(); }"></SearchSelector>
|
||||
<ToolSelector :python="toolsConfig.python"
|
||||
@update:python="(v: boolean) => { toolsConfig.python = v; saveToolsConfig(); }"></ToolSelector>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="allowManualRole" class="flex items-center">
|
||||
<button aria-label="Send message" @click="handleSubmit"
|
||||
<div class="flex items-center gap-1 shrink-0">
|
||||
<FileSelector ref="fileSelectorRef" :selected-model="selectedModel" v-model="files"></FileSelector>
|
||||
<div v-if="allowManualRole" class="flex items-center">
|
||||
<button aria-label="Send message" @click="handleSubmit"
|
||||
:disabled="((!inputValue.content.trim() && files.length === 0) && !loading) || isUploading || hasFailedUploads"
|
||||
:class="[
|
||||
'h-8 w-8 rounded-l-lg rounded-r-none transition-all duration-200 flex items-center justify-center disabled:cursor-not-allowed disabled:bg-transparent',
|
||||
(inputValue.content.trim() || files.length > 0) && !loading && !isUploading && !hasFailedUploads
|
||||
? 'bg-[var(--color-accent)] text-[var(--color-accent-text)] @hover:bg-[var(--color-accent-hover)]'
|
||||
: 'text-[var(--text-dim)]',
|
||||
loading && 'bg-[var(--color-hover)] @hover:bg-[var(--color-active)]',
|
||||
]">
|
||||
<span v-if="loading" class="text-6.5 i-mynaui-stop-solid"></span>
|
||||
<span v-else class="text-5 i-mynaui-send-solid"></span>
|
||||
</button>
|
||||
<Dropdown placement="bottom-end">
|
||||
<template #default="{ setRef, isOpen, toggle }">
|
||||
<button :ref="setRef" aria-label="Message options" @click="toggle"
|
||||
:disabled="(!inputValue.content.trim() && files.length === 0) || loading || isUploading || hasFailedUploads"
|
||||
:class="[
|
||||
'h-8 w-6 rounded-r-lg rounded-l-none transition-all duration-200 flex items-center justify-center disabled:cursor-not-allowed border-l border-[var(--text-dim)] disabled:border-transparent',
|
||||
(inputValue.content.trim() || files.length > 0) && !loading && !isUploading && !hasFailedUploads
|
||||
? 'bg-[var(--color-accent)] text-[var(--color-accent-text)] @hover:bg-[var(--color-accent-hover)] disabled:bg-transparent'
|
||||
: 'text-[var(--text-dim)]',
|
||||
loading && 'bg-[var(--color-hover)] @hover:bg-[var(--color-active)]',
|
||||
]">
|
||||
<span class="text-4.5 i-mynaui-chevron-down" :class="{ 'rotate-180': isOpen }"></span>
|
||||
</button>
|
||||
</template>
|
||||
<template #dropdown="{ close }">
|
||||
<button
|
||||
class="flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm text-[var(--text-primary)] @hover:bg-[var(--color-hover)] transition-colors whitespace-nowrap"
|
||||
@click="handleAddMessage('user'); close()">
|
||||
<span class="text-4 i-mynaui-user"></span>
|
||||
Add as User
|
||||
</button>
|
||||
<button
|
||||
class="flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm text-[var(--text-primary)] @hover:bg-[var(--color-hover)] transition-colors whitespace-nowrap"
|
||||
@click="handleAddMessage('assistant'); close()">
|
||||
<span class="text-4 i-mynaui-sparkles"></span>
|
||||
Add as Assistant
|
||||
</button>
|
||||
</template>
|
||||
</Dropdown>
|
||||
</div>
|
||||
<button v-else aria-label="Send message" @click="handleSubmit"
|
||||
:disabled="((!inputValue.content.trim() && files.length === 0) && !loading) || isUploading || hasFailedUploads"
|
||||
:class="[
|
||||
'h-8 w-8 rounded-l-lg rounded-r-none transition-all duration-200 flex items-center justify-center disabled:cursor-not-allowed disabled:bg-transparent',
|
||||
'h-8 w-8 rounded-xl transition-all duration-200 flex items-center justify-center disabled:cursor-not-allowed disabled:bg-transparent',
|
||||
(inputValue.content.trim() || files.length > 0) && !loading && !isUploading && !hasFailedUploads
|
||||
? 'bg-[var(--color-accent)] text-[var(--color-accent-text)] @hover:bg-[var(--color-accent-hover)]'
|
||||
: 'text-[var(--text-dim)]',
|
||||
@@ -426,48 +508,19 @@ onUnmounted(() => {
|
||||
<span v-if="loading" class="text-6.5 i-mynaui-stop-solid"></span>
|
||||
<span v-else class="text-5 i-mynaui-send-solid"></span>
|
||||
</button>
|
||||
<Dropdown placement="bottom-end">
|
||||
<template #default="{ setRef, isOpen, toggle }">
|
||||
<button :ref="setRef" aria-label="Message options" @click="toggle"
|
||||
:disabled="(!inputValue.content.trim() && files.length === 0) || loading || isUploading || hasFailedUploads"
|
||||
:class="[
|
||||
'h-8 w-6 rounded-r-lg rounded-l-none transition-all duration-200 flex items-center justify-center disabled:cursor-not-allowed border-l border-[var(--text-dim)] disabled:border-transparent',
|
||||
(inputValue.content.trim() || files.length > 0) && !loading && !isUploading && !hasFailedUploads
|
||||
? 'bg-[var(--color-accent)] text-[var(--color-accent-text)] @hover:bg-[var(--color-accent-hover)] disabled:bg-transparent'
|
||||
: 'text-[var(--text-dim)]',
|
||||
loading && 'bg-[var(--color-hover)] @hover:bg-[var(--color-active)]',
|
||||
]">
|
||||
<span class="text-4.5 i-mynaui-chevron-down" :class="{ 'rotate-180': isOpen }"></span>
|
||||
</button>
|
||||
</template>
|
||||
<template #dropdown="{ close }">
|
||||
<button
|
||||
class="flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm text-[var(--text-primary)] @hover:bg-[var(--color-hover)] transition-colors whitespace-nowrap"
|
||||
@click="handleAddMessage('user'); close()">
|
||||
<span class="text-4 i-mynaui-user"></span>
|
||||
Add as User
|
||||
</button>
|
||||
<button
|
||||
class="flex items-center gap-2 px-3 py-1.5 rounded-lg text-sm text-[var(--text-primary)] @hover:bg-[var(--color-hover)] transition-colors whitespace-nowrap"
|
||||
@click="handleAddMessage('assistant'); close()">
|
||||
<span class="text-4 i-mynaui-sparkles"></span>
|
||||
Add as Assistant
|
||||
</button>
|
||||
</template>
|
||||
</Dropdown>
|
||||
</div>
|
||||
<button v-else aria-label="Send message" @click="handleSubmit"
|
||||
:disabled="((!inputValue.content.trim() && files.length === 0) && !loading) || isUploading || hasFailedUploads"
|
||||
:class="[
|
||||
'h-8 w-8 rounded-xl transition-all duration-200 flex items-center justify-center disabled:cursor-not-allowed disabled:bg-transparent',
|
||||
(inputValue.content.trim() || files.length > 0) && !loading && !isUploading && !hasFailedUploads
|
||||
? 'bg-[var(--color-accent)] text-[var(--color-accent-text)] @hover:bg-[var(--color-accent-hover)]'
|
||||
: 'text-[var(--text-dim)]',
|
||||
loading && 'bg-[var(--color-hover)] @hover:bg-[var(--color-active)]',
|
||||
]">
|
||||
<span v-if="loading" class="text-6.5 i-mynaui-stop-solid"></span>
|
||||
<span v-else class="text-5 i-mynaui-send-solid"></span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="selectedModel?.capabilities.includes('tools')"
|
||||
class="sm:hidden relative z-0 mx-auto w-[calc(100%-4px)] transition-[height] duration-250 ease-[cubic-bezier(0.4,_0,_0.2,_1)]"
|
||||
:class="isDrawerOpen ? 'h-[44px]' : 'h-0'">
|
||||
<div class="absolute -top-4 left-0 right-0 pt-5 px-3 pb-1.5 rounded-b-2xl border-x border-b border-[var(--color-border)] bg-[var(--bg-surface)] flex items-center gap-1.5 transition-[transform,opacity] duration-250 ease-[cubic-bezier(0.4,_0,_0.2,_1)]"
|
||||
:class="isDrawerOpen ? 'translate-y-0 opacity-100' : '-translate-y-[44px] opacity-0 pointer-events-none'">
|
||||
<SearchSelector :enabled="searchConfig.enabled"
|
||||
@update:enabled="(v: boolean) => { searchConfig.enabled = v; saveSearchConfig(); }"></SearchSelector>
|
||||
<ToolSelector :python="toolsConfig.python"
|
||||
@update:python="(v: boolean) => { toolsConfig.python = v; saveToolsConfig(); }"></ToolSelector>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
import type { MarkdownAstNode, MarkdownElementNode } from '~/utils/markdown';
|
||||
import { createMarkdownParser, getNodeAttributes, getNodeChildren, getNodeTag, splitParagraphBreaks, textContent, toVueAttributes } from '~/utils/markdown';
|
||||
import { createTextVNode, h, ref, watch } from 'vue';
|
||||
import type { MarkdownAstNode } from '~/utils/markdown';
|
||||
import { agentParser, userParser, getNodeAttributes, getNodeChildren, getNodeTag, splitParagraphBreaks, textContent, toVueAttributes } from '~/utils/markdown';
|
||||
import { createTextVNode, h, shallowRef, watch } from 'vue';
|
||||
import type { SearchSource } from '~/utils/tool-rendering';
|
||||
import SourceCitation from './SourceCitation.vue';
|
||||
import MarkdownMath from './Math.vue';
|
||||
import MarkdownShikiHighlight from './ShikiHighlight.vue';
|
||||
|
||||
@@ -9,15 +11,19 @@ const props = defineProps<{
|
||||
content: string;
|
||||
finished: boolean;
|
||||
id: string;
|
||||
sources?: ReadonlyMap<string, SearchSource>;
|
||||
citations?: boolean;
|
||||
}>();
|
||||
|
||||
const parser = createMarkdownParser();
|
||||
const parser = props.citations ? agentParser : userParser;
|
||||
const parse = async (content: string, finished: boolean) => {
|
||||
const tree = await parser(content, { streaming: !finished });
|
||||
// Copy-on-write: br-free trees return by reference with no allocation.
|
||||
return splitParagraphBreaks(tree);
|
||||
};
|
||||
|
||||
const parsed = ref(await parse(props.content, props.finished));
|
||||
// Parsed trees are replaced, never mutated. Avoid proxying every AST node.
|
||||
const parsed = shallowRef(await parse(props.content, props.finished));
|
||||
let parseVersion = 0;
|
||||
|
||||
watch(
|
||||
@@ -46,6 +52,11 @@ const renderNode = (node: MarkdownAstNode, path: string): any => {
|
||||
|
||||
const tag = getNodeTag(node);
|
||||
const attributes = getNodeAttributes(node);
|
||||
if (tag === 'source-cite') {
|
||||
const ids = typeof attributes.ids === "string" ? attributes.ids.split(",") : [];
|
||||
return h(SourceCitation, { key: path, ids, sources: props.sources });
|
||||
}
|
||||
|
||||
if (tag === 'pre') {
|
||||
const language = typeof attributes.language === 'string' ? attributes.language : 'text';
|
||||
return h(MarkdownShikiHighlight, {
|
||||
@@ -79,9 +90,7 @@ const render = () => {
|
||||
.map((node, index) => renderNode(node, `${props.id}.${index}`))
|
||||
.filter((child) => child !== null);
|
||||
|
||||
return h('div', { class: 'prose-wrapper' }, [
|
||||
h('article', { class: 'markdown-body' }, children),
|
||||
]);
|
||||
return h('article', { class: 'prose-wrapper markdown-body' }, children);
|
||||
};
|
||||
</script>
|
||||
|
||||
|
||||
@@ -3,8 +3,6 @@ import { type Grammar } from 'shiki';
|
||||
import { hashSync } from '~/utils/hash';
|
||||
const props = defineProps<{ code: string; language: string }>();
|
||||
|
||||
const start = Date.now();
|
||||
|
||||
const MAX_LENGTH = 15000;
|
||||
|
||||
const renderId = `${useId()}-${hashSync(props.code + props.language)}`;
|
||||
@@ -76,8 +74,6 @@ onUnmounted(() => {
|
||||
if (copyTimeout) clearTimeout(copyTimeout);
|
||||
clear();
|
||||
});
|
||||
|
||||
console.log("shiki codeblock rendered in", Date.now() - start);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
<script setup lang="ts">
|
||||
import type { SearchSource } from "~/utils/tool-rendering";
|
||||
import { autoUpdate, flip, offset, shift, useFloating } from "@floating-ui/vue";
|
||||
import { computed, onBeforeUnmount, ref, useId } from "vue";
|
||||
import { getFaviconUrl } from "~/utils/tool-rendering";
|
||||
|
||||
const props = defineProps<{
|
||||
ids: string[];
|
||||
sources?: ReadonlyMap<string, SearchSource>;
|
||||
}>();
|
||||
|
||||
const entries = computed(() => [...new Set(props.ids)].map(id => ({ id, source: props.sources?.get(id) })));
|
||||
const firstSource = computed(() => entries.value.find(entry => entry.source)?.source);
|
||||
const label = computed(() => {
|
||||
const first = firstSource.value?.hostname ?? "Source unavailable";
|
||||
return entries.value.length > 1 ? `${first} +${entries.value.length - 1}` : first;
|
||||
});
|
||||
const popupId = useId();
|
||||
const trigger = ref<HTMLElement | null>(null);
|
||||
const preview = ref<HTMLElement | null>(null);
|
||||
const open = ref(false);
|
||||
const failedFavicons = ref(new Set<string>());
|
||||
const { floatingStyles, placement } = useFloating(trigger, preview, {
|
||||
open,
|
||||
strategy: "fixed",
|
||||
placement: "top-start",
|
||||
middleware: [offset(8), flip(), shift({ padding: 12 })],
|
||||
whileElementsMounted: autoUpdate,
|
||||
transform: false,
|
||||
});
|
||||
|
||||
const transformOrigin = computed(() =>
|
||||
placement.value.startsWith("top")
|
||||
? "transform-origin-bottom-center"
|
||||
: "transform-origin-top-center"
|
||||
);
|
||||
|
||||
let closeTimer: ReturnType<typeof setTimeout> | undefined;
|
||||
let pointerInside = false;
|
||||
|
||||
const cancelClose = () => {
|
||||
clearTimeout(closeTimer);
|
||||
closeTimer = undefined;
|
||||
};
|
||||
|
||||
const showPreview = () => {
|
||||
cancelClose();
|
||||
open.value = true;
|
||||
};
|
||||
|
||||
const scheduleClose = () => {
|
||||
cancelClose();
|
||||
// Allow the pointer to cross the gap between the badge and the preview.
|
||||
closeTimer = setTimeout(() => {
|
||||
closeTimer = undefined;
|
||||
const focused = document.activeElement;
|
||||
if (!pointerInside && !trigger.value?.contains(focused) && !preview.value?.contains(focused)) {
|
||||
open.value = false;
|
||||
}
|
||||
}, 150);
|
||||
};
|
||||
|
||||
const onPointerEnter = (event: PointerEvent) => {
|
||||
if (event.pointerType === "touch") {
|
||||
return;
|
||||
}
|
||||
pointerInside = true;
|
||||
showPreview();
|
||||
};
|
||||
|
||||
const onPointerLeave = (event: PointerEvent) => {
|
||||
if (event.pointerType === "touch") {
|
||||
return;
|
||||
}
|
||||
pointerInside = false;
|
||||
scheduleClose();
|
||||
};
|
||||
|
||||
const dismissPreview = () => {
|
||||
cancelClose();
|
||||
if (preview.value?.contains(document.activeElement)) {
|
||||
trigger.value?.focus();
|
||||
}
|
||||
open.value = false;
|
||||
};
|
||||
|
||||
onBeforeUnmount(cancelClose);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<a ref="trigger" :href="firstSource?.url" target="_blank" rel="noopener noreferrer"
|
||||
:tabindex="firstSource ? undefined : 0" :aria-expanded="open" :aria-controls="open ? popupId : undefined"
|
||||
@pointerenter="onPointerEnter" @pointerleave="onPointerLeave" @focusin="showPreview" @focusout="scheduleClose"
|
||||
@keydown.esc.stop.prevent="dismissPreview"
|
||||
class="inline-flex items-center gap-1 max-w-64 mx-1 px-2 border border-[var(--color-border)] rounded-full bg-[var(--bg-container)] hover:bg-[var(--color-hover)] transition-colors text-[var(--text-secondary)] text-xs align-baseline cursor-pointer focus-visible:outline-solid focus-visible:outline-2 focus-visible:outline-[var(--text-secondary)] focus-visible:outline-offset-2 decoration-none">
|
||||
<img v-if="firstSource && !failedFavicons.has(firstSource.hostname)" :src="getFaviconUrl(firstSource.hostname)"
|
||||
alt="" loading="lazy" class="rounded-[4px] w-[0.9rem] h-[0.9rem] m-0"
|
||||
@error="failedFavicons.add(firstSource.hostname)">
|
||||
{{ label }}
|
||||
</a>
|
||||
<Transition enter-active-class="transition-[opacity,transform] duration-150 ease-[cubic-bezier(0.5,_1,_0.89,_1)]"
|
||||
enter-from-class="opacity-0 scale-95 translate-y-1" enter-to-class="opacity-100 scale-100 translate-y-0"
|
||||
leave-active-class="transition-[opacity,transform] duration-100 ease-[cubic-bezier(0.5,_1,_0.89,_1)]"
|
||||
leave-from-class="opacity-100 scale-100 translate-y-0" leave-to-class="opacity-0 scale-95 translate-y-1">
|
||||
<span v-if="open" :id="popupId" ref="preview" @pointerenter="onPointerEnter" @pointerleave="onPointerLeave"
|
||||
@focusin="showPreview" @focusout="scheduleClose" @keydown.esc.stop.prevent="dismissPreview"
|
||||
class="z-2 inset-auto m-0 p-[0.85rem] w-[min(22rem,calc(100vw_-_24px))] max-h-[min(24rem,70vh)] overflow-y-auto border border-[var(--color-border)] rounded-xl bg-[var(--bg-surface)] text-[var(--text-primary)] shadow-md text-sm leading-normal"
|
||||
:class="transformOrigin" :style="floatingStyles">
|
||||
<span v-for="(entry, index) in entries" :key="entry.id"
|
||||
class="flex flex-col gap-[0.4rem] [overflow-wrap:anywhere]"
|
||||
:class="{ 'mt-[0.8rem] pt-[0.8rem] border-t border-[var(--color-border)]': index > 0 }">
|
||||
<template v-if="entry.source">
|
||||
<span class="text-xs text-[var(--text-secondary)]">{{ entry.source.hostname }} · Search
|
||||
excerpt</span>
|
||||
<a :href="entry.source.url" target="_blank" rel="noopener noreferrer">{{ entry.source.title }}</a>
|
||||
<span v-if="entry.source.snippet" class="whitespace-pre-wrap text-[var(--text-secondary)]">{{
|
||||
entry.source.snippet }}</span>
|
||||
</template>
|
||||
<span v-else>Source unavailable ({{ entry.id }})</span>
|
||||
</span>
|
||||
</span>
|
||||
</Transition>
|
||||
</template>
|
||||
@@ -1,11 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
import type { MessagePart } from '~/composables/useChat';
|
||||
import ReasoningBody from './ReasoningBody.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
part: Readonly<MessagePart>;
|
||||
}>();
|
||||
|
||||
const reasoningOpen = ref(!props.part.finished);
|
||||
const bodyRef = ref<InstanceType<typeof ReasoningBody> | null>(null);
|
||||
|
||||
watch(
|
||||
() => props.part.finished,
|
||||
@@ -14,44 +16,14 @@ watch(
|
||||
},
|
||||
);
|
||||
|
||||
const containerRef: Ref<HTMLDivElement | null> = ref(null);
|
||||
const scrollState = ref('middle');
|
||||
|
||||
const { scrollToBottom } = useAutoScroll(containerRef);
|
||||
|
||||
const handleScroll = () => {
|
||||
if (!containerRef.value) return;
|
||||
|
||||
const container = containerRef.value;
|
||||
const scrollTop = container.scrollTop;
|
||||
const scrollHeight = container.scrollHeight;
|
||||
const clientHeight = container.clientHeight;
|
||||
|
||||
const topThreshold = 0.02 * clientHeight;
|
||||
|
||||
if (scrollHeight <= clientHeight) {
|
||||
// the container does not have enough content to scroll
|
||||
scrollState.value = '';
|
||||
return;
|
||||
}
|
||||
|
||||
if (scrollTop <= topThreshold) {
|
||||
scrollState.value = 'top';
|
||||
} else if (scrollTop + 100 >= scrollHeight - clientHeight) {
|
||||
scrollState.value = 'bottom';
|
||||
} else {
|
||||
scrollState.value = 'middle';
|
||||
}
|
||||
};
|
||||
|
||||
const toggleReasoning = async () => {
|
||||
if (!props.part.finished) return;
|
||||
|
||||
reasoningOpen.value = !reasoningOpen.value;
|
||||
if (!reasoningOpen.value) return;
|
||||
await nextTick();
|
||||
scrollToBottom('instant');
|
||||
handleScroll();
|
||||
bodyRef.value?.scrollToBottom('instant');
|
||||
bodyRef.value?.handleScroll();
|
||||
};
|
||||
|
||||
const formatDuration = (ms: number) => {
|
||||
@@ -91,11 +63,6 @@ const formatDuration = (ms: number) => {
|
||||
<span class="i-mynaui-chevron-down w-4 h-4 text-[var(--text-secondary)]"
|
||||
:class="reasoningOpen ? '' : '-rotate-90'"></span>
|
||||
</button>
|
||||
<div v-if="reasoningOpen" ref="containerRef" @scroll="handleScroll"
|
||||
:class="['reasoning-container max-h-[min(40vh,320px)] overflow-y-auto [scrollbar-width:thin] [scrollbar-color:#888_transparent] [scrollbar-gutter:stable]', scrollState]">
|
||||
<div class="p-2">
|
||||
<MarkdownRenderer :finished="part.finished" :id="part.id" :content="part.content!" />
|
||||
</div>
|
||||
</div>
|
||||
<ReasoningBody v-if="reasoningOpen" ref="bodyRef" :part="part" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
<script setup lang="ts">
|
||||
import type { MessagePart } from '~/composables/useChat';
|
||||
import { nextTick, onMounted, ref, watch, type Ref } from 'vue';
|
||||
|
||||
const props = defineProps<{
|
||||
part: Readonly<MessagePart>;
|
||||
}>();
|
||||
|
||||
const containerRef: Ref<HTMLDivElement | null> = ref(null);
|
||||
const scrollState = ref('');
|
||||
|
||||
const { scrollToBottom } = useAutoScroll(containerRef);
|
||||
|
||||
const handleScroll = () => {
|
||||
if (!containerRef.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
const container = containerRef.value;
|
||||
const scrollTop = container.scrollTop;
|
||||
const scrollHeight = container.scrollHeight;
|
||||
const clientHeight = container.clientHeight;
|
||||
|
||||
if (scrollHeight <= clientHeight) {
|
||||
scrollState.value = '';
|
||||
return;
|
||||
}
|
||||
|
||||
const threshold = Math.max(6, 0.02 * clientHeight);
|
||||
|
||||
if (scrollTop <= threshold) {
|
||||
scrollState.value = 'top';
|
||||
} else if (scrollTop >= scrollHeight - clientHeight - threshold) {
|
||||
scrollState.value = 'bottom';
|
||||
} else {
|
||||
scrollState.value = 'middle';
|
||||
}
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
nextTick(() => {
|
||||
handleScroll();
|
||||
});
|
||||
});
|
||||
|
||||
watch(
|
||||
() => props.part.content,
|
||||
() => {
|
||||
nextTick(() => {
|
||||
handleScroll();
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
defineExpose({ scrollToBottom, handleScroll });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div ref="containerRef" @scroll="handleScroll"
|
||||
:class="['reasoning-container max-h-[min(40vh,320px)] overflow-y-auto [scrollbar-width:thin] [scrollbar-color:#888_transparent] [scrollbar-gutter:stable]', scrollState]">
|
||||
<div class="p-2">
|
||||
<MarkdownRenderer :finished="props.part.finished" :id="props.part.id" :content="props.part.content!" />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -1,11 +0,0 @@
|
||||
<script lang="ts" setup>
|
||||
import type { MessagePart } from '~/composables/useChat';
|
||||
|
||||
const props = defineProps<{
|
||||
part: Readonly<MessagePart>;
|
||||
}>();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<MarkdownRenderer :finished="part.finished" :id="part.id" :content="part.content!" />
|
||||
</template>
|
||||
@@ -1,7 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
import { collectCitationSources } from '~/utils/citations';
|
||||
import type { SearchSource } from '~/utils/tool-rendering';
|
||||
import Error from './Error.vue';
|
||||
import Reasoning from './Reasoning.vue';
|
||||
import Text from './Text.vue';
|
||||
import Tool from './Tool/index.vue';
|
||||
import type { MessageEntity } from '~/composables/useChat';
|
||||
|
||||
@@ -9,6 +10,14 @@ const props = defineProps<{
|
||||
message: MessageEntity
|
||||
}>();
|
||||
|
||||
const EMPTY_SOURCES: ReadonlyMap<string, SearchSource> = new Map();
|
||||
|
||||
// Citation markers are rare; avoid JSON-parsing every tool output when none exist.
|
||||
const sources = computed(() => {
|
||||
const parts = props.message.parts ?? [];
|
||||
const hasCitations = parts.some(part => part.type === 'text' && part.content?.includes('[[cite:') === true);
|
||||
return hasCitations ? collectCitationSources(parts) : EMPTY_SOURCES;
|
||||
});
|
||||
const triggerRef = ref<HTMLElement | null>(null);
|
||||
|
||||
const { open, close, isOpen } = useTokenDropdown();
|
||||
@@ -25,14 +34,17 @@ const toggleTokenDropdown = () => {
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col w-full gap-2">
|
||||
<div v-for="part in message.parts?.filter(p => p.content?.trim() !== '' || p.toolCall)" :key="part.id">
|
||||
<Reasoning v-if="part.type === 'reasoning'" :part="part" />
|
||||
<Text v-else-if="part.type === 'text'" :part="part" />
|
||||
<Tool v-else-if="part.type === 'tool-call'" :tool-call="part.toolCall!" :part="part"></Tool>
|
||||
<div v-else>
|
||||
Unhandled part type: {{ part.type }} {{ part }}
|
||||
</div>
|
||||
</div>
|
||||
<template v-for="part in message.parts" :key="part.id">
|
||||
<template v-if="part.content?.trim() !== '' || part.toolCall">
|
||||
<Reasoning v-if="part.type === 'reasoning'" :part="part"></Reasoning>
|
||||
<MarkdownRenderer v-else-if="part.type === 'text'" :finished="part.finished" :id="part.id"
|
||||
:content="part.content!" :sources="sources" :citations="true"></MarkdownRenderer>
|
||||
<Tool v-else-if="part.type === 'tool-call'" :tool-call="part.toolCall!" :part="part"></Tool>
|
||||
<div v-else>
|
||||
Unhandled part type: {{ part.type }} {{ part }}
|
||||
</div>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
<span class="flex items-center gap-1"
|
||||
v-if="message.generation?.status === 'pending' && (message.parts || []).length === 0">
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import type { Message } from '~/composables/useChat';
|
||||
import { getActiveMessage, getCurrentChildIndex, getMessageCount, getNextActiveChildId } from '~~/utils/message';
|
||||
|
||||
const { openDialog } = useDialog();
|
||||
|
||||
@@ -35,7 +36,9 @@ watch(() => message.activeChildId, async (newValue) => {
|
||||
});
|
||||
|
||||
watch(() => message.children.length, (newCount, oldCount) => {
|
||||
if (newCount === oldCount) return;
|
||||
if (newCount === oldCount) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (newCount === 0) {
|
||||
emit('patch', { activeChildId: null });
|
||||
@@ -56,19 +59,17 @@ watch(() => message.children.length, (newCount, oldCount) => {
|
||||
}
|
||||
});
|
||||
|
||||
const activeMessage = computed(() => {
|
||||
if (message.activeChildId && message.children.length > 0) {
|
||||
const child = message.children.find(c => c?.id === message.activeChildId);
|
||||
if (child) return child;
|
||||
watch(() => message.deleted, (isDeleted) => {
|
||||
if (isDeleted && message.children.length > 0) {
|
||||
const activeChild = message.children.find(c => c?.id === message.activeChildId);
|
||||
if (!activeChild) {
|
||||
emit('patch', { activeChildId: message.children[0]?.id ?? null });
|
||||
}
|
||||
}
|
||||
|
||||
if (message.deleted === true && message.children.length > 0) {
|
||||
return message.children[0];
|
||||
}
|
||||
|
||||
return message;
|
||||
});
|
||||
|
||||
const activeMessage = computed(() => getActiveMessage(message));
|
||||
|
||||
const copied = ref(false);
|
||||
const copyMessage = async () => {
|
||||
if (activeMessage.value!.role === 'user') {
|
||||
@@ -135,91 +136,118 @@ const deleteMessage = () => {
|
||||
emit('delete');
|
||||
};
|
||||
|
||||
const messageCount = computed(() => {
|
||||
if (message.deleted === true) {
|
||||
return message.children.length;
|
||||
}
|
||||
const messageCount = computed(() => getMessageCount(message));
|
||||
|
||||
return message.children.length + 1;
|
||||
});
|
||||
|
||||
const currentChildIndex = computed(() => {
|
||||
if (!message.activeChildId) return 0;
|
||||
const idx = message.children.findIndex(c => c?.id === message.activeChildId);
|
||||
return idx >= 0 ? idx + 1 : 0;
|
||||
});
|
||||
const currentChildIndex = computed(() => getCurrentChildIndex(message));
|
||||
|
||||
const navigateChild = (direction: -1 | 1) => {
|
||||
const allItems = message.deleted === true
|
||||
? message.children
|
||||
: [null, ...message.children];
|
||||
const nextActiveChildId = getNextActiveChildId(message, direction);
|
||||
emit('patch', { activeChildId: nextActiveChildId });
|
||||
};
|
||||
|
||||
const currentIdx = allItems.findIndex(item =>
|
||||
!item ? !message.activeChildId : item.id === message.activeChildId
|
||||
);
|
||||
const { show: showTooltip, hide: hideTooltip } = useTooltip();
|
||||
|
||||
const newIdx = Math.max(0, Math.min(allItems.length - 1, currentIdx + direction));
|
||||
const newItem = allItems[newIdx];
|
||||
let hasCursor: boolean | null = null;
|
||||
const checkHasCursor = () => {
|
||||
if (hasCursor === null && typeof window !== 'undefined') {
|
||||
hasCursor = window.matchMedia('(hover: hover) and (pointer: fine)').matches;
|
||||
}
|
||||
return hasCursor ?? false;
|
||||
};
|
||||
|
||||
emit('patch', { activeChildId: newItem?.id ?? null });
|
||||
const handleTooltipHover = (e: MouseEvent) => {
|
||||
if (!checkHasCursor()) {
|
||||
return;
|
||||
}
|
||||
const target = (e.target as HTMLElement).closest('[data-hotkey], [data-tooltip]') as HTMLElement | null;
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
const hotkey = target.dataset.hotkey ? target.dataset.hotkey.split(',') : undefined;
|
||||
const text = target.dataset.tooltip || undefined;
|
||||
showTooltip(target, hotkey, text);
|
||||
};
|
||||
|
||||
const handleTooltipLeave = () => {
|
||||
hideTooltip();
|
||||
};
|
||||
|
||||
const handleAction = (e: MouseEvent) => {
|
||||
const trigger = (e.target as HTMLElement).closest('[data-action]') as HTMLElement | null;
|
||||
if (!trigger) {
|
||||
return;
|
||||
}
|
||||
switch (trigger.dataset.action) {
|
||||
case 'prev-child':
|
||||
navigateChild(-1);
|
||||
break;
|
||||
case 'next-child':
|
||||
navigateChild(1);
|
||||
break;
|
||||
case 'regenerate':
|
||||
regenerateMessage();
|
||||
break;
|
||||
case 'edit':
|
||||
handleEdit();
|
||||
break;
|
||||
case 'copy':
|
||||
copyMessage();
|
||||
break;
|
||||
case 'fork':
|
||||
forkMessage();
|
||||
break;
|
||||
case 'delete':
|
||||
deleteMessage();
|
||||
break;
|
||||
}
|
||||
};
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="activeMessage" class="max-w-full mb-4 group flex flex-col">
|
||||
<div :class="[message.role === 'user' ? 'pl-9 flex justify-end' : '']">
|
||||
<MessageUser v-if="message.role === 'user'" :message="activeMessage!" />
|
||||
<MessageAgent v-else :message="activeMessage" />
|
||||
</div>
|
||||
<div class="flex justify-between items-center">
|
||||
<div>
|
||||
<div v-if="messageCount > 1" class="flex gap-1">
|
||||
<Tooltip :inert="currentChildIndex === 0" :hotkey="['alt', '[']">
|
||||
<button @click="navigateChild(-1)"
|
||||
class="@hover:bg-[var(--color-hover)] rounded transition duration-150 ease-[cubic-bezier(0.5,_1,_0.89,_1)]">
|
||||
<span class="i-mynaui-chevron-left w-4 h-4 text-[var(--text-secondary)]"
|
||||
:class="currentChildIndex === 0 ? 'opacity-0' : ''"></span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
<span class="text-xs text-[var(--text-secondary)]">
|
||||
{{ currentChildIndex + 1 }} / {{ messageCount }}
|
||||
</span>
|
||||
<Tooltip :inert="currentChildIndex + 1 === messageCount" :hotkey="['alt', ']']">
|
||||
<button @click="navigateChild(1)"
|
||||
class="@hover:bg-[var(--color-hover)] rounded transition duration-150 ease-[cubic-bezier(0.5,_1,_0.89,_1)]">
|
||||
<span class="i-mynaui-chevron-right w-4 h-4 text-[var(--text-secondary)]"
|
||||
:class="currentChildIndex + 1 === messageCount ? 'opacity-0' : ''"></span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<MessageUser v-if="message.role === 'user'" class="pl-9 self-end" :message="activeMessage!"></MessageUser>
|
||||
<MessageAgent v-else :message="activeMessage"></MessageAgent>
|
||||
<div class="flex justify-between items-center" @click="handleAction">
|
||||
<div v-if="messageCount > 1" class="flex gap-1"
|
||||
@mouseover="handleTooltipHover" @mouseout="handleTooltipLeave">
|
||||
<button data-action="prev-child" :data-hotkey="currentChildIndex > 0 ? 'alt,[' : undefined"
|
||||
class="@hover:bg-[var(--color-hover)] rounded transition duration-150 ease-[cubic-bezier(0.5,_1,_0.89,_1)]">
|
||||
<span class="i-mynaui-chevron-left w-4 h-4 text-[var(--text-secondary)] pointer-events-none"
|
||||
:class="currentChildIndex === 0 ? 'opacity-0' : ''"></span>
|
||||
</button>
|
||||
<span class="text-xs text-[var(--text-secondary)]">
|
||||
{{ currentChildIndex + 1 }} / {{ messageCount }}
|
||||
</span>
|
||||
<button data-action="next-child" :data-hotkey="currentChildIndex + 1 < messageCount ? 'alt,]' : undefined"
|
||||
class="@hover:bg-[var(--color-hover)] rounded transition duration-150 ease-[cubic-bezier(0.5,_1,_0.89,_1)]">
|
||||
<span class="i-mynaui-chevron-right w-4 h-4 text-[var(--text-secondary)] pointer-events-none"
|
||||
:class="currentChildIndex + 1 === messageCount ? 'opacity-0' : ''"></span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-show="activeMessage.generation?.status !== 'pending'"
|
||||
class="self-end mt-1 w-fit bg-[var(--bg-container)] text-[var(--text-secondary)] gap-px flex items-center rounded-md overflow-hidden opacity-0 group-hover:opacity-100 transition-opacity duration-200 ease-[cubic-bezier(0.5,_1,_0.89,_1)]">
|
||||
<Tooltip :hotkey="['ctrl', 'shift', 'enter']">
|
||||
<button @click="regenerateMessage"
|
||||
class="flex justify-center items-center w-7 h-6 @hover:bg-[var(--color-hover)]">
|
||||
<span class="i-mynaui-refresh text-4.5"></span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
<button v-if="message.role === 'user'" @click="handleEdit"
|
||||
@mouseover="handleTooltipHover" @mouseout="handleTooltipLeave"
|
||||
class="ml-auto self-end mt-1 w-fit bg-[var(--bg-container)] text-[var(--text-secondary)] gap-px flex items-center rounded-md overflow-hidden opacity-0 group-hover:opacity-100 transition-opacity duration-200 ease-[cubic-bezier(0.5,_1,_0.89,_1)]">
|
||||
<button data-action="regenerate" data-hotkey="ctrl,shift,enter"
|
||||
class="flex justify-center items-center w-7 h-6 @hover:bg-[var(--color-hover)]">
|
||||
<span class="i-mynaui-pencil text-4.5"></span>
|
||||
<span class="i-mynaui-refresh text-4.5 pointer-events-none"></span>
|
||||
</button>
|
||||
<button @click="copyMessage" :class="{ 'text-emerald-500': copied }"
|
||||
<button v-if="message.role === 'user'" data-action="edit"
|
||||
class="flex justify-center items-center w-7 h-6 @hover:bg-[var(--color-hover)]">
|
||||
<span :class="copied ? 'i-mynaui-check text-emerald-500' : 'i-mynaui-copy text-4.5'"></span>
|
||||
<span class="i-mynaui-pencil text-4.5 pointer-events-none"></span>
|
||||
</button>
|
||||
<button @click="forkMessage"
|
||||
<button data-action="copy" :class="{ 'text-emerald-500': copied }"
|
||||
class="flex justify-center items-center w-7 h-6 @hover:bg-[var(--color-hover)]">
|
||||
<span class="i-mynaui-git-branch text-4.5"></span>
|
||||
<span :class="copied ? 'i-mynaui-check text-emerald-500' : 'i-mynaui-copy text-4.5'" class="pointer-events-none"></span>
|
||||
</button>
|
||||
<button data-action="fork"
|
||||
class="flex justify-center items-center w-7 h-6 @hover:bg-[var(--color-hover)]">
|
||||
<span class="i-mynaui-git-branch text-4.5 pointer-events-none"></span>
|
||||
</button>
|
||||
<button data-action="delete" data-hotkey="ctrl,shift,backspace"
|
||||
class="flex justify-center items-center w-7 h-6 text-red-500 @hover:bg-[var(--color-hover)]">
|
||||
<span class="i-mynaui-trash text-5 pointer-events-none"></span>
|
||||
</button>
|
||||
<Tooltip :hotkey="['ctrl', 'shift', 'backspace']">
|
||||
<button @click="deleteMessage"
|
||||
class="flex justify-center items-center w-7 h-6 text-red-500 @hover:bg-[var(--color-hover)]">
|
||||
<span class="i-mynaui-trash text-5"></span>
|
||||
</button>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -127,10 +127,12 @@ const autoRenameTopic = async (topicId: string) => {
|
||||
}
|
||||
|
||||
const cancelAutoRename = async (topicId: string) => {
|
||||
// TODO: make this more optimistic
|
||||
await $fetch(`/api/topic/${topicId}/auto-rename/cancel`, {
|
||||
method: 'POST',
|
||||
const result = await $fetch(`/api/topic/${topicId}/auto-rename/cancel`, {
|
||||
method: "POST",
|
||||
});
|
||||
if (result.ok) {
|
||||
patchTopicLocally(topicId, { renaming: false });
|
||||
}
|
||||
}
|
||||
|
||||
const renameTopicId = ref<string | null>(null);
|
||||
@@ -256,12 +258,13 @@ onMounted(() => {
|
||||
v-model="newTopicName" @keydown.enter="saveRename" @keydown.escape="cancelRename"
|
||||
@blur="saveRename"
|
||||
class="flex-1 bg-transparent border-none outline-none md:text-sm font-medium text-[var(--text-primary)] px-0 min-w-0" />
|
||||
<div v-else-if="topic.renaming" class="flex w-full">
|
||||
<span class="i-svg-spinners-3-dots-fade text-7 md:text-6"></span>
|
||||
<div v-else class="flex items-center gap-2 min-w-0">
|
||||
<span class="md:text-sm font-medium overflow-hidden text-ellipsis whitespace-nowrap">
|
||||
{{ topic.name }}
|
||||
</span>
|
||||
<span v-if="topic.renaming" aria-label="Renaming"
|
||||
class="i-svg-spinners-3-dots-fade shrink-0 text-4"></span>
|
||||
</div>
|
||||
<span v-else class="md:text-sm font-medium overflow-hidden text-ellipsis whitespace-nowrap">
|
||||
{{ topic.name }}
|
||||
</span>
|
||||
|
||||
<div data-action="toggle-dropdown"
|
||||
class="text-[var(--text-secondary)] shrink-0 w-0 max-w-0 opacity-0 overflow-hidden p-1 max-md:w-auto max-md:max-w-none max-md:opacity-100 flex items-center justify-center rounded-md @hover:bg-[var(--color-hover)] focus-visible:bg-[var(--color-hover)]"
|
||||
|
||||
@@ -7,14 +7,16 @@ const props = defineProps<{
|
||||
const { show, hide } = useTooltip();
|
||||
const triggerRef = ref<HTMLElement | null>(null);
|
||||
|
||||
const hasCursor = ref(false);
|
||||
|
||||
onMounted(() => {
|
||||
hasCursor.value = window.matchMedia('(hover: hover) and (pointer: fine)').matches;
|
||||
});
|
||||
let hasCursor: boolean | null = null;
|
||||
const checkHasCursor = () => {
|
||||
if (hasCursor === null && typeof window !== 'undefined') {
|
||||
hasCursor = window.matchMedia('(hover: hover) and (pointer: fine)').matches;
|
||||
}
|
||||
return hasCursor ?? false;
|
||||
};
|
||||
|
||||
const onMouseEnter = () => {
|
||||
if (triggerRef.value && hasCursor.value) {
|
||||
if (triggerRef.value && checkHasCursor()) {
|
||||
show(triggerRef.value, props.hotkey, props.text);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
import type { BaseMessage } from "~/composables/useChat";
|
||||
import { nanoid } from "nanoid";
|
||||
import { provisionalTopicTitle } from "~~/utils/topic-title";
|
||||
import { attempt } from "~~/types/result";
|
||||
import * as schema from '~~/drizzle/schema';
|
||||
|
||||
@@ -153,11 +155,11 @@ export const useAgents = async () => {
|
||||
|
||||
// TODO: since topics are contained within each agent struct, all topic
|
||||
// actions must be done through the agents composable
|
||||
const createTopic = async (agentId: string) => {
|
||||
const createTopic = async (agentId: string, message?: BaseMessage) => {
|
||||
const topicId = nanoid();
|
||||
const topic = {
|
||||
id: topicId,
|
||||
name: 'New Topic',
|
||||
name: provisionalTopicTitle(message),
|
||||
agentId,
|
||||
};
|
||||
|
||||
@@ -214,6 +216,9 @@ export const useAgents = async () => {
|
||||
agentId: agent.id,
|
||||
userId: agent.userId,
|
||||
renaming: false,
|
||||
renameAttemptId: null,
|
||||
renameExpiresAt: null,
|
||||
titleSource: "manual",
|
||||
createdAt: new Date(),
|
||||
};
|
||||
agents.value = agents.value.map(a =>
|
||||
|
||||
@@ -15,6 +15,7 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
||||
let lastScrollTop = 0;
|
||||
let mutationRaf: number | null = null;
|
||||
let anchorRaf: number | null = null;
|
||||
let anchorDebounceTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
let observer: MutationObserver | null = null;
|
||||
let resizeObserver: ResizeObserver | null = null;
|
||||
let lastWidth = 0;
|
||||
@@ -26,15 +27,25 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
||||
const setUnhooked = (value: boolean) => {
|
||||
unhooked.value = value;
|
||||
shouldAutoScroll.value = !value;
|
||||
if (!value) anchor = null;
|
||||
};
|
||||
|
||||
const scrollToBottom = (behavior: ScrollBehavior = 'instant') => {
|
||||
const el = elementRef.value;
|
||||
if (!el) return;
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
|
||||
const bottom = Math.max(0, el.scrollHeight - el.clientHeight);
|
||||
if (Math.abs(el.scrollTop - bottom) < 0.5) {
|
||||
setUnhooked(false);
|
||||
lastScrollTop = el.scrollTop;
|
||||
return;
|
||||
}
|
||||
|
||||
isProgrammatic = true;
|
||||
el.scrollTo({
|
||||
top: el.scrollHeight,
|
||||
top: bottom,
|
||||
behavior,
|
||||
});
|
||||
|
||||
@@ -48,13 +59,19 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
||||
};
|
||||
|
||||
const captureAnchor = (el: HTMLElement) => {
|
||||
if (!unhooked.value) {
|
||||
anchor = null;
|
||||
return;
|
||||
}
|
||||
const rect = el.getBoundingClientRect();
|
||||
const x = rect.left + rect.width / 2;
|
||||
const offsets = [4, 24, 48, 80, 120];
|
||||
|
||||
for (const y of offsets) {
|
||||
const target = document.elementFromPoint(x, rect.top + y);
|
||||
if (!target || target === el || !el.contains(target)) continue;
|
||||
if (!target || target === el || !el.contains(target)) {
|
||||
continue;
|
||||
}
|
||||
anchor = {
|
||||
element: target,
|
||||
offsetFromTop: target.getBoundingClientRect().top - rect.top,
|
||||
@@ -65,8 +82,8 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
||||
anchor = null;
|
||||
};
|
||||
|
||||
const scheduleAnchorCapture = () => {
|
||||
if (anchorRaf !== null) return;
|
||||
const requestAnchorCapture = () => {
|
||||
if (!unhooked.value || anchorRaf !== null) return;
|
||||
anchorRaf = requestAnimationFrame(() => {
|
||||
anchorRaf = null;
|
||||
const el = elementRef.value;
|
||||
@@ -74,13 +91,38 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
||||
});
|
||||
};
|
||||
|
||||
const scheduleAnchorCapture = () => {
|
||||
const el = elementRef.value;
|
||||
// Native scrollend is the primary path; debounce is only a fallback.
|
||||
if (!el || 'onscrollend' in el || !unhooked.value) return;
|
||||
if (anchorDebounceTimeout !== null) {
|
||||
clearTimeout(anchorDebounceTimeout);
|
||||
}
|
||||
anchorDebounceTimeout = setTimeout(() => {
|
||||
anchorDebounceTimeout = null;
|
||||
requestAnchorCapture();
|
||||
}, 150);
|
||||
};
|
||||
|
||||
const handleScrollEnd = () => {
|
||||
if (anchorDebounceTimeout !== null) {
|
||||
clearTimeout(anchorDebounceTimeout);
|
||||
anchorDebounceTimeout = null;
|
||||
}
|
||||
requestAnchorCapture();
|
||||
};
|
||||
|
||||
const restoreAnchor = (el: HTMLElement) => {
|
||||
if (!anchor || !el.contains(anchor.element)) return;
|
||||
if (!anchor || !el.contains(anchor.element)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const top = el.getBoundingClientRect().top;
|
||||
const delta =
|
||||
anchor.element.getBoundingClientRect().top - top - anchor.offsetFromTop;
|
||||
if (Math.abs(delta) < 0.5) return;
|
||||
if (Math.abs(delta) < 0.5) {
|
||||
return;
|
||||
}
|
||||
|
||||
isProgrammatic = true;
|
||||
el.scrollTop += delta;
|
||||
@@ -99,37 +141,54 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
||||
|
||||
const handleScroll = () => {
|
||||
const el = elementRef.value;
|
||||
if (!el) return;
|
||||
if (!el) {
|
||||
return;
|
||||
}
|
||||
|
||||
const scrollingUp = el.scrollTop < lastScrollTop;
|
||||
lastScrollTop = el.scrollTop;
|
||||
|
||||
scheduleAnchorCapture();
|
||||
|
||||
if (isProgrammatic) {
|
||||
if (isAtBottom(el)) setUnhooked(false);
|
||||
if (isAtBottom(el)) {
|
||||
setUnhooked(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// Only re-hook when actually inside the bottom threshold.
|
||||
// Mid-page scroll (up or down) must never re-enable stick.
|
||||
// If the user is scrolling up, they are deliberately navigating away from the bottom.
|
||||
// Unhook immediately so we never fight the scroll or snap back down.
|
||||
if (scrollingUp) {
|
||||
setUnhooked(true);
|
||||
scheduleAnchorCapture();
|
||||
return;
|
||||
}
|
||||
|
||||
// Only re-hook when scrolling down into the bottom threshold.
|
||||
if (isAtBottom(el)) {
|
||||
setUnhooked(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (scrollingUp) {
|
||||
setUnhooked(true);
|
||||
}
|
||||
scheduleAnchorCapture();
|
||||
};
|
||||
|
||||
const followIfHooked = () => {
|
||||
if (unhooked.value) return;
|
||||
if (unhooked.value) {
|
||||
return;
|
||||
}
|
||||
scrollToBottom('instant');
|
||||
};
|
||||
|
||||
const handleMutation = () => {
|
||||
if (mutationRaf !== null) return;
|
||||
const handleMutation = (records: MutationRecord[]) => {
|
||||
if (unhooked.value || mutationRaf !== null) {
|
||||
return;
|
||||
}
|
||||
// The isolated sizing mirror changes on every keystroke, but cannot
|
||||
// change scroll height. Keep observing real composer content (files,
|
||||
// tool controls, etc.) as well as message content.
|
||||
if (records.every(record => {
|
||||
const target = record.target instanceof Element ? record.target : record.target.parentElement;
|
||||
return target?.closest('[data-chat-measurement]');
|
||||
})) return;
|
||||
mutationRaf = requestAnimationFrame(() => {
|
||||
mutationRaf = null;
|
||||
followIfHooked();
|
||||
@@ -144,6 +203,7 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
||||
|
||||
el.addEventListener('wheel', handleWheel, { passive: true });
|
||||
el.addEventListener('scroll', handleScroll, { passive: true });
|
||||
el.addEventListener('scrollend', handleScrollEnd, { passive: true });
|
||||
|
||||
observer = new MutationObserver(handleMutation);
|
||||
observer.observe(el, {
|
||||
@@ -154,7 +214,9 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
||||
|
||||
resizeObserver = new ResizeObserver(() => {
|
||||
const current = elementRef.value;
|
||||
if (!current) return;
|
||||
if (!current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const width = current.clientWidth;
|
||||
if (width === lastWidth) {
|
||||
@@ -172,13 +234,18 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!anchor) {
|
||||
captureAnchor(current);
|
||||
}
|
||||
restoreAnchor(current);
|
||||
});
|
||||
resizeObserver.observe(el);
|
||||
|
||||
// Content already taller than the viewport on mount — catch up once
|
||||
requestAnimationFrame(() => {
|
||||
if (!unhooked.value) scrollToBottom('instant');
|
||||
if (!unhooked.value) {
|
||||
scrollToBottom('instant');
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -186,6 +253,7 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
||||
if (el) {
|
||||
el.removeEventListener('wheel', handleWheel);
|
||||
el.removeEventListener('scroll', handleScroll);
|
||||
el.removeEventListener('scrollend', handleScrollEnd);
|
||||
}
|
||||
observer?.disconnect();
|
||||
observer = null;
|
||||
@@ -199,12 +267,18 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
||||
cancelAnimationFrame(anchorRaf);
|
||||
anchorRaf = null;
|
||||
}
|
||||
if (anchorDebounceTimeout !== null) {
|
||||
clearTimeout(anchorDebounceTimeout);
|
||||
anchorDebounceTimeout = null;
|
||||
}
|
||||
anchor = null;
|
||||
};
|
||||
|
||||
watch(elementRef, (newEl, oldEl) => {
|
||||
detach(oldEl ?? null);
|
||||
if (newEl) attach(newEl);
|
||||
if (newEl) {
|
||||
attach(newEl);
|
||||
}
|
||||
}, { immediate: true });
|
||||
|
||||
onUnmounted(() => {
|
||||
|
||||
+161
-52
@@ -1,7 +1,9 @@
|
||||
import { nanoid } from 'nanoid';
|
||||
import { toRaw } from 'vue';
|
||||
import * as schema from '~~/drizzle/schema';
|
||||
import { Err, Ok, type Result } from '~~/types/result';
|
||||
import { buildMessageTree } from '~~/utils/message';
|
||||
import { appendTextDelta, serializeTopicSnapshot } from '~~/utils/topic-sync';
|
||||
|
||||
export type BaseMessage = {
|
||||
content: string;
|
||||
@@ -38,7 +40,7 @@ export enum ChatErrorType {
|
||||
Unimplemented,
|
||||
}
|
||||
|
||||
type Event = { type: string; payload: any; timestamp: number };
|
||||
type Event = { type: string; payload: any; timestamp: number; replay?: boolean };
|
||||
|
||||
const TARGET_UPDATES_PER_SECOND = 24;
|
||||
|
||||
@@ -46,6 +48,10 @@ export const useChat = async (topicId: MaybeRef<string>, connect = true) => {
|
||||
let data = useState<Topic & { messages: Message[] } | undefined>('useChat:data', () => undefined);
|
||||
|
||||
let sse: EventSource | undefined;
|
||||
let disposed = false;
|
||||
let connectionAttempt = 0;
|
||||
let reconnectTimeout: ReturnType<typeof setTimeout> | undefined;
|
||||
const { promise: connectionReady, resolve: markConnected } = Promise.withResolvers<void>();
|
||||
|
||||
const textDeltaBuffer: Map<string, Map<string, {
|
||||
content: string;
|
||||
@@ -64,7 +70,7 @@ export const useChat = async (topicId: MaybeRef<string>, connect = true) => {
|
||||
for (const [partId, content] of parts) {
|
||||
const part = msg.parts?.find(p => p.id === partId);
|
||||
if (part) {
|
||||
part.content += content.content;
|
||||
part.content = content.content;
|
||||
part.lastUpdatedAt = new Date(content.lastUpdatedAt);
|
||||
}
|
||||
}
|
||||
@@ -93,6 +99,23 @@ export const useChat = async (topicId: MaybeRef<string>, connect = true) => {
|
||||
flushTimeout = setTimeout(flushTextDeltas, 1000 / TARGET_UPDATES_PER_SECOND);
|
||||
};
|
||||
|
||||
const resetTextDeltas = () => {
|
||||
if (flushTimeout !== undefined) clearTimeout(flushTimeout);
|
||||
flushTimeout = undefined;
|
||||
textDeltaBuffer.clear();
|
||||
flushCbs.clear();
|
||||
};
|
||||
|
||||
const scheduleReconnect = (forceSnapshot = false) => {
|
||||
sse?.close();
|
||||
sse = undefined;
|
||||
if (disposed || reconnectTimeout !== undefined) return;
|
||||
reconnectTimeout = setTimeout(() => {
|
||||
reconnectTimeout = undefined;
|
||||
void connectSSE(forceSnapshot);
|
||||
}, 1500);
|
||||
};
|
||||
|
||||
const processEvent = (event: Event) => {
|
||||
if (!data.value) return;
|
||||
|
||||
@@ -102,12 +125,17 @@ export const useChat = async (topicId: MaybeRef<string>, connect = true) => {
|
||||
case 'MESSAGE_CREATED': {
|
||||
// Push the new message if it doesn't exist (prevents duplicates from HTTP vs SSE)
|
||||
if (!data.value.messages.find(m => m.id === payload.id)) {
|
||||
data.value.messages.push({ ...payload, parts: [] });
|
||||
data.value.messages.push({ ...payload, parts: payload.parts ?? [], attachments: payload.attachments ?? [] });
|
||||
} else {
|
||||
// replace the existing data with the new data
|
||||
const index = data.value.messages.findIndex(m => m.id === payload.id);
|
||||
if (index !== -1) {
|
||||
data.value.messages[index] = { ...payload, parts: [] };
|
||||
if (index !== -1 && !event.replay) {
|
||||
const existing = data.value.messages[index]!;
|
||||
data.value.messages[index] = {
|
||||
...payload,
|
||||
parts: payload.parts ?? [],
|
||||
attachments: payload.attachments ?? existing.attachments ?? [],
|
||||
};
|
||||
}
|
||||
}
|
||||
break;
|
||||
@@ -130,7 +158,9 @@ export const useChat = async (topicId: MaybeRef<string>, connect = true) => {
|
||||
const msg = data.value.messages.find(m => m.id === payload.messageId);
|
||||
if (msg) {
|
||||
if (!msg.parts) msg.parts = [];
|
||||
msg.parts.push(payload.part);
|
||||
if (!msg.parts.some(part => part.id === payload.part.id)) {
|
||||
msg.parts.push(payload.part);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -138,18 +168,33 @@ export const useChat = async (topicId: MaybeRef<string>, connect = true) => {
|
||||
case 'text-delta': {
|
||||
const msg = data.value.messages.find(m => m.id === payload.messageId);
|
||||
if (!msg) break;
|
||||
const part = msg.parts?.find(part => part.id === payload.partId);
|
||||
if (!part || part.finished) break;
|
||||
|
||||
if (!textDeltaBuffer.has(payload.messageId)) {
|
||||
textDeltaBuffer.set(payload.messageId, new Map());
|
||||
}
|
||||
const messageBuffer = textDeltaBuffer.get(payload.messageId)!;
|
||||
const existing = messageBuffer.get(payload.partId)?.content || '';
|
||||
messageBuffer.set(payload.partId, { content: existing + payload.content, lastUpdatedAt: payload.lastUpdatedAt });
|
||||
const existing = messageBuffer.get(payload.partId)?.content ?? part.content ?? '';
|
||||
if (typeof payload.offset === 'number' && payload.offset > existing.length) {
|
||||
scheduleReconnect(true);
|
||||
break;
|
||||
}
|
||||
const content = appendTextDelta(existing, payload.content, payload.offset);
|
||||
if (content === existing) break;
|
||||
messageBuffer.set(payload.partId, { content, lastUpdatedAt: payload.lastUpdatedAt });
|
||||
|
||||
scheduleFlush();
|
||||
break;
|
||||
}
|
||||
|
||||
case 'text-delete': {
|
||||
const msg = data.value.messages.find(m => m.id === payload.messageId);
|
||||
if (msg?.parts) msg.parts = msg.parts.filter(part => part.id !== payload.partId);
|
||||
textDeltaBuffer.get(payload.messageId)?.delete(payload.partId);
|
||||
break;
|
||||
}
|
||||
|
||||
case 'text-end': {
|
||||
const msg = data.value.messages.find(m => m.id === payload.messageId);
|
||||
const part = msg?.parts?.find(p => p.id === payload.partId);
|
||||
@@ -175,7 +220,9 @@ export const useChat = async (topicId: MaybeRef<string>, connect = true) => {
|
||||
if (!part.createdAt) {
|
||||
part.createdAt = new Date().toISOString();
|
||||
}
|
||||
msg.parts.push(part);
|
||||
if (!msg.parts.some(existing => existing.id === part.id)) {
|
||||
msg.parts.push(part);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -229,55 +276,79 @@ export const useChat = async (topicId: MaybeRef<string>, connect = true) => {
|
||||
}
|
||||
}
|
||||
|
||||
const connectSSE = async () => {
|
||||
const { promise, resolve } = Promise.withResolvers<void>();
|
||||
|
||||
const connectSSE = async (forceSnapshot = false) => {
|
||||
if (disposed) return;
|
||||
const attempt = ++connectionAttempt;
|
||||
const id = unref(topicId);
|
||||
const lastUpdate = data.value?.messages.at(-1)?.updatedAt || '0';
|
||||
const msgCount = data.value?.messages.length || 0;
|
||||
|
||||
if (sse && sse.readyState !== EventSource.CLOSED) {
|
||||
if (!(new URL(sse.url).pathname.startsWith(`/api/topic/${id}`))) {
|
||||
sse.close();
|
||||
} else {
|
||||
return;
|
||||
sse?.close();
|
||||
if (flushTimeout !== undefined) {
|
||||
clearTimeout(flushTimeout);
|
||||
flushTextDeltas();
|
||||
}
|
||||
let offeredSnapshot: string | undefined;
|
||||
const query = new URLSearchParams();
|
||||
if (!forceSnapshot && data.value?.id === id && globalThis.crypto?.subtle) {
|
||||
try {
|
||||
offeredSnapshot = serializeTopicSnapshot(toRaw(data.value));
|
||||
const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(offeredSnapshot));
|
||||
query.set('snapshot', Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join(''));
|
||||
} catch {
|
||||
// Fingerprinting is an optimization; a full snapshot remains safe.
|
||||
offeredSnapshot = undefined;
|
||||
}
|
||||
}
|
||||
if (disposed || attempt !== connectionAttempt) return;
|
||||
|
||||
sse = new EventSource(`/api/topic/${id}?lastUpdate=${lastUpdate}&count=${msgCount}`);
|
||||
const source = new EventSource(`/api/topic/${id}?${query}`);
|
||||
sse = source;
|
||||
source.addEventListener('error', () => {
|
||||
if (sse === source) scheduleReconnect();
|
||||
});
|
||||
|
||||
sse.addEventListener("error", (e) => {
|
||||
console.error('sse error', e);
|
||||
setTimeout(connectSSE, 1500);
|
||||
})
|
||||
|
||||
sse.addEventListener("message", (e) => {
|
||||
source.addEventListener('message', (e) => {
|
||||
if (disposed || sse !== source) return;
|
||||
const raw = JSON.parse(e.data);
|
||||
const events: Event[] = Array.isArray(raw) ? raw : [raw];
|
||||
|
||||
for (const { type, payload, timestamp } of events) {
|
||||
for (const event of events) {
|
||||
const { type, payload } = event;
|
||||
if (!type || !payload) continue;
|
||||
|
||||
if (type === 'initial_state') {
|
||||
data.value = payload;
|
||||
resolve()
|
||||
if (type === 'synced') {
|
||||
// Optimistic edits can occur while the handshake is in flight.
|
||||
// Only retain the exact state that we offered to the server.
|
||||
if (offeredSnapshot !== serializeTopicSnapshot(toRaw(data.value))) {
|
||||
scheduleReconnect(true);
|
||||
return;
|
||||
}
|
||||
offeredSnapshot = undefined;
|
||||
markConnected();
|
||||
continue;
|
||||
}
|
||||
|
||||
processEvent({ type, payload, timestamp });
|
||||
if (type === 'initial_state') {
|
||||
resetTextDeltas();
|
||||
data.value = payload;
|
||||
offeredSnapshot = undefined;
|
||||
markConnected();
|
||||
continue;
|
||||
}
|
||||
|
||||
processEvent(event);
|
||||
}
|
||||
});
|
||||
|
||||
await promise;
|
||||
}
|
||||
await connectionReady;
|
||||
};
|
||||
|
||||
|
||||
if (connect) {
|
||||
onBeforeUnmount(() => {
|
||||
if (flushTimeout) {
|
||||
clearTimeout(flushTimeout);
|
||||
flushTextDeltas();
|
||||
}
|
||||
disposed = true;
|
||||
connectionAttempt++;
|
||||
if (reconnectTimeout !== undefined) clearTimeout(reconnectTimeout);
|
||||
resetTextDeltas();
|
||||
markConnected();
|
||||
if (sse) {
|
||||
console.log('[SSE] Closing connection');
|
||||
sse.close();
|
||||
@@ -525,38 +596,76 @@ export const useChat = async (topicId: MaybeRef<string>, connect = true) => {
|
||||
}
|
||||
|
||||
const deleteMessagesFocusedDescendant = async (messageId: string): Promise<Result<void, Error>> => {
|
||||
if (!data.value) return Err(new Error('No data'));
|
||||
if (!data.value) {
|
||||
return Err(new Error("No data"));
|
||||
}
|
||||
|
||||
const msg = data.value.messages.find(m => m.id === messageId);
|
||||
if (!msg) return Err(new Error('Message not found'));
|
||||
const msg = data.value.messages.find((m) => {
|
||||
return m.id === messageId;
|
||||
});
|
||||
if (!msg) {
|
||||
return Err(new Error("Message not found"));
|
||||
}
|
||||
|
||||
const previousMessages = data.value!.messages;
|
||||
const previousMessages = data.value.messages;
|
||||
|
||||
const res = await $fetch(`/api/messages/${messageId}`, {
|
||||
method: 'DELETE',
|
||||
method: "DELETE",
|
||||
onRequest() {
|
||||
if (!msg.activeChildId && (msg.parentMessageId === null || msg.parentMessageId === undefined)) {
|
||||
msg.deleted = true;
|
||||
if (!data.value) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parent = data.value!.messages.find(m => m.id === msg.parentMessageId);
|
||||
data.value!.messages = data.value!.messages.filter(m => m.id !== msg.id);
|
||||
if (parent?.deleted) {
|
||||
data.value!.messages = data.value!.messages.filter(m => m.id !== parent.id);
|
||||
if (msg.parentMessageId) {
|
||||
const parent = data.value.messages.find((m) => {
|
||||
return m.id === msg.parentMessageId;
|
||||
});
|
||||
data.value.messages = data.value.messages.filter((m) => {
|
||||
return m.id !== msg.id;
|
||||
});
|
||||
if (parent) {
|
||||
const remainingChildren = data.value.messages.filter((m) => {
|
||||
return m.parentMessageId === parent.id;
|
||||
});
|
||||
if (parent.deleted && remainingChildren.length === 0) {
|
||||
data.value.messages = data.value.messages.filter((m) => {
|
||||
return m.id !== parent.id;
|
||||
});
|
||||
} else if (parent.activeChildId === msg.id) {
|
||||
parent.activeChildId = remainingChildren.length > 0
|
||||
? (parent.deleted ? remainingChildren[0]!.id : remainingChildren[remainingChildren.length - 1]!.id)
|
||||
: null;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const children = data.value.messages.filter((m) => {
|
||||
return m.parentMessageId === msg.id;
|
||||
});
|
||||
if (children.length === 0) {
|
||||
data.value.messages = data.value.messages.filter((m) => {
|
||||
return m.id !== msg.id;
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
msg.deleted = true;
|
||||
msg.activeChildId = children[0]?.id ?? null;
|
||||
},
|
||||
onResponseError() {
|
||||
data.value!.messages = previousMessages;
|
||||
if (data.value) {
|
||||
data.value.messages = previousMessages;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
return Err(new Error('Failed to delete message'));
|
||||
return Err(new Error("Failed to delete message"));
|
||||
}
|
||||
|
||||
return Ok(undefined);
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
topic,
|
||||
|
||||
@@ -8,8 +8,6 @@ export const useTokenDropdown = () => {
|
||||
const triggerElement = useState<HTMLElement | null>('token-dropdown:trigger', () => null);
|
||||
|
||||
const open = (generation: Generation, trigger: HTMLElement) => {
|
||||
console.log("open", generation, trigger);
|
||||
|
||||
activeGeneration.value = generation;
|
||||
triggerElement.value = trigger;
|
||||
isOpen.value = true;
|
||||
|
||||
@@ -10,7 +10,7 @@ export const useTopic = () => {
|
||||
FailedToDecryptProviderApiKey,
|
||||
FailedToGenerate,
|
||||
}
|
||||
const autoRename = async (topicId: string): Promise<Result<string, AutoRenameError>> => {
|
||||
const autoRename = async (topicId: string): Promise<Result<void, AutoRenameError>> => {
|
||||
const { settings } = await useUserSettings();
|
||||
|
||||
if (!settings.value.systemAssistants.rename.enabled) {
|
||||
@@ -54,7 +54,7 @@ export const useTopic = () => {
|
||||
}
|
||||
}
|
||||
|
||||
const { agents } = await useAgents();
|
||||
const { patchTopicLocally, refresh } = await useAgents();
|
||||
|
||||
try {
|
||||
// @ts-ignore - excessive stack depth
|
||||
@@ -65,31 +65,20 @@ export const useTopic = () => {
|
||||
providerApiKey,
|
||||
}),
|
||||
onRequest() {
|
||||
const topics = agents.value.flatMap(agent => agent.topics);
|
||||
const topic = topics.find(topic => topic.id === topicId);
|
||||
if (topic) {
|
||||
agents.value = agents.value.map(agent => {
|
||||
return agent.id === topic.agentId ? { ...agent, topics: agent.topics.map(t => t.id === topic.id ? { ...topic, renaming: true } : t) } : agent;
|
||||
});
|
||||
}
|
||||
patchTopicLocally(topicId, { renaming: true });
|
||||
},
|
||||
onRequestError() {
|
||||
const topics = agents.value.flatMap(agent => agent.topics);
|
||||
const topic = topics.find(topic => topic.id === topicId);
|
||||
if (topic) {
|
||||
agents.value = agents.value.map(agent => {
|
||||
return agent.id === topic.agentId ? { ...agent, topics: agent.topics.map(t => t.id === topic.id ? { ...topic, renaming: false } : t) } : agent;
|
||||
});
|
||||
}
|
||||
},
|
||||
}) as { ok: true, renameId: string } | { ok: false, code: string };
|
||||
});
|
||||
if (!res.ok) {
|
||||
patchTopicLocally(topicId, { renaming: false });
|
||||
await refresh();
|
||||
console.error('Failed to auto-rename:', res.code);
|
||||
return Err(AutoRenameError.FailedToGenerate);
|
||||
}
|
||||
|
||||
return Ok(res.renameId);
|
||||
return Ok(undefined);
|
||||
} catch (error) {
|
||||
patchTopicLocally(topicId, { renaming: false });
|
||||
await refresh();
|
||||
console.error('Failed to auto-rename:', error);
|
||||
return Err(AutoRenameError.FailedToGenerate);
|
||||
}
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
export const useUserEvents = () => {
|
||||
const eventSource = ref<EventSource | null>(null);
|
||||
const agents = useState<AgentWithTopics[]>("agents_state", () => []);
|
||||
const isConnected = useState('userEvents:connected', () => false);
|
||||
const lastEventTimestamp = useState<number>('userEvents:lastTimestamp', () => 0);
|
||||
|
||||
const reconnectAttempts = ref(0);
|
||||
const connectionStartTime = ref<number>(0);
|
||||
const pendingReconnect = ref<NodeJS.Timeout | null>(null);
|
||||
let reconciliationTimer: ReturnType<typeof setInterval> | undefined;
|
||||
let reconciling = false;
|
||||
|
||||
const BASE_DELAY = 1000;
|
||||
const MAX_DELAY = 30000;
|
||||
@@ -50,7 +53,6 @@ export const useUserEvents = () => {
|
||||
cleanup();
|
||||
|
||||
connectionStartTime.value = Date.now();
|
||||
reconnectAttempts.value = 0;
|
||||
|
||||
const source = new EventSource('/api/events');
|
||||
eventSource.value = source;
|
||||
@@ -59,6 +61,7 @@ export const useUserEvents = () => {
|
||||
console.log('User events connected');
|
||||
isConnected.value = true;
|
||||
reconnectAttempts.value = 0;
|
||||
void reconcile();
|
||||
};
|
||||
|
||||
source.onerror = () => {
|
||||
@@ -164,20 +167,48 @@ export const useUserEvents = () => {
|
||||
};
|
||||
|
||||
const reconcile = async () => {
|
||||
console.log('Reconciling user state...');
|
||||
const { data } = await useFetch<AgentWithTopics[]>('/api/agents');
|
||||
if (data.value) {
|
||||
const { agents } = await useAgents();
|
||||
agents.value = data.value;
|
||||
if (reconciling) {
|
||||
return;
|
||||
}
|
||||
reconciling = true;
|
||||
try {
|
||||
agents.value = await $fetch<AgentWithTopics[]>("/api/agents");
|
||||
} catch (error) {
|
||||
console.error("Failed to reconcile topics:", error);
|
||||
} finally {
|
||||
reconciling = false;
|
||||
}
|
||||
};
|
||||
|
||||
const resume = () => {
|
||||
if (document.visibilityState !== "visible") {
|
||||
return;
|
||||
}
|
||||
if (!isConnected.value) {
|
||||
reconnectAttempts.value = 0;
|
||||
void connect();
|
||||
}
|
||||
void reconcile();
|
||||
};
|
||||
|
||||
onMounted(() => {
|
||||
connect();
|
||||
void connect();
|
||||
document.addEventListener("visibilitychange", resume);
|
||||
window.addEventListener("online", resume);
|
||||
window.addEventListener("pageshow", resume);
|
||||
reconciliationTimer = setInterval(() => {
|
||||
if (document.visibilityState === "visible" && agents.value.some(agent => agent.topics.some(topic => topic.renaming))) {
|
||||
void reconcile();
|
||||
}
|
||||
}, 15000);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
cleanup();
|
||||
clearInterval(reconciliationTimer);
|
||||
document.removeEventListener("visibilitychange", resume);
|
||||
window.removeEventListener("online", resume);
|
||||
window.removeEventListener("pageshow", resume);
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
@@ -18,8 +18,7 @@ useHead({
|
||||
});
|
||||
|
||||
if (import.meta.client) {
|
||||
const { connect } = useUserEvents();
|
||||
connect();
|
||||
useUserEvents();
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -28,7 +27,7 @@ if (import.meta.client) {
|
||||
<div class="p-2 w-full h-full max-w-full overflow-x-hidden">
|
||||
<main
|
||||
class="bg-[var(--bg-surface)] flex flex-col h-full w-full border border-solid border-[var(--color-border)] rounded-lg overflow-hidden">
|
||||
<div class="flex-1 overflow-y-auto">
|
||||
<div class="flex-1 min-h-0 flex flex-col">
|
||||
<slot />
|
||||
</div>
|
||||
</main>
|
||||
|
||||
@@ -66,7 +66,7 @@ const handleSubmit = async (message: BaseMessage, model: ModelWithProvider | nul
|
||||
updatedAt: new Date(),
|
||||
}
|
||||
|
||||
const topic = await createTopic(agent.value!.id);
|
||||
const topic = await createTopic(agent.value!.id, message);
|
||||
if (!topic) throw new Error('Failed to create topic');
|
||||
|
||||
const { sendMessage, startGeneration } = await useChat(topic.id, false);
|
||||
@@ -100,7 +100,7 @@ const handleAddMessage = async (message: BaseMessage, role: 'user' | 'assistant'
|
||||
return;
|
||||
}
|
||||
|
||||
const topic = await createTopic(agent.value!.id);
|
||||
const topic = await createTopic(agent.value!.id, message);
|
||||
if (!topic) throw new Error('Failed to create topic');
|
||||
|
||||
const { sendMessage } = await useChat(topic.id, false);
|
||||
@@ -118,7 +118,8 @@ const handleAddMessage = async (message: BaseMessage, role: 'user' | 'assistant'
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col h-full w-full max-w-full overflow-x-hidden">
|
||||
<div class="h-14 flex items-center justify-between px-4 border-b border-[var(--color-border)]">
|
||||
<div
|
||||
class="z-5 h-14 flex items-center justify-between px-4 border-b border-[var(--color-border)] bg-[var(--bg-surface)]">
|
||||
<div class="flex items-center gap-2 max-w-full">
|
||||
<button v-if="!sidebarOpen" @click="openSidebar"
|
||||
class="flex p-2 rounded-lg text-[var(--text-primary)] bg-transparent @hover:bg-[var(--color-hover)] transition-colors">
|
||||
@@ -131,7 +132,7 @@ const handleAddMessage = async (message: BaseMessage, role: 'user' | 'assistant'
|
||||
</div>
|
||||
|
||||
<div ref="chatPaneWrapper"
|
||||
class="chat-scroll-container justify-center w-full h-full [scrollbar-width:thin] [scrollbar-color:#888_transparent] overflow-y-scroll overflow-x-hidden flex justify-center pt-4">
|
||||
class="chat-scroll-container justify-center w-full flex-1 min-h-0 [scrollbar-width:thin] [scrollbar-color:#888_transparent] overflow-y-scroll overflow-x-hidden flex justify-center pt-4">
|
||||
<div class="chatPane max-w-4xl w-full min-h-full flex flex-col px-4">
|
||||
<div class="w-full px-px flex flex-col flex-grow gap-2"
|
||||
:class="pendingMessage === null ? 'justify-end pb-28' : 'pb-9'">
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
<script setup lang="ts">
|
||||
import { type BaseMessage, type Message, ChatErrorType } from '~/composables/useChat';
|
||||
import type { ModelWithProvider } from '~/composables/useModels';
|
||||
import { buildFocusedMessageTree } from '~~/utils/message';
|
||||
|
||||
const rootStart = Date.now();
|
||||
import { buildFocusedMessageTree, getActiveMessage, getNextActiveChildId } from '~~/utils/message';
|
||||
|
||||
const chatPaneWrapper = ref<HTMLElement | null>(null);
|
||||
const inputValue = ref<BaseMessage>({ content: '', fileIds: [] });
|
||||
@@ -81,11 +79,10 @@ const handleRegenerate = async (message: Message) => {
|
||||
return;
|
||||
}
|
||||
|
||||
let messageId: string;
|
||||
if (message.activeChildId && message.children.length > 0) {
|
||||
messageId = message.activeChildId;
|
||||
} else {
|
||||
messageId = message.id;
|
||||
const activeMsg = getActiveMessage(message);
|
||||
if (!activeMsg) {
|
||||
console.error('No active message');
|
||||
return;
|
||||
}
|
||||
|
||||
const model = allModels.value.find(m => m.id === agent.value!.defaultModelId);
|
||||
@@ -94,20 +91,26 @@ const handleRegenerate = async (message: Message) => {
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await regenerateMessage(messageId, buildFocusedMessageTree(topic.value!.messages), model);
|
||||
const res = await regenerateMessage(activeMsg.id, buildFocusedMessageTree(topic.value!.messages), model);
|
||||
if (!res.ok) {
|
||||
console.error('Failed to regenerate message:', ChatErrorType[res.error]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const flatMessages = computed(() => {
|
||||
const messages: Message[] = [];
|
||||
|
||||
for (const message of topic.value?.messages ?? []) {
|
||||
messages.push(message);
|
||||
if (!message.deleted) {
|
||||
messages.push(message);
|
||||
}
|
||||
if (message.children.length > 0) {
|
||||
messages.push(...message.children as Message[]);
|
||||
for (const child of message.children) {
|
||||
if (child && !child.deleted) {
|
||||
messages.push(child as Message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -115,11 +118,13 @@ const flatMessages = computed(() => {
|
||||
});
|
||||
|
||||
const handleFork = async (message: Message) => {
|
||||
const messageId = message.activeChildId && message.children.length > 0
|
||||
? message.activeChildId
|
||||
: message.id;
|
||||
const activeMsg = getActiveMessage(message);
|
||||
if (!activeMsg) {
|
||||
console.error('No active message');
|
||||
return;
|
||||
}
|
||||
|
||||
const newTopicId = await forkTopic(topicId.value, messageId);
|
||||
const newTopicId = await forkTopic(topicId.value, activeMsg.id);
|
||||
if (newTopicId) {
|
||||
await navigateTo(`/agent/${route.params.id}/topic/${newTopicId}`);
|
||||
} else {
|
||||
@@ -128,14 +133,12 @@ const handleFork = async (message: Message) => {
|
||||
};
|
||||
|
||||
const handleDelete = async (rootMessage: Message) => {
|
||||
let messageId: string;
|
||||
if (rootMessage.activeChildId && rootMessage.children.length > 0) {
|
||||
messageId = rootMessage.activeChildId;
|
||||
} else {
|
||||
messageId = rootMessage.id;
|
||||
const activeMsg = getActiveMessage(rootMessage);
|
||||
if (!activeMsg) {
|
||||
return;
|
||||
}
|
||||
|
||||
const result = await deleteMessagesFocusedDescendant(messageId);
|
||||
const result = await deleteMessagesFocusedDescendant(activeMsg.id);
|
||||
if (!result.ok) {
|
||||
console.error('Failed to delete message:', result.error);
|
||||
return;
|
||||
@@ -145,7 +148,7 @@ const handleDelete = async (rootMessage: Message) => {
|
||||
await navigateTo(`/agent/${route.params.id}`);
|
||||
deleteTopic(route.params.id as string, topicId.value);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const { scrollToBottom, isAtBottom } = useAutoScroll(chatPaneWrapper);
|
||||
|
||||
@@ -198,76 +201,39 @@ addShortcut(['ctrl', 'shift', 'c'], (event) => {
|
||||
handleCancel();
|
||||
})
|
||||
|
||||
addShortcut(['alt', '['], async (event) => {
|
||||
const navigateLastMessage = (direction: -1 | 1) => {
|
||||
const lastMessage = topic.value?.messages?.at(-1);
|
||||
if (!lastMessage || lastMessage.children.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const nextActiveChildId = getNextActiveChildId(lastMessage, direction);
|
||||
patchMessageLocally(lastMessage.id, { activeChildId: nextActiveChildId });
|
||||
};
|
||||
|
||||
addShortcut(['alt', '['], (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
navigateLastMessage(-1);
|
||||
});
|
||||
|
||||
const lastMessage = topic.value?.messages?.at(-1);
|
||||
if (lastMessage && lastMessage.children.length > 0) {
|
||||
const currentIdx = lastMessage.children.findIndex(c => c?.id === lastMessage.activeChildId);
|
||||
const prevIdx = Math.max(0, currentIdx);
|
||||
if (currentIdx > 0) {
|
||||
patchMessageLocally(lastMessage.id, { activeChildId: lastMessage.children[prevIdx - 1]!.id });
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
addShortcut(['alt', ']'], async (event) => {
|
||||
addShortcut(['ctrl', 'alt', 'arrowleft'], (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
navigateLastMessage(-1);
|
||||
});
|
||||
|
||||
const lastMessage = topic.value?.messages?.at(-1);
|
||||
if (lastMessage && lastMessage.children.length > 0) {
|
||||
const currentIdx = lastMessage.children.findIndex(c => c?.id === lastMessage.activeChildId);
|
||||
const maxIdx = lastMessage.deleted ? lastMessage.children.length - 1 : lastMessage.children.length;
|
||||
const nextIdx = Math.min(maxIdx, currentIdx + 1);
|
||||
addShortcut(['alt', ']'], (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
navigateLastMessage(1);
|
||||
});
|
||||
|
||||
if (lastMessage.deleted) {
|
||||
patchMessageLocally(lastMessage.id, { activeChildId: lastMessage.children[nextIdx]?.id ?? null });
|
||||
} else {
|
||||
if (nextIdx === 0) {
|
||||
patchMessageLocally(lastMessage.id, { activeChildId: null });
|
||||
} else {
|
||||
patchMessageLocally(lastMessage.id, { activeChildId: lastMessage.children[nextIdx - 1]?.id ?? null });
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
addShortcut(['ctrl', 'alt', 'arrowleft'], async (event) => {
|
||||
const lastMessage = topic.value?.messages?.at(-1);
|
||||
if (lastMessage && lastMessage.children.length > 0) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
const currentIdx = lastMessage.children.findIndex(c => c?.id === lastMessage.activeChildId);
|
||||
if (currentIdx > 0) {
|
||||
patchMessageLocally(lastMessage.id, { activeChildId: lastMessage.children[currentIdx - 1]!.id });
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
addShortcut(['ctrl', 'alt', 'arrowright'], async (event) => {
|
||||
const lastMessage = topic.value?.messages?.at(-1);
|
||||
if (lastMessage && lastMessage.children.length > 0) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
const currentIdx = lastMessage.children.findIndex(c => c?.id === lastMessage.activeChildId);
|
||||
const maxIdx = lastMessage.deleted ? lastMessage.children.length - 1 : lastMessage.children.length;
|
||||
const nextIdx = Math.min(maxIdx, currentIdx + 1);
|
||||
|
||||
if (lastMessage.deleted) {
|
||||
patchMessageLocally(lastMessage.id, { activeChildId: lastMessage.children[nextIdx]?.id ?? null });
|
||||
} else {
|
||||
if (nextIdx === 0) {
|
||||
patchMessageLocally(lastMessage.id, { activeChildId: null });
|
||||
} else {
|
||||
patchMessageLocally(lastMessage.id, { activeChildId: lastMessage.children[nextIdx - 1]?.id ?? null });
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
addShortcut(['ctrl', 'alt', 'arrowright'], (event) => {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
navigateLastMessage(1);
|
||||
});
|
||||
|
||||
addShortcut(['ctrl', 'alt', 'backspace'], async (event) => {
|
||||
event.preventDefault();
|
||||
@@ -287,13 +253,12 @@ const handleCancel = async () => {
|
||||
method: 'POST',
|
||||
});
|
||||
};
|
||||
|
||||
console.log("full page render took", Date.now() - rootStart);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="flex flex-col h-full w-full max-w-full overflow-x-hidden">
|
||||
<div class="h-14 flex items-center justify-between px-4 border-b border-[var(--color-border)]">
|
||||
<div
|
||||
class="z-5 h-14 flex items-center justify-between px-4 border-b border-[var(--color-border)] bg-[var(--bg-surface)]">
|
||||
<div class="flex items-center gap-2 max-w-full">
|
||||
<button v-if="!sidebarOpen" @click="openSidebar"
|
||||
class="flex p-2 rounded-lg text-[var(--text-primary)] bg-transparent @hover:bg-[var(--color-hover)] transition-colors">
|
||||
@@ -307,7 +272,7 @@ console.log("full page render took", Date.now() - rootStart);
|
||||
|
||||
<!-- chat pane -->
|
||||
<div ref="chatPaneWrapper"
|
||||
class="chat-scroll-container justify-center w-full h-full [scrollbar-width:thin] [scrollbar-color:#888_transparent] overflow-y-scroll overflow-x-hidden flex justify-center pt-4">
|
||||
class="chat-scroll-container justify-center w-full flex-1 min-h-0 [scrollbar-width:thin] [scrollbar-color:#888_transparent] overflow-y-scroll overflow-x-hidden flex justify-center pt-4">
|
||||
<div class="chatPane max-w-4xl w-full min-h-full flex flex-col px-4">
|
||||
<div class="w-full px-px flex flex-col flex-grow gap-2 pb-9">
|
||||
<Suspense>
|
||||
|
||||
+1
-1
@@ -95,7 +95,7 @@ const handleChatSubmit = async (message: BaseMessage, model: ModelWithProvider |
|
||||
}
|
||||
}
|
||||
|
||||
const topic = await createTopic(targetAgent.id);
|
||||
const topic = await createTopic(targetAgent.id, message);
|
||||
if (!topic) {
|
||||
console.error('Failed to create topic');
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import type { ComarkPlugin } from "comark";
|
||||
import type { SearchSource, StoredToolValue } from "./tool-rendering";
|
||||
import { parseToolValue, readSearchSources } from "./tool-rendering";
|
||||
|
||||
export const citationPlugin: ComarkPlugin = {
|
||||
name: "source-citations",
|
||||
markdownItPlugins: [
|
||||
(markdown) => {
|
||||
markdown.inline.ruler.before("link", "source_citation", (state, silent) => {
|
||||
if (state.linkLevel > 0 || !state.src.startsWith("[[cite:", state.pos)) {
|
||||
return false;
|
||||
}
|
||||
const match = /^\[\[cite:([a-zA-Z0-9_-]+(?:,[a-zA-Z0-9_-]+)*)\]\]/.exec(state.src.slice(state.pos));
|
||||
if (!match) {
|
||||
return false;
|
||||
}
|
||||
if (silent) {
|
||||
return false;
|
||||
}
|
||||
const token = state.push("mdc_inline_component", "source-cite", 0);
|
||||
token.attrSet("ids", match[1] ?? "");
|
||||
state.pos += match[0].length;
|
||||
return true;
|
||||
});
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
export const collectCitationSources = (
|
||||
parts: readonly { toolCall?: { toolName: string; output?: StoredToolValue } | null }[],
|
||||
): ReadonlyMap<string, SearchSource> => {
|
||||
const sources = new Map<string, SearchSource>();
|
||||
for (const part of parts) {
|
||||
if (part.toolCall?.toolName !== "search") {
|
||||
continue;
|
||||
}
|
||||
const results = readSearchSources(parseToolValue(part.toolCall.output), { deduplicate: false });
|
||||
for (const source of results ?? []) {
|
||||
if (source.sourceId) {
|
||||
sources.set(source.sourceId, source);
|
||||
}
|
||||
}
|
||||
}
|
||||
return sources;
|
||||
};
|
||||
@@ -0,0 +1,11 @@
|
||||
export const getComposerHeight = (
|
||||
scrollHeight: number,
|
||||
lineHeight: number,
|
||||
padding: number,
|
||||
borders: number,
|
||||
borderBox: boolean,
|
||||
): number => {
|
||||
const contentHeight = Math.min(Math.max(scrollHeight - padding, lineHeight * 2), lineHeight * 10);
|
||||
// A stable CSS-pixel boundary avoids 47.999… / 48.01 oscillations.
|
||||
return Math.round(contentHeight + (borderBox ? padding + borders : 0));
|
||||
};
|
||||
+82
-71
@@ -3,6 +3,7 @@ import { createSerializedMarkdownParser as createComarkParser } from 'comark';
|
||||
import breaks from 'comark/plugins/breaks';
|
||||
import footnotes from 'comark/plugins/footnotes';
|
||||
import math from 'comark/plugins/math';
|
||||
import { citationPlugin } from './citations';
|
||||
|
||||
export type MarkdownTree = MarkdownDocument;
|
||||
export type MarkdownAstNode = Node;
|
||||
@@ -39,10 +40,10 @@ const parserPlugins = [
|
||||
math(),
|
||||
] as const;
|
||||
|
||||
const createConfiguredParser = (autoClose: boolean) => createComarkParser({
|
||||
const createConfiguredParser = (autoClose: boolean, citations: boolean) => createComarkParser({
|
||||
registerDefaultPlugins: false,
|
||||
autoClose,
|
||||
plugins: parserPlugins,
|
||||
plugins: citations ? [...parserPlugins, citationPlugin] : parserPlugins,
|
||||
});
|
||||
|
||||
const protectDollarRunsInLine = (line: string): string => {
|
||||
@@ -89,6 +90,10 @@ const protectDollarRunsInLine = (line: string): string => {
|
||||
};
|
||||
|
||||
const protectDollarRuns = (content: string): string => {
|
||||
// Fast path: most messages contain no dollar runs; avoid line-splitting entirely.
|
||||
if (!content.includes('$')) {
|
||||
return content;
|
||||
}
|
||||
const lines = content.split('\n');
|
||||
let inFence = false;
|
||||
|
||||
@@ -107,13 +112,16 @@ const protectDollarRuns = (content: string): string => {
|
||||
}).join('\n');
|
||||
};
|
||||
|
||||
export const createMarkdownParser = () => {
|
||||
const streamingParser = createConfiguredParser(true);
|
||||
const finalParser = createConfiguredParser(false);
|
||||
export const createMarkdownParser = (options: { citations?: boolean } = {}) => {
|
||||
const citations = options.citations === true;
|
||||
const streamingParser = createConfiguredParser(true, citations);
|
||||
const finalParser = createConfiguredParser(false, citations);
|
||||
|
||||
return (content: string, options: { streaming?: boolean } = {}) => {
|
||||
const protectedContent = protectDollarRuns(content);
|
||||
if (options.streaming === true) {
|
||||
// Do not let auto-close complete an unfinished citation on the model's behalf.
|
||||
const incompleteCitation = citations && /\[\[cite:[a-zA-Z0-9_,\-]*\]?$/.test(protectedContent);
|
||||
if (options.streaming === true && !incompleteCitation) {
|
||||
return streamingParser(protectedContent, { streaming: true });
|
||||
}
|
||||
|
||||
@@ -121,6 +129,9 @@ export const createMarkdownParser = () => {
|
||||
};
|
||||
};
|
||||
|
||||
export const agentParser = createMarkdownParser({ citations: true });
|
||||
export const userParser = createMarkdownParser({ citations: false });
|
||||
|
||||
export const getNodeTag = (node: MarkdownAstNode): string | null => {
|
||||
if (!Array.isArray(node) || node[0] === null) {
|
||||
return null;
|
||||
@@ -157,29 +168,7 @@ export const textContent = (node: MarkdownAstNode): string => {
|
||||
return getNodeChildren(node).map(textContent).join('');
|
||||
};
|
||||
|
||||
const cloneNode = (node: MarkdownAstNode): MarkdownAstNode => {
|
||||
if (typeof node === 'string') {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (!Array.isArray(node)) {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (node[0] === null) {
|
||||
return [null, { ...node[1] }, node[2]];
|
||||
}
|
||||
|
||||
return [
|
||||
node[0],
|
||||
{ ...node[1] },
|
||||
...getNodeChildren(node).map(cloneNode),
|
||||
] as MarkdownElementNode;
|
||||
};
|
||||
|
||||
const splitParagraph = (node: MarkdownElementNode): MarkdownElementNode[] => {
|
||||
const attributes = { ...node[1] };
|
||||
const children = getNodeChildren(node);
|
||||
const splitParagraph = (attributes: Record<string, unknown>, children: MarkdownAstNode[]): MarkdownElementNode[] => {
|
||||
const paragraphs: MarkdownElementNode[] = [];
|
||||
let current: MarkdownAstNode[] = [];
|
||||
|
||||
@@ -200,58 +189,80 @@ const splitParagraph = (node: MarkdownElementNode): MarkdownElementNode[] => {
|
||||
return paragraphs;
|
||||
};
|
||||
|
||||
const transformChildren = (nodes: MarkdownAstNode[]): MarkdownAstNode[] => {
|
||||
const result: MarkdownAstNode[] = [];
|
||||
const hasBrChild = (children: MarkdownAstNode[]): boolean =>
|
||||
children.some((child) => getNodeTag(child) === 'br');
|
||||
|
||||
for (const originalNode of nodes) {
|
||||
const node = cloneNode(originalNode);
|
||||
if (typeof node === 'string' || !Array.isArray(node) || node[0] === null) {
|
||||
result.push(node);
|
||||
continue;
|
||||
/**
|
||||
* Transform a single element node into its replacement list. Returns a
|
||||
* single-element array holding the ORIGINAL node reference when nothing
|
||||
* changed, so callers can skip all allocation for unaffected subtrees.
|
||||
*/
|
||||
const transformElement = (node: MarkdownElementNode): MarkdownAstNode[] => {
|
||||
const tag = node[0];
|
||||
const children = getNodeChildren(node);
|
||||
const transformedChildren = transformChildren(children);
|
||||
|
||||
if (tag === 'p') {
|
||||
if (!hasBrChild(transformedChildren)) {
|
||||
if (transformedChildren === children) return [node];
|
||||
return [[tag, { ...node[1] }, ...transformedChildren] as MarkdownElementNode];
|
||||
}
|
||||
|
||||
const tag = node[0];
|
||||
const transformedChildren = transformChildren(getNodeChildren(node));
|
||||
let transformedNode = [tag, { ...node[1] }, ...transformedChildren] as MarkdownElementNode;
|
||||
|
||||
if (tag === 'p') {
|
||||
result.push(...splitParagraph(transformedNode));
|
||||
continue;
|
||||
}
|
||||
|
||||
if ((tag === 'li' || tag === 'blockquote') && transformedChildren.some((child) => getNodeTag(child) === 'br')) {
|
||||
const segments: MarkdownAstNode[][] = [[]];
|
||||
for (const child of transformedChildren) {
|
||||
if (getNodeTag(child) === 'br') {
|
||||
segments.push([]);
|
||||
} else {
|
||||
segments[segments.length - 1]?.push(child);
|
||||
}
|
||||
}
|
||||
|
||||
transformedNode = [
|
||||
tag,
|
||||
{ ...node[1] },
|
||||
...segments
|
||||
.filter((segment) => segment.length > 0)
|
||||
.map((segment) => ['p', {}, ...segment] as MarkdownElementNode),
|
||||
] as MarkdownElementNode;
|
||||
}
|
||||
|
||||
result.push(transformedNode);
|
||||
return splitParagraph({ ...node[1] }, transformedChildren);
|
||||
}
|
||||
|
||||
return result;
|
||||
if ((tag === 'li' || tag === 'blockquote') && hasBrChild(transformedChildren)) {
|
||||
const segments: MarkdownAstNode[][] = [[]];
|
||||
for (const child of transformedChildren) {
|
||||
if (getNodeTag(child) === 'br') {
|
||||
segments.push([]);
|
||||
} else {
|
||||
segments[segments.length - 1]?.push(child);
|
||||
}
|
||||
}
|
||||
|
||||
return [[
|
||||
tag,
|
||||
{ ...node[1] },
|
||||
...segments
|
||||
.filter((segment) => segment.length > 0)
|
||||
.map((segment) => ['p', {}, ...segment] as MarkdownElementNode),
|
||||
] as MarkdownElementNode];
|
||||
}
|
||||
|
||||
if (transformedChildren === children) return [node];
|
||||
return [[tag, { ...node[1] }, ...transformedChildren] as MarkdownElementNode];
|
||||
};
|
||||
|
||||
const transformChildren = (nodes: MarkdownAstNode[]): MarkdownAstNode[] => {
|
||||
let result: MarkdownAstNode[] | null = null;
|
||||
|
||||
for (let index = 0; index < nodes.length; index++) {
|
||||
const node = nodes[index]!;
|
||||
const replacement = typeof node === 'string' || !Array.isArray(node) || node[0] === null
|
||||
? [node]
|
||||
: transformElement(node);
|
||||
|
||||
if (result === null) {
|
||||
if (replacement.length === 1 && replacement[0] === node) continue;
|
||||
result = nodes.slice(0, index);
|
||||
}
|
||||
result.push(...replacement);
|
||||
}
|
||||
|
||||
return result ?? nodes;
|
||||
};
|
||||
|
||||
/**
|
||||
* Comark's breaks plugin emits `br` nodes. Promote each hard break to a
|
||||
* sibling paragraph to keep the chat renderer's established layout.
|
||||
*
|
||||
* Copy-on-write: trees without `br` nodes are returned by reference with no
|
||||
* allocation, so the common case costs a single tag scan per node.
|
||||
*/
|
||||
export const splitParagraphBreaks = (tree: MarkdownTree): MarkdownTree => ({
|
||||
...tree,
|
||||
nodes: transformChildren(tree.nodes),
|
||||
});
|
||||
export const splitParagraphBreaks = (tree: MarkdownTree): MarkdownTree => {
|
||||
const nodes = transformChildren(tree.nodes);
|
||||
return nodes === tree.nodes ? tree : { ...tree, nodes };
|
||||
};
|
||||
|
||||
export const toVueAttributes = (attributes: Record<string, unknown>): Record<string, unknown> => {
|
||||
const result: Record<string, unknown> = {};
|
||||
|
||||
@@ -21,6 +21,7 @@ export const formatToolValue = (stored: StoredToolValue): string => {
|
||||
};
|
||||
|
||||
export interface SearchSource {
|
||||
sourceId?: string;
|
||||
title: string;
|
||||
url: string;
|
||||
hostname: string;
|
||||
@@ -41,7 +42,7 @@ export const readSearchWarnings = (value: unknown): { engine: string; reason: st
|
||||
});
|
||||
};
|
||||
|
||||
export const readSearchSources = (value: unknown): SearchSource[] | null => {
|
||||
export const readSearchSources = (value: unknown, options: { deduplicate?: boolean } = {}): SearchSource[] | null => {
|
||||
// Older tool calls stored the results array directly.
|
||||
if (typeof value === "object" && value !== null && "results" in value) {
|
||||
value = value.results;
|
||||
@@ -65,11 +66,12 @@ export const readSearchSources = (value: unknown): SearchSource[] | null => {
|
||||
continue;
|
||||
}
|
||||
url.hash = "";
|
||||
if (seen.has(url.href)) {
|
||||
if (options.deduplicate !== false && seen.has(url.href)) {
|
||||
continue;
|
||||
}
|
||||
seen.add(url.href);
|
||||
sources.push({
|
||||
...("sourceId" in item && typeof item.sourceId === "string" ? { sourceId: item.sourceId } : {}),
|
||||
title: "title" in item && typeof item.title === "string" ? item.title : url.hostname,
|
||||
url: url.href,
|
||||
hostname: url.hostname,
|
||||
|
||||
Reference in New Issue
Block a user