bug fixes, and performance improvements, and drawer
This commit is contained in:
@@ -4,6 +4,7 @@
|
|||||||
- [x] Make dropdowns a singleton component (work in progress)
|
- [x] Make dropdowns a singleton component (work in progress)
|
||||||
- [ ] Make the sidebar better :kekdoggo:. It's annoying to manage across routes
|
- [ ] Make the sidebar better :kekdoggo:. It's annoying to manage across routes
|
||||||
- [x] Make topics manually renameable
|
- [x] Make topics manually renameable
|
||||||
|
- [ ] Surface auto-rename failures through the future toast/error UI; add actionable retry and bounded bulk naming for unnamed/provisional topics
|
||||||
- [ ] Improve latex rendering, make single line equations work _well_, and likely make it configurable
|
- [ ] Improve latex rendering, make single line equations work _well_, and likely make it configurable
|
||||||
- [x] Implement appearence settings
|
- [x] Implement appearence settings
|
||||||
- [x] Accent colors
|
- [x] Accent colors
|
||||||
|
|||||||
@@ -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");
|
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 {
|
.reasoning-container.top {
|
||||||
mask-image: linear-gradient(#000, #000, transparent 0, #000 12%, #000 88%, transparent)
|
-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 {
|
.reasoning-container.middle {
|
||||||
mask-image: linear-gradient(#000, transparent, #000 0, #000 12%, #000 88%, transparent)
|
-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 {
|
.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 */
|
/* Markdown renderer */
|
||||||
|
|||||||
+104
-51
@@ -4,11 +4,17 @@ import { computed, onMounted, ref, watch, onUnmounted, nextTick, type Ref } from
|
|||||||
import type { ModelWithProvider, ProviderWithModels } from '~/composables/useModels';
|
import type { ModelWithProvider, ProviderWithModels } from '~/composables/useModels';
|
||||||
import type { Agent } from '~/composables/useAgents';
|
import type { Agent } from '~/composables/useAgents';
|
||||||
import type FileSelector from './FileSelector.vue';
|
import type FileSelector from './FileSelector.vue';
|
||||||
|
import { getComposerHeight } from '~/utils/composer-size';
|
||||||
|
|
||||||
const { allModels } = await useModels();
|
const { allModels } = await useModels();
|
||||||
const { updateAgent, patchAgentLocally } = await useAgents();
|
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 fileSelectorRef = ref<InstanceType<typeof FileSelector> | null>(null);
|
||||||
const inputRef = ref<HTMLTextAreaElement | null>(null);
|
const inputRef = ref<HTMLTextAreaElement | null>(null);
|
||||||
let tempInput = '';
|
let tempInput = '';
|
||||||
@@ -303,47 +309,57 @@ const handleWindowKeyDown = async (event: KeyboardEvent) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const mirrorRef = ref<HTMLDivElement | null>(null);
|
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 resizeTextArea = () => {
|
||||||
|
if (import.meta.server || sizingRaf !== undefined) return;
|
||||||
|
sizingRaf = requestAnimationFrame(() => {
|
||||||
|
sizingRaf = undefined;
|
||||||
const textarea = inputRef.value;
|
const textarea = inputRef.value;
|
||||||
const mirror = mirrorRef.value;
|
const mirror = mirrorRef.value;
|
||||||
if (!textarea || !mirror) return;
|
if (!textarea || !mirror) return;
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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;
|
||||||
|
|
||||||
|
// Capture bottom-follow intent before applying the new height.
|
||||||
emit('resize');
|
emit('resize');
|
||||||
nextTick().then(() => {
|
inputHeight.value = height;
|
||||||
mirror.textContent = (textarea.value || '\u200b') + '\n';
|
|
||||||
|
|
||||||
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';
|
|
||||||
|
|
||||||
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`;
|
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
watch(textAreaValue, resizeTextArea, { immediate: true });
|
watch(textAreaValue, resizeTextArea, { flush: 'post' });
|
||||||
|
|
||||||
let hasCommandKey = false;
|
let hasCommandKey = false;
|
||||||
if (import.meta.server) {
|
if (import.meta.server) {
|
||||||
@@ -357,41 +373,51 @@ onBeforeMount(() => {
|
|||||||
tempInput = (document.getElementById('chat') as HTMLInputElement)?.value ?? '';
|
tempInput = (document.getElementById('chat') as HTMLInputElement)?.value ?? '';
|
||||||
});
|
});
|
||||||
|
|
||||||
let resizeRafId: number | undefined;
|
|
||||||
const handleWindowResize = () => {
|
const handleWindowResize = () => {
|
||||||
if (resizeRafId) return;
|
sizingDirty = true;
|
||||||
resizeRafId = requestAnimationFrame(() => {
|
|
||||||
resizeRafId = undefined;
|
|
||||||
resizeTextArea();
|
resizeTextArea();
|
||||||
});
|
};
|
||||||
}
|
|
||||||
|
|
||||||
onMounted(() => {
|
onMounted(() => {
|
||||||
textAreaValue.value = tempInput;
|
textAreaValue.value = tempInput;
|
||||||
document.addEventListener('keydown', handleWindowKeyDown);
|
document.addEventListener('keydown', handleWindowKeyDown);
|
||||||
window.addEventListener('resize', handleWindowResize);
|
window.addEventListener('resize', handleWindowResize);
|
||||||
inputRef.value?.addEventListener('paste', handlePaste);
|
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(() => {
|
onUnmounted(() => {
|
||||||
document.removeEventListener('keydown', handleWindowKeyDown);
|
document.removeEventListener('keydown', handleWindowKeyDown);
|
||||||
window.removeEventListener('resize', handleWindowResize);
|
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);
|
inputRef.value?.removeEventListener('paste', handlePaste);
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div :class="['w-full flex max-h-full', $attrs.class]">
|
<div :class="['w-full flex flex-col max-h-full', $attrs.class]">
|
||||||
<div ref="mirrorRef" aria-hidden="true"
|
<div ref="mirrorRef" data-chat-measurement aria-hidden="true"
|
||||||
class="absolute top-0 left-0 pointer-events-none invisible overflow-hidden h-0"></div>
|
class="fixed top-0 left-0 pointer-events-none invisible overflow-hidden h-0 [contain:layout_style_paint]"></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="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)]">
|
border-[var(--color-border)] focus-within:border-[var(--color-border-active)]">
|
||||||
<div v-if="files.length > 0"
|
<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]">
|
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 -->
|
<!-- TODO: show attachment previews -->
|
||||||
<AttachmentPreview v-for="file in files" @delete="files = files.filter((f) => f.id !== file.id)"
|
<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>
|
||||||
<div class="min-w-0 max-h-full">
|
<div class="min-w-0 max-h-full">
|
||||||
<!-- Grammarly literally breaks everything, go fuck yourself -->
|
<!-- Grammarly literally breaks everything, go fuck yourself -->
|
||||||
@@ -404,15 +430,29 @@ onUnmounted(() => {
|
|||||||
|
|
||||||
<div class="flex items-center justify-between gap-2">
|
<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 -->
|
<!-- 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"
|
<ModelSelector v-if="providers !== undefined" :add-hotkey="true" v-model="selectedModel"
|
||||||
:providers="providers" />
|
:providers="providers"></ModelSelector>
|
||||||
<SearchSelector v-if="selectedModel?.capabilities.includes('tools')" :enabled="searchConfig.enabled"
|
<div v-if="selectedModel?.capabilities.includes('tools')" class="hidden sm:flex items-center gap-1">
|
||||||
@update:enabled="(v: boolean) => { searchConfig.enabled = v; saveSearchConfig() }" />
|
<SearchSelector :enabled="searchConfig.enabled"
|
||||||
<ToolSelector v-if="selectedModel?.capabilities.includes('tools')" :python="toolsConfig.python"
|
@update:enabled="(v: boolean) => { searchConfig.enabled = v; saveSearchConfig(); }"></SearchSelector>
|
||||||
@update:python="(v: boolean) => { toolsConfig.python = v; saveToolsConfig() }" />
|
<ToolSelector :python="toolsConfig.python"
|
||||||
<FileSelector ref="fileSelectorRef" :selected-model="selectedModel" v-model="files" />
|
@update:python="(v: boolean) => { toolsConfig.python = v; saveToolsConfig(); }"></ToolSelector>
|
||||||
</div>
|
</div>
|
||||||
|
</div>
|
||||||
|
<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">
|
<div v-if="allowManualRole" class="flex items-center">
|
||||||
<button aria-label="Send message" @click="handleSubmit"
|
<button aria-label="Send message" @click="handleSubmit"
|
||||||
:disabled="((!inputValue.content.trim() && files.length === 0) && !loading) || isUploading || hasFailedUploads"
|
:disabled="((!inputValue.content.trim() && files.length === 0) && !loading) || isUploading || hasFailedUploads"
|
||||||
@@ -471,4 +511,17 @@ onUnmounted(() => {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</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>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
@@ -1,7 +1,9 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import type { MarkdownAstNode, MarkdownElementNode } from '~/utils/markdown';
|
import type { MarkdownAstNode } from '~/utils/markdown';
|
||||||
import { createMarkdownParser, getNodeAttributes, getNodeChildren, getNodeTag, splitParagraphBreaks, textContent, toVueAttributes } from '~/utils/markdown';
|
import { agentParser, userParser, getNodeAttributes, getNodeChildren, getNodeTag, splitParagraphBreaks, textContent, toVueAttributes } from '~/utils/markdown';
|
||||||
import { createTextVNode, h, ref, watch } from 'vue';
|
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 MarkdownMath from './Math.vue';
|
||||||
import MarkdownShikiHighlight from './ShikiHighlight.vue';
|
import MarkdownShikiHighlight from './ShikiHighlight.vue';
|
||||||
|
|
||||||
@@ -9,15 +11,19 @@ const props = defineProps<{
|
|||||||
content: string;
|
content: string;
|
||||||
finished: boolean;
|
finished: boolean;
|
||||||
id: string;
|
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 parse = async (content: string, finished: boolean) => {
|
||||||
const tree = await parser(content, { streaming: !finished });
|
const tree = await parser(content, { streaming: !finished });
|
||||||
|
// Copy-on-write: br-free trees return by reference with no allocation.
|
||||||
return splitParagraphBreaks(tree);
|
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;
|
let parseVersion = 0;
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
@@ -46,6 +52,11 @@ const renderNode = (node: MarkdownAstNode, path: string): any => {
|
|||||||
|
|
||||||
const tag = getNodeTag(node);
|
const tag = getNodeTag(node);
|
||||||
const attributes = getNodeAttributes(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') {
|
if (tag === 'pre') {
|
||||||
const language = typeof attributes.language === 'string' ? attributes.language : 'text';
|
const language = typeof attributes.language === 'string' ? attributes.language : 'text';
|
||||||
return h(MarkdownShikiHighlight, {
|
return h(MarkdownShikiHighlight, {
|
||||||
@@ -79,9 +90,7 @@ const render = () => {
|
|||||||
.map((node, index) => renderNode(node, `${props.id}.${index}`))
|
.map((node, index) => renderNode(node, `${props.id}.${index}`))
|
||||||
.filter((child) => child !== null);
|
.filter((child) => child !== null);
|
||||||
|
|
||||||
return h('div', { class: 'prose-wrapper' }, [
|
return h('article', { class: 'prose-wrapper markdown-body' }, children);
|
||||||
h('article', { class: 'markdown-body' }, children),
|
|
||||||
]);
|
|
||||||
};
|
};
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|||||||
@@ -3,8 +3,6 @@ import { type Grammar } from 'shiki';
|
|||||||
import { hashSync } from '~/utils/hash';
|
import { hashSync } from '~/utils/hash';
|
||||||
const props = defineProps<{ code: string; language: string }>();
|
const props = defineProps<{ code: string; language: string }>();
|
||||||
|
|
||||||
const start = Date.now();
|
|
||||||
|
|
||||||
const MAX_LENGTH = 15000;
|
const MAX_LENGTH = 15000;
|
||||||
|
|
||||||
const renderId = `${useId()}-${hashSync(props.code + props.language)}`;
|
const renderId = `${useId()}-${hashSync(props.code + props.language)}`;
|
||||||
@@ -76,8 +74,6 @@ onUnmounted(() => {
|
|||||||
if (copyTimeout) clearTimeout(copyTimeout);
|
if (copyTimeout) clearTimeout(copyTimeout);
|
||||||
clear();
|
clear();
|
||||||
});
|
});
|
||||||
|
|
||||||
console.log("shiki codeblock rendered in", Date.now() - start);
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<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">
|
<script setup lang="ts">
|
||||||
import type { MessagePart } from '~/composables/useChat';
|
import type { MessagePart } from '~/composables/useChat';
|
||||||
|
import ReasoningBody from './ReasoningBody.vue';
|
||||||
|
|
||||||
const props = defineProps<{
|
const props = defineProps<{
|
||||||
part: Readonly<MessagePart>;
|
part: Readonly<MessagePart>;
|
||||||
}>();
|
}>();
|
||||||
|
|
||||||
const reasoningOpen = ref(!props.part.finished);
|
const reasoningOpen = ref(!props.part.finished);
|
||||||
|
const bodyRef = ref<InstanceType<typeof ReasoningBody> | null>(null);
|
||||||
|
|
||||||
watch(
|
watch(
|
||||||
() => props.part.finished,
|
() => 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 () => {
|
const toggleReasoning = async () => {
|
||||||
if (!props.part.finished) return;
|
if (!props.part.finished) return;
|
||||||
|
|
||||||
reasoningOpen.value = !reasoningOpen.value;
|
reasoningOpen.value = !reasoningOpen.value;
|
||||||
if (!reasoningOpen.value) return;
|
if (!reasoningOpen.value) return;
|
||||||
await nextTick();
|
await nextTick();
|
||||||
scrollToBottom('instant');
|
bodyRef.value?.scrollToBottom('instant');
|
||||||
handleScroll();
|
bodyRef.value?.handleScroll();
|
||||||
};
|
};
|
||||||
|
|
||||||
const formatDuration = (ms: number) => {
|
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)]"
|
<span class="i-mynaui-chevron-down w-4 h-4 text-[var(--text-secondary)]"
|
||||||
:class="reasoningOpen ? '' : '-rotate-90'"></span>
|
:class="reasoningOpen ? '' : '-rotate-90'"></span>
|
||||||
</button>
|
</button>
|
||||||
<div v-if="reasoningOpen" ref="containerRef" @scroll="handleScroll"
|
<ReasoningBody v-if="reasoningOpen" ref="bodyRef" :part="part" />
|
||||||
: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>
|
|
||||||
</div>
|
</div>
|
||||||
</template>
|
</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">
|
<script setup lang="ts">
|
||||||
|
import { collectCitationSources } from '~/utils/citations';
|
||||||
|
import type { SearchSource } from '~/utils/tool-rendering';
|
||||||
import Error from './Error.vue';
|
import Error from './Error.vue';
|
||||||
import Reasoning from './Reasoning.vue';
|
import Reasoning from './Reasoning.vue';
|
||||||
import Text from './Text.vue';
|
|
||||||
import Tool from './Tool/index.vue';
|
import Tool from './Tool/index.vue';
|
||||||
import type { MessageEntity } from '~/composables/useChat';
|
import type { MessageEntity } from '~/composables/useChat';
|
||||||
|
|
||||||
@@ -9,6 +10,14 @@ const props = defineProps<{
|
|||||||
message: MessageEntity
|
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 triggerRef = ref<HTMLElement | null>(null);
|
||||||
|
|
||||||
const { open, close, isOpen } = useTokenDropdown();
|
const { open, close, isOpen } = useTokenDropdown();
|
||||||
@@ -25,14 +34,17 @@ const toggleTokenDropdown = () => {
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="flex flex-col w-full gap-2">
|
<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">
|
<template v-for="part in message.parts" :key="part.id">
|
||||||
<Reasoning v-if="part.type === 'reasoning'" :part="part" />
|
<template v-if="part.content?.trim() !== '' || part.toolCall">
|
||||||
<Text v-else-if="part.type === 'text'" :part="part" />
|
<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>
|
<Tool v-else-if="part.type === 'tool-call'" :tool-call="part.toolCall!" :part="part"></Tool>
|
||||||
<div v-else>
|
<div v-else>
|
||||||
Unhandled part type: {{ part.type }} {{ part }}
|
Unhandled part type: {{ part.type }} {{ part }}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</template>
|
||||||
|
</template>
|
||||||
|
|
||||||
<span class="flex items-center gap-1"
|
<span class="flex items-center gap-1"
|
||||||
v-if="message.generation?.status === 'pending' && (message.parts || []).length === 0">
|
v-if="message.generation?.status === 'pending' && (message.parts || []).length === 0">
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import type { Message } from '~/composables/useChat';
|
import type { Message } from '~/composables/useChat';
|
||||||
|
import { getActiveMessage, getCurrentChildIndex, getMessageCount, getNextActiveChildId } from '~~/utils/message';
|
||||||
|
|
||||||
const { openDialog } = useDialog();
|
const { openDialog } = useDialog();
|
||||||
|
|
||||||
@@ -35,7 +36,9 @@ watch(() => message.activeChildId, async (newValue) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
watch(() => message.children.length, (newCount, oldCount) => {
|
watch(() => message.children.length, (newCount, oldCount) => {
|
||||||
if (newCount === oldCount) return;
|
if (newCount === oldCount) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
if (newCount === 0) {
|
if (newCount === 0) {
|
||||||
emit('patch', { activeChildId: null });
|
emit('patch', { activeChildId: null });
|
||||||
@@ -56,19 +59,17 @@ watch(() => message.children.length, (newCount, oldCount) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const activeMessage = computed(() => {
|
watch(() => message.deleted, (isDeleted) => {
|
||||||
if (message.activeChildId && message.children.length > 0) {
|
if (isDeleted && message.children.length > 0) {
|
||||||
const child = message.children.find(c => c?.id === message.activeChildId);
|
const activeChild = message.children.find(c => c?.id === message.activeChildId);
|
||||||
if (child) return child;
|
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 copied = ref(false);
|
||||||
const copyMessage = async () => {
|
const copyMessage = async () => {
|
||||||
if (activeMessage.value!.role === 'user') {
|
if (activeMessage.value!.role === 'user') {
|
||||||
@@ -135,91 +136,118 @@ const deleteMessage = () => {
|
|||||||
emit('delete');
|
emit('delete');
|
||||||
};
|
};
|
||||||
|
|
||||||
const messageCount = computed(() => {
|
const messageCount = computed(() => getMessageCount(message));
|
||||||
if (message.deleted === true) {
|
|
||||||
return message.children.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
return message.children.length + 1;
|
const currentChildIndex = computed(() => getCurrentChildIndex(message));
|
||||||
});
|
|
||||||
|
|
||||||
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 navigateChild = (direction: -1 | 1) => {
|
const navigateChild = (direction: -1 | 1) => {
|
||||||
const allItems = message.deleted === true
|
const nextActiveChildId = getNextActiveChildId(message, direction);
|
||||||
? message.children
|
emit('patch', { activeChildId: nextActiveChildId });
|
||||||
: [null, ...message.children];
|
};
|
||||||
|
|
||||||
const currentIdx = allItems.findIndex(item =>
|
const { show: showTooltip, hide: hideTooltip } = useTooltip();
|
||||||
!item ? !message.activeChildId : item.id === message.activeChildId
|
|
||||||
);
|
|
||||||
|
|
||||||
const newIdx = Math.max(0, Math.min(allItems.length - 1, currentIdx + direction));
|
let hasCursor: boolean | null = null;
|
||||||
const newItem = allItems[newIdx];
|
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>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div v-if="activeMessage" class="max-w-full mb-4 group flex flex-col">
|
<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'" class="pl-9 self-end" :message="activeMessage!"></MessageUser>
|
||||||
<MessageUser v-if="message.role === 'user'" :message="activeMessage!" />
|
<MessageAgent v-else :message="activeMessage"></MessageAgent>
|
||||||
<MessageAgent v-else :message="activeMessage" />
|
<div class="flex justify-between items-center" @click="handleAction">
|
||||||
</div>
|
<div v-if="messageCount > 1" class="flex gap-1"
|
||||||
<div class="flex justify-between items-center">
|
@mouseover="handleTooltipHover" @mouseout="handleTooltipLeave">
|
||||||
<div>
|
<button data-action="prev-child" :data-hotkey="currentChildIndex > 0 ? 'alt,[' : undefined"
|
||||||
<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)]">
|
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)]"
|
<span class="i-mynaui-chevron-left w-4 h-4 text-[var(--text-secondary)] pointer-events-none"
|
||||||
:class="currentChildIndex === 0 ? 'opacity-0' : ''"></span>
|
:class="currentChildIndex === 0 ? 'opacity-0' : ''"></span>
|
||||||
</button>
|
</button>
|
||||||
</Tooltip>
|
|
||||||
<span class="text-xs text-[var(--text-secondary)]">
|
<span class="text-xs text-[var(--text-secondary)]">
|
||||||
{{ currentChildIndex + 1 }} / {{ messageCount }}
|
{{ currentChildIndex + 1 }} / {{ messageCount }}
|
||||||
</span>
|
</span>
|
||||||
<Tooltip :inert="currentChildIndex + 1 === messageCount" :hotkey="['alt', ']']">
|
<button data-action="next-child" :data-hotkey="currentChildIndex + 1 < messageCount ? 'alt,]' : undefined"
|
||||||
<button @click="navigateChild(1)"
|
|
||||||
class="@hover:bg-[var(--color-hover)] rounded transition duration-150 ease-[cubic-bezier(0.5,_1,_0.89,_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)]"
|
<span class="i-mynaui-chevron-right w-4 h-4 text-[var(--text-secondary)] pointer-events-none"
|
||||||
:class="currentChildIndex + 1 === messageCount ? 'opacity-0' : ''"></span>
|
:class="currentChildIndex + 1 === messageCount ? 'opacity-0' : ''"></span>
|
||||||
</button>
|
</button>
|
||||||
</Tooltip>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div v-show="activeMessage.generation?.status !== 'pending'"
|
<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)]">
|
@mouseover="handleTooltipHover" @mouseout="handleTooltipLeave"
|
||||||
<Tooltip :hotkey="['ctrl', 'shift', 'enter']">
|
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 @click="regenerateMessage"
|
<button data-action="regenerate" data-hotkey="ctrl,shift,enter"
|
||||||
class="flex justify-center items-center w-7 h-6 @hover:bg-[var(--color-hover)]">
|
class="flex justify-center items-center w-7 h-6 @hover:bg-[var(--color-hover)]">
|
||||||
<span class="i-mynaui-refresh text-4.5"></span>
|
<span class="i-mynaui-refresh text-4.5 pointer-events-none"></span>
|
||||||
</button>
|
</button>
|
||||||
</Tooltip>
|
<button v-if="message.role === 'user'" data-action="edit"
|
||||||
<button v-if="message.role === 'user'" @click="handleEdit"
|
|
||||||
class="flex justify-center items-center w-7 h-6 @hover:bg-[var(--color-hover)]">
|
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-pencil text-4.5 pointer-events-none"></span>
|
||||||
</button>
|
</button>
|
||||||
<button @click="copyMessage" :class="{ 'text-emerald-500': copied }"
|
<button data-action="copy" :class="{ 'text-emerald-500': copied }"
|
||||||
class="flex justify-center items-center w-7 h-6 @hover:bg-[var(--color-hover)]">
|
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="copied ? 'i-mynaui-check text-emerald-500' : 'i-mynaui-copy text-4.5'" class="pointer-events-none"></span>
|
||||||
</button>
|
</button>
|
||||||
<button @click="forkMessage"
|
<button data-action="fork"
|
||||||
class="flex justify-center items-center w-7 h-6 @hover:bg-[var(--color-hover)]">
|
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="i-mynaui-git-branch text-4.5 pointer-events-none"></span>
|
||||||
</button>
|
</button>
|
||||||
<Tooltip :hotkey="['ctrl', 'shift', 'backspace']">
|
<button data-action="delete" data-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)]">
|
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>
|
<span class="i-mynaui-trash text-5 pointer-events-none"></span>
|
||||||
</button>
|
</button>
|
||||||
</Tooltip>
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -127,10 +127,12 @@ const autoRenameTopic = async (topicId: string) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const cancelAutoRename = async (topicId: string) => {
|
const cancelAutoRename = async (topicId: string) => {
|
||||||
// TODO: make this more optimistic
|
const result = await $fetch(`/api/topic/${topicId}/auto-rename/cancel`, {
|
||||||
await $fetch(`/api/topic/${topicId}/auto-rename/cancel`, {
|
method: "POST",
|
||||||
method: 'POST',
|
|
||||||
});
|
});
|
||||||
|
if (result.ok) {
|
||||||
|
patchTopicLocally(topicId, { renaming: false });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const renameTopicId = ref<string | null>(null);
|
const renameTopicId = ref<string | null>(null);
|
||||||
@@ -256,12 +258,13 @@ onMounted(() => {
|
|||||||
v-model="newTopicName" @keydown.enter="saveRename" @keydown.escape="cancelRename"
|
v-model="newTopicName" @keydown.enter="saveRename" @keydown.escape="cancelRename"
|
||||||
@blur="saveRename"
|
@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" />
|
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">
|
<div v-else class="flex items-center gap-2 min-w-0">
|
||||||
<span class="i-svg-spinners-3-dots-fade text-7 md:text-6"></span>
|
<span class="md:text-sm font-medium overflow-hidden text-ellipsis whitespace-nowrap">
|
||||||
</div>
|
|
||||||
<span v-else class="md:text-sm font-medium overflow-hidden text-ellipsis whitespace-nowrap">
|
|
||||||
{{ topic.name }}
|
{{ topic.name }}
|
||||||
</span>
|
</span>
|
||||||
|
<span v-if="topic.renaming" aria-label="Renaming"
|
||||||
|
class="i-svg-spinners-3-dots-fade shrink-0 text-4"></span>
|
||||||
|
</div>
|
||||||
|
|
||||||
<div data-action="toggle-dropdown"
|
<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)]"
|
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 { show, hide } = useTooltip();
|
||||||
const triggerRef = ref<HTMLElement | null>(null);
|
const triggerRef = ref<HTMLElement | null>(null);
|
||||||
|
|
||||||
const hasCursor = ref(false);
|
let hasCursor: boolean | null = null;
|
||||||
|
const checkHasCursor = () => {
|
||||||
onMounted(() => {
|
if (hasCursor === null && typeof window !== 'undefined') {
|
||||||
hasCursor.value = window.matchMedia('(hover: hover) and (pointer: fine)').matches;
|
hasCursor = window.matchMedia('(hover: hover) and (pointer: fine)').matches;
|
||||||
});
|
}
|
||||||
|
return hasCursor ?? false;
|
||||||
|
};
|
||||||
|
|
||||||
const onMouseEnter = () => {
|
const onMouseEnter = () => {
|
||||||
if (triggerRef.value && hasCursor.value) {
|
if (triggerRef.value && checkHasCursor()) {
|
||||||
show(triggerRef.value, props.hotkey, props.text);
|
show(triggerRef.value, props.hotkey, props.text);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,4 +1,6 @@
|
|||||||
|
import type { BaseMessage } from "~/composables/useChat";
|
||||||
import { nanoid } from "nanoid";
|
import { nanoid } from "nanoid";
|
||||||
|
import { provisionalTopicTitle } from "~~/utils/topic-title";
|
||||||
import { attempt } from "~~/types/result";
|
import { attempt } from "~~/types/result";
|
||||||
import * as schema from '~~/drizzle/schema';
|
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
|
// TODO: since topics are contained within each agent struct, all topic
|
||||||
// actions must be done through the agents composable
|
// actions must be done through the agents composable
|
||||||
const createTopic = async (agentId: string) => {
|
const createTopic = async (agentId: string, message?: BaseMessage) => {
|
||||||
const topicId = nanoid();
|
const topicId = nanoid();
|
||||||
const topic = {
|
const topic = {
|
||||||
id: topicId,
|
id: topicId,
|
||||||
name: 'New Topic',
|
name: provisionalTopicTitle(message),
|
||||||
agentId,
|
agentId,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -214,6 +216,9 @@ export const useAgents = async () => {
|
|||||||
agentId: agent.id,
|
agentId: agent.id,
|
||||||
userId: agent.userId,
|
userId: agent.userId,
|
||||||
renaming: false,
|
renaming: false,
|
||||||
|
renameAttemptId: null,
|
||||||
|
renameExpiresAt: null,
|
||||||
|
titleSource: "manual",
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
};
|
};
|
||||||
agents.value = agents.value.map(a =>
|
agents.value = agents.value.map(a =>
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
|||||||
let lastScrollTop = 0;
|
let lastScrollTop = 0;
|
||||||
let mutationRaf: number | null = null;
|
let mutationRaf: number | null = null;
|
||||||
let anchorRaf: number | null = null;
|
let anchorRaf: number | null = null;
|
||||||
|
let anchorDebounceTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||||
let observer: MutationObserver | null = null;
|
let observer: MutationObserver | null = null;
|
||||||
let resizeObserver: ResizeObserver | null = null;
|
let resizeObserver: ResizeObserver | null = null;
|
||||||
let lastWidth = 0;
|
let lastWidth = 0;
|
||||||
@@ -26,15 +27,25 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
|||||||
const setUnhooked = (value: boolean) => {
|
const setUnhooked = (value: boolean) => {
|
||||||
unhooked.value = value;
|
unhooked.value = value;
|
||||||
shouldAutoScroll.value = !value;
|
shouldAutoScroll.value = !value;
|
||||||
|
if (!value) anchor = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const scrollToBottom = (behavior: ScrollBehavior = 'instant') => {
|
const scrollToBottom = (behavior: ScrollBehavior = 'instant') => {
|
||||||
const el = elementRef.value;
|
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;
|
isProgrammatic = true;
|
||||||
el.scrollTo({
|
el.scrollTo({
|
||||||
top: el.scrollHeight,
|
top: bottom,
|
||||||
behavior,
|
behavior,
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -48,13 +59,19 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const captureAnchor = (el: HTMLElement) => {
|
const captureAnchor = (el: HTMLElement) => {
|
||||||
|
if (!unhooked.value) {
|
||||||
|
anchor = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
const rect = el.getBoundingClientRect();
|
const rect = el.getBoundingClientRect();
|
||||||
const x = rect.left + rect.width / 2;
|
const x = rect.left + rect.width / 2;
|
||||||
const offsets = [4, 24, 48, 80, 120];
|
const offsets = [4, 24, 48, 80, 120];
|
||||||
|
|
||||||
for (const y of offsets) {
|
for (const y of offsets) {
|
||||||
const target = document.elementFromPoint(x, rect.top + y);
|
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 = {
|
anchor = {
|
||||||
element: target,
|
element: target,
|
||||||
offsetFromTop: target.getBoundingClientRect().top - rect.top,
|
offsetFromTop: target.getBoundingClientRect().top - rect.top,
|
||||||
@@ -65,8 +82,8 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
|||||||
anchor = null;
|
anchor = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
const scheduleAnchorCapture = () => {
|
const requestAnchorCapture = () => {
|
||||||
if (anchorRaf !== null) return;
|
if (!unhooked.value || anchorRaf !== null) return;
|
||||||
anchorRaf = requestAnimationFrame(() => {
|
anchorRaf = requestAnimationFrame(() => {
|
||||||
anchorRaf = null;
|
anchorRaf = null;
|
||||||
const el = elementRef.value;
|
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) => {
|
const restoreAnchor = (el: HTMLElement) => {
|
||||||
if (!anchor || !el.contains(anchor.element)) return;
|
if (!anchor || !el.contains(anchor.element)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const top = el.getBoundingClientRect().top;
|
const top = el.getBoundingClientRect().top;
|
||||||
const delta =
|
const delta =
|
||||||
anchor.element.getBoundingClientRect().top - top - anchor.offsetFromTop;
|
anchor.element.getBoundingClientRect().top - top - anchor.offsetFromTop;
|
||||||
if (Math.abs(delta) < 0.5) return;
|
if (Math.abs(delta) < 0.5) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
isProgrammatic = true;
|
isProgrammatic = true;
|
||||||
el.scrollTop += delta;
|
el.scrollTop += delta;
|
||||||
@@ -99,37 +141,54 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
|||||||
|
|
||||||
const handleScroll = () => {
|
const handleScroll = () => {
|
||||||
const el = elementRef.value;
|
const el = elementRef.value;
|
||||||
if (!el) return;
|
if (!el) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const scrollingUp = el.scrollTop < lastScrollTop;
|
const scrollingUp = el.scrollTop < lastScrollTop;
|
||||||
lastScrollTop = el.scrollTop;
|
lastScrollTop = el.scrollTop;
|
||||||
|
|
||||||
scheduleAnchorCapture();
|
|
||||||
|
|
||||||
if (isProgrammatic) {
|
if (isProgrammatic) {
|
||||||
if (isAtBottom(el)) setUnhooked(false);
|
if (isAtBottom(el)) {
|
||||||
|
setUnhooked(false);
|
||||||
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only re-hook when actually inside the bottom threshold.
|
// If the user is scrolling up, they are deliberately navigating away from the bottom.
|
||||||
// Mid-page scroll (up or down) must never re-enable stick.
|
// 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)) {
|
if (isAtBottom(el)) {
|
||||||
setUnhooked(false);
|
setUnhooked(false);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
scheduleAnchorCapture();
|
||||||
if (scrollingUp) {
|
|
||||||
setUnhooked(true);
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const followIfHooked = () => {
|
const followIfHooked = () => {
|
||||||
if (unhooked.value) return;
|
if (unhooked.value) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
scrollToBottom('instant');
|
scrollToBottom('instant');
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleMutation = () => {
|
const handleMutation = (records: MutationRecord[]) => {
|
||||||
if (mutationRaf !== null) return;
|
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 = requestAnimationFrame(() => {
|
||||||
mutationRaf = null;
|
mutationRaf = null;
|
||||||
followIfHooked();
|
followIfHooked();
|
||||||
@@ -144,6 +203,7 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
|||||||
|
|
||||||
el.addEventListener('wheel', handleWheel, { passive: true });
|
el.addEventListener('wheel', handleWheel, { passive: true });
|
||||||
el.addEventListener('scroll', handleScroll, { passive: true });
|
el.addEventListener('scroll', handleScroll, { passive: true });
|
||||||
|
el.addEventListener('scrollend', handleScrollEnd, { passive: true });
|
||||||
|
|
||||||
observer = new MutationObserver(handleMutation);
|
observer = new MutationObserver(handleMutation);
|
||||||
observer.observe(el, {
|
observer.observe(el, {
|
||||||
@@ -154,7 +214,9 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
|||||||
|
|
||||||
resizeObserver = new ResizeObserver(() => {
|
resizeObserver = new ResizeObserver(() => {
|
||||||
const current = elementRef.value;
|
const current = elementRef.value;
|
||||||
if (!current) return;
|
if (!current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const width = current.clientWidth;
|
const width = current.clientWidth;
|
||||||
if (width === lastWidth) {
|
if (width === lastWidth) {
|
||||||
@@ -172,13 +234,18 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!anchor) {
|
||||||
|
captureAnchor(current);
|
||||||
|
}
|
||||||
restoreAnchor(current);
|
restoreAnchor(current);
|
||||||
});
|
});
|
||||||
resizeObserver.observe(el);
|
resizeObserver.observe(el);
|
||||||
|
|
||||||
// Content already taller than the viewport on mount — catch up once
|
// Content already taller than the viewport on mount — catch up once
|
||||||
requestAnimationFrame(() => {
|
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) {
|
if (el) {
|
||||||
el.removeEventListener('wheel', handleWheel);
|
el.removeEventListener('wheel', handleWheel);
|
||||||
el.removeEventListener('scroll', handleScroll);
|
el.removeEventListener('scroll', handleScroll);
|
||||||
|
el.removeEventListener('scrollend', handleScrollEnd);
|
||||||
}
|
}
|
||||||
observer?.disconnect();
|
observer?.disconnect();
|
||||||
observer = null;
|
observer = null;
|
||||||
@@ -199,12 +267,18 @@ export function useAutoScroll(elementRef: Ref<HTMLElement | null>, options: {
|
|||||||
cancelAnimationFrame(anchorRaf);
|
cancelAnimationFrame(anchorRaf);
|
||||||
anchorRaf = null;
|
anchorRaf = null;
|
||||||
}
|
}
|
||||||
|
if (anchorDebounceTimeout !== null) {
|
||||||
|
clearTimeout(anchorDebounceTimeout);
|
||||||
|
anchorDebounceTimeout = null;
|
||||||
|
}
|
||||||
anchor = null;
|
anchor = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
watch(elementRef, (newEl, oldEl) => {
|
watch(elementRef, (newEl, oldEl) => {
|
||||||
detach(oldEl ?? null);
|
detach(oldEl ?? null);
|
||||||
if (newEl) attach(newEl);
|
if (newEl) {
|
||||||
|
attach(newEl);
|
||||||
|
}
|
||||||
}, { immediate: true });
|
}, { immediate: true });
|
||||||
|
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
|
|||||||
+159
-50
@@ -1,7 +1,9 @@
|
|||||||
import { nanoid } from 'nanoid';
|
import { nanoid } from 'nanoid';
|
||||||
|
import { toRaw } from 'vue';
|
||||||
import * as schema from '~~/drizzle/schema';
|
import * as schema from '~~/drizzle/schema';
|
||||||
import { Err, Ok, type Result } from '~~/types/result';
|
import { Err, Ok, type Result } from '~~/types/result';
|
||||||
import { buildMessageTree } from '~~/utils/message';
|
import { buildMessageTree } from '~~/utils/message';
|
||||||
|
import { appendTextDelta, serializeTopicSnapshot } from '~~/utils/topic-sync';
|
||||||
|
|
||||||
export type BaseMessage = {
|
export type BaseMessage = {
|
||||||
content: string;
|
content: string;
|
||||||
@@ -38,7 +40,7 @@ export enum ChatErrorType {
|
|||||||
Unimplemented,
|
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;
|
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 data = useState<Topic & { messages: Message[] } | undefined>('useChat:data', () => undefined);
|
||||||
|
|
||||||
let sse: EventSource | 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, {
|
const textDeltaBuffer: Map<string, Map<string, {
|
||||||
content: string;
|
content: string;
|
||||||
@@ -64,7 +70,7 @@ export const useChat = async (topicId: MaybeRef<string>, connect = true) => {
|
|||||||
for (const [partId, content] of parts) {
|
for (const [partId, content] of parts) {
|
||||||
const part = msg.parts?.find(p => p.id === partId);
|
const part = msg.parts?.find(p => p.id === partId);
|
||||||
if (part) {
|
if (part) {
|
||||||
part.content += content.content;
|
part.content = content.content;
|
||||||
part.lastUpdatedAt = new Date(content.lastUpdatedAt);
|
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);
|
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) => {
|
const processEvent = (event: Event) => {
|
||||||
if (!data.value) return;
|
if (!data.value) return;
|
||||||
|
|
||||||
@@ -102,12 +125,17 @@ export const useChat = async (topicId: MaybeRef<string>, connect = true) => {
|
|||||||
case 'MESSAGE_CREATED': {
|
case 'MESSAGE_CREATED': {
|
||||||
// Push the new message if it doesn't exist (prevents duplicates from HTTP vs SSE)
|
// 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)) {
|
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 {
|
} else {
|
||||||
// replace the existing data with the new data
|
// replace the existing data with the new data
|
||||||
const index = data.value.messages.findIndex(m => m.id === payload.id);
|
const index = data.value.messages.findIndex(m => m.id === payload.id);
|
||||||
if (index !== -1) {
|
if (index !== -1 && !event.replay) {
|
||||||
data.value.messages[index] = { ...payload, parts: [] };
|
const existing = data.value.messages[index]!;
|
||||||
|
data.value.messages[index] = {
|
||||||
|
...payload,
|
||||||
|
parts: payload.parts ?? [],
|
||||||
|
attachments: payload.attachments ?? existing.attachments ?? [],
|
||||||
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
@@ -130,26 +158,43 @@ export const useChat = async (topicId: MaybeRef<string>, connect = true) => {
|
|||||||
const msg = data.value.messages.find(m => m.id === payload.messageId);
|
const msg = data.value.messages.find(m => m.id === payload.messageId);
|
||||||
if (msg) {
|
if (msg) {
|
||||||
if (!msg.parts) msg.parts = [];
|
if (!msg.parts) msg.parts = [];
|
||||||
|
if (!msg.parts.some(part => part.id === payload.part.id)) {
|
||||||
msg.parts.push(payload.part);
|
msg.parts.push(payload.part);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'text-delta': {
|
case 'text-delta': {
|
||||||
const msg = data.value.messages.find(m => m.id === payload.messageId);
|
const msg = data.value.messages.find(m => m.id === payload.messageId);
|
||||||
if (!msg) break;
|
if (!msg) break;
|
||||||
|
const part = msg.parts?.find(part => part.id === payload.partId);
|
||||||
|
if (!part || part.finished) break;
|
||||||
|
|
||||||
if (!textDeltaBuffer.has(payload.messageId)) {
|
if (!textDeltaBuffer.has(payload.messageId)) {
|
||||||
textDeltaBuffer.set(payload.messageId, new Map());
|
textDeltaBuffer.set(payload.messageId, new Map());
|
||||||
}
|
}
|
||||||
const messageBuffer = textDeltaBuffer.get(payload.messageId)!;
|
const messageBuffer = textDeltaBuffer.get(payload.messageId)!;
|
||||||
const existing = messageBuffer.get(payload.partId)?.content || '';
|
const existing = messageBuffer.get(payload.partId)?.content ?? part.content ?? '';
|
||||||
messageBuffer.set(payload.partId, { content: existing + payload.content, lastUpdatedAt: payload.lastUpdatedAt });
|
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();
|
scheduleFlush();
|
||||||
break;
|
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': {
|
case 'text-end': {
|
||||||
const msg = data.value.messages.find(m => m.id === payload.messageId);
|
const msg = data.value.messages.find(m => m.id === payload.messageId);
|
||||||
const part = msg?.parts?.find(p => p.id === payload.partId);
|
const part = msg?.parts?.find(p => p.id === payload.partId);
|
||||||
@@ -175,8 +220,10 @@ export const useChat = async (topicId: MaybeRef<string>, connect = true) => {
|
|||||||
if (!part.createdAt) {
|
if (!part.createdAt) {
|
||||||
part.createdAt = new Date().toISOString();
|
part.createdAt = new Date().toISOString();
|
||||||
}
|
}
|
||||||
|
if (!msg.parts.some(existing => existing.id === part.id)) {
|
||||||
msg.parts.push(part);
|
msg.parts.push(part);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -229,55 +276,79 @@ export const useChat = async (topicId: MaybeRef<string>, connect = true) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const connectSSE = async () => {
|
const connectSSE = async (forceSnapshot = false) => {
|
||||||
const { promise, resolve } = Promise.withResolvers<void>();
|
if (disposed) return;
|
||||||
|
const attempt = ++connectionAttempt;
|
||||||
const id = unref(topicId);
|
const id = unref(topicId);
|
||||||
const lastUpdate = data.value?.messages.at(-1)?.updatedAt || '0';
|
sse?.close();
|
||||||
const msgCount = data.value?.messages.length || 0;
|
if (flushTimeout !== undefined) {
|
||||||
|
clearTimeout(flushTimeout);
|
||||||
if (sse && sse.readyState !== EventSource.CLOSED) {
|
flushTextDeltas();
|
||||||
if (!(new URL(sse.url).pathname.startsWith(`/api/topic/${id}`))) {
|
}
|
||||||
sse.close();
|
let offeredSnapshot: string | undefined;
|
||||||
} else {
|
const query = new URLSearchParams();
|
||||||
return;
|
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) => {
|
source.addEventListener('message', (e) => {
|
||||||
console.error('sse error', e);
|
if (disposed || sse !== source) return;
|
||||||
setTimeout(connectSSE, 1500);
|
|
||||||
})
|
|
||||||
|
|
||||||
sse.addEventListener("message", (e) => {
|
|
||||||
const raw = JSON.parse(e.data);
|
const raw = JSON.parse(e.data);
|
||||||
const events: Event[] = Array.isArray(raw) ? raw : [raw];
|
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 || !payload) continue;
|
||||||
|
|
||||||
if (type === 'initial_state') {
|
if (type === 'synced') {
|
||||||
data.value = payload;
|
// Optimistic edits can occur while the handshake is in flight.
|
||||||
resolve()
|
// Only retain the exact state that we offered to the server.
|
||||||
|
if (offeredSnapshot !== serializeTopicSnapshot(toRaw(data.value))) {
|
||||||
|
scheduleReconnect(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
offeredSnapshot = undefined;
|
||||||
|
markConnected();
|
||||||
continue;
|
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) {
|
if (connect) {
|
||||||
onBeforeUnmount(() => {
|
onBeforeUnmount(() => {
|
||||||
if (flushTimeout) {
|
disposed = true;
|
||||||
clearTimeout(flushTimeout);
|
connectionAttempt++;
|
||||||
flushTextDeltas();
|
if (reconnectTimeout !== undefined) clearTimeout(reconnectTimeout);
|
||||||
}
|
resetTextDeltas();
|
||||||
|
markConnected();
|
||||||
if (sse) {
|
if (sse) {
|
||||||
console.log('[SSE] Closing connection');
|
console.log('[SSE] Closing connection');
|
||||||
sse.close();
|
sse.close();
|
||||||
@@ -525,38 +596,76 @@ export const useChat = async (topicId: MaybeRef<string>, connect = true) => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const deleteMessagesFocusedDescendant = async (messageId: string): Promise<Result<void, Error>> => {
|
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);
|
const msg = data.value.messages.find((m) => {
|
||||||
if (!msg) return Err(new Error('Message not found'));
|
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}`, {
|
const res = await $fetch(`/api/messages/${messageId}`, {
|
||||||
method: 'DELETE',
|
method: "DELETE",
|
||||||
onRequest() {
|
onRequest() {
|
||||||
if (!msg.activeChildId && (msg.parentMessageId === null || msg.parentMessageId === undefined)) {
|
if (!data.value) {
|
||||||
msg.deleted = true;
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const parent = data.value!.messages.find(m => m.id === msg.parentMessageId);
|
if (msg.parentMessageId) {
|
||||||
data.value!.messages = data.value!.messages.filter(m => m.id !== msg.id);
|
const parent = data.value.messages.find((m) => {
|
||||||
if (parent?.deleted) {
|
return m.id === msg.parentMessageId;
|
||||||
data.value!.messages = data.value!.messages.filter(m => m.id !== parent.id);
|
});
|
||||||
|
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() {
|
onResponseError() {
|
||||||
data.value!.messages = previousMessages;
|
if (data.value) {
|
||||||
|
data.value.messages = previousMessages;
|
||||||
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
return Err(new Error('Failed to delete message'));
|
return Err(new Error("Failed to delete message"));
|
||||||
}
|
}
|
||||||
|
|
||||||
return Ok(undefined);
|
return Ok(undefined);
|
||||||
}
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
topic,
|
topic,
|
||||||
|
|||||||
@@ -8,8 +8,6 @@ export const useTokenDropdown = () => {
|
|||||||
const triggerElement = useState<HTMLElement | null>('token-dropdown:trigger', () => null);
|
const triggerElement = useState<HTMLElement | null>('token-dropdown:trigger', () => null);
|
||||||
|
|
||||||
const open = (generation: Generation, trigger: HTMLElement) => {
|
const open = (generation: Generation, trigger: HTMLElement) => {
|
||||||
console.log("open", generation, trigger);
|
|
||||||
|
|
||||||
activeGeneration.value = generation;
|
activeGeneration.value = generation;
|
||||||
triggerElement.value = trigger;
|
triggerElement.value = trigger;
|
||||||
isOpen.value = true;
|
isOpen.value = true;
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ export const useTopic = () => {
|
|||||||
FailedToDecryptProviderApiKey,
|
FailedToDecryptProviderApiKey,
|
||||||
FailedToGenerate,
|
FailedToGenerate,
|
||||||
}
|
}
|
||||||
const autoRename = async (topicId: string): Promise<Result<string, AutoRenameError>> => {
|
const autoRename = async (topicId: string): Promise<Result<void, AutoRenameError>> => {
|
||||||
const { settings } = await useUserSettings();
|
const { settings } = await useUserSettings();
|
||||||
|
|
||||||
if (!settings.value.systemAssistants.rename.enabled) {
|
if (!settings.value.systemAssistants.rename.enabled) {
|
||||||
@@ -54,7 +54,7 @@ export const useTopic = () => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const { agents } = await useAgents();
|
const { patchTopicLocally, refresh } = await useAgents();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// @ts-ignore - excessive stack depth
|
// @ts-ignore - excessive stack depth
|
||||||
@@ -65,31 +65,20 @@ export const useTopic = () => {
|
|||||||
providerApiKey,
|
providerApiKey,
|
||||||
}),
|
}),
|
||||||
onRequest() {
|
onRequest() {
|
||||||
const topics = agents.value.flatMap(agent => agent.topics);
|
patchTopicLocally(topicId, { renaming: true });
|
||||||
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;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
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) {
|
if (!res.ok) {
|
||||||
|
patchTopicLocally(topicId, { renaming: false });
|
||||||
|
await refresh();
|
||||||
console.error('Failed to auto-rename:', res.code);
|
console.error('Failed to auto-rename:', res.code);
|
||||||
return Err(AutoRenameError.FailedToGenerate);
|
return Err(AutoRenameError.FailedToGenerate);
|
||||||
}
|
}
|
||||||
|
|
||||||
return Ok(res.renameId);
|
return Ok(undefined);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
patchTopicLocally(topicId, { renaming: false });
|
||||||
|
await refresh();
|
||||||
console.error('Failed to auto-rename:', error);
|
console.error('Failed to auto-rename:', error);
|
||||||
return Err(AutoRenameError.FailedToGenerate);
|
return Err(AutoRenameError.FailedToGenerate);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
export const useUserEvents = () => {
|
export const useUserEvents = () => {
|
||||||
const eventSource = ref<EventSource | null>(null);
|
const eventSource = ref<EventSource | null>(null);
|
||||||
|
const agents = useState<AgentWithTopics[]>("agents_state", () => []);
|
||||||
const isConnected = useState('userEvents:connected', () => false);
|
const isConnected = useState('userEvents:connected', () => false);
|
||||||
const lastEventTimestamp = useState<number>('userEvents:lastTimestamp', () => 0);
|
const lastEventTimestamp = useState<number>('userEvents:lastTimestamp', () => 0);
|
||||||
|
|
||||||
const reconnectAttempts = ref(0);
|
const reconnectAttempts = ref(0);
|
||||||
const connectionStartTime = ref<number>(0);
|
const connectionStartTime = ref<number>(0);
|
||||||
const pendingReconnect = ref<NodeJS.Timeout | null>(null);
|
const pendingReconnect = ref<NodeJS.Timeout | null>(null);
|
||||||
|
let reconciliationTimer: ReturnType<typeof setInterval> | undefined;
|
||||||
|
let reconciling = false;
|
||||||
|
|
||||||
const BASE_DELAY = 1000;
|
const BASE_DELAY = 1000;
|
||||||
const MAX_DELAY = 30000;
|
const MAX_DELAY = 30000;
|
||||||
@@ -50,7 +53,6 @@ export const useUserEvents = () => {
|
|||||||
cleanup();
|
cleanup();
|
||||||
|
|
||||||
connectionStartTime.value = Date.now();
|
connectionStartTime.value = Date.now();
|
||||||
reconnectAttempts.value = 0;
|
|
||||||
|
|
||||||
const source = new EventSource('/api/events');
|
const source = new EventSource('/api/events');
|
||||||
eventSource.value = source;
|
eventSource.value = source;
|
||||||
@@ -59,6 +61,7 @@ export const useUserEvents = () => {
|
|||||||
console.log('User events connected');
|
console.log('User events connected');
|
||||||
isConnected.value = true;
|
isConnected.value = true;
|
||||||
reconnectAttempts.value = 0;
|
reconnectAttempts.value = 0;
|
||||||
|
void reconcile();
|
||||||
};
|
};
|
||||||
|
|
||||||
source.onerror = () => {
|
source.onerror = () => {
|
||||||
@@ -164,20 +167,48 @@ export const useUserEvents = () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const reconcile = async () => {
|
const reconcile = async () => {
|
||||||
console.log('Reconciling user state...');
|
if (reconciling) {
|
||||||
const { data } = await useFetch<AgentWithTopics[]>('/api/agents');
|
return;
|
||||||
if (data.value) {
|
}
|
||||||
const { agents } = await useAgents();
|
reconciling = true;
|
||||||
agents.value = data.value;
|
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(() => {
|
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(() => {
|
onBeforeUnmount(() => {
|
||||||
cleanup();
|
cleanup();
|
||||||
|
clearInterval(reconciliationTimer);
|
||||||
|
document.removeEventListener("visibilitychange", resume);
|
||||||
|
window.removeEventListener("online", resume);
|
||||||
|
window.removeEventListener("pageshow", resume);
|
||||||
});
|
});
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -18,8 +18,7 @@ useHead({
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (import.meta.client) {
|
if (import.meta.client) {
|
||||||
const { connect } = useUserEvents();
|
useUserEvents();
|
||||||
connect();
|
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -28,7 +27,7 @@ if (import.meta.client) {
|
|||||||
<div class="p-2 w-full h-full max-w-full overflow-x-hidden">
|
<div class="p-2 w-full h-full max-w-full overflow-x-hidden">
|
||||||
<main
|
<main
|
||||||
class="bg-[var(--bg-surface)] flex flex-col h-full w-full border border-solid border-[var(--color-border)] rounded-lg overflow-hidden">
|
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 />
|
<slot />
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
|
|||||||
@@ -66,7 +66,7 @@ const handleSubmit = async (message: BaseMessage, model: ModelWithProvider | nul
|
|||||||
updatedAt: new Date(),
|
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');
|
if (!topic) throw new Error('Failed to create topic');
|
||||||
|
|
||||||
const { sendMessage, startGeneration } = await useChat(topic.id, false);
|
const { sendMessage, startGeneration } = await useChat(topic.id, false);
|
||||||
@@ -100,7 +100,7 @@ const handleAddMessage = async (message: BaseMessage, role: 'user' | 'assistant'
|
|||||||
return;
|
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');
|
if (!topic) throw new Error('Failed to create topic');
|
||||||
|
|
||||||
const { sendMessage } = await useChat(topic.id, false);
|
const { sendMessage } = await useChat(topic.id, false);
|
||||||
@@ -118,7 +118,8 @@ const handleAddMessage = async (message: BaseMessage, role: 'user' | 'assistant'
|
|||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="flex flex-col h-full w-full max-w-full overflow-x-hidden">
|
<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">
|
<div class="flex items-center gap-2 max-w-full">
|
||||||
<button v-if="!sidebarOpen" @click="openSidebar"
|
<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">
|
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>
|
||||||
|
|
||||||
<div ref="chatPaneWrapper"
|
<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="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"
|
<div class="w-full px-px flex flex-col flex-grow gap-2"
|
||||||
:class="pendingMessage === null ? 'justify-end pb-28' : 'pb-9'">
|
:class="pendingMessage === null ? 'justify-end pb-28' : 'pb-9'">
|
||||||
|
|||||||
@@ -1,9 +1,7 @@
|
|||||||
<script setup lang="ts">
|
<script setup lang="ts">
|
||||||
import { type BaseMessage, type Message, ChatErrorType } from '~/composables/useChat';
|
import { type BaseMessage, type Message, ChatErrorType } from '~/composables/useChat';
|
||||||
import type { ModelWithProvider } from '~/composables/useModels';
|
import type { ModelWithProvider } from '~/composables/useModels';
|
||||||
import { buildFocusedMessageTree } from '~~/utils/message';
|
import { buildFocusedMessageTree, getActiveMessage, getNextActiveChildId } from '~~/utils/message';
|
||||||
|
|
||||||
const rootStart = Date.now();
|
|
||||||
|
|
||||||
const chatPaneWrapper = ref<HTMLElement | null>(null);
|
const chatPaneWrapper = ref<HTMLElement | null>(null);
|
||||||
const inputValue = ref<BaseMessage>({ content: '', fileIds: [] });
|
const inputValue = ref<BaseMessage>({ content: '', fileIds: [] });
|
||||||
@@ -81,11 +79,10 @@ const handleRegenerate = async (message: Message) => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let messageId: string;
|
const activeMsg = getActiveMessage(message);
|
||||||
if (message.activeChildId && message.children.length > 0) {
|
if (!activeMsg) {
|
||||||
messageId = message.activeChildId;
|
console.error('No active message');
|
||||||
} else {
|
return;
|
||||||
messageId = message.id;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const model = allModels.value.find(m => m.id === agent.value!.defaultModelId);
|
const model = allModels.value.find(m => m.id === agent.value!.defaultModelId);
|
||||||
@@ -94,20 +91,26 @@ const handleRegenerate = async (message: Message) => {
|
|||||||
return;
|
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) {
|
if (!res.ok) {
|
||||||
console.error('Failed to regenerate message:', ChatErrorType[res.error]);
|
console.error('Failed to regenerate message:', ChatErrorType[res.error]);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const flatMessages = computed(() => {
|
const flatMessages = computed(() => {
|
||||||
const messages: Message[] = [];
|
const messages: Message[] = [];
|
||||||
|
|
||||||
for (const message of topic.value?.messages ?? []) {
|
for (const message of topic.value?.messages ?? []) {
|
||||||
|
if (!message.deleted) {
|
||||||
messages.push(message);
|
messages.push(message);
|
||||||
|
}
|
||||||
if (message.children.length > 0) {
|
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 handleFork = async (message: Message) => {
|
||||||
const messageId = message.activeChildId && message.children.length > 0
|
const activeMsg = getActiveMessage(message);
|
||||||
? message.activeChildId
|
if (!activeMsg) {
|
||||||
: message.id;
|
console.error('No active message');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const newTopicId = await forkTopic(topicId.value, messageId);
|
const newTopicId = await forkTopic(topicId.value, activeMsg.id);
|
||||||
if (newTopicId) {
|
if (newTopicId) {
|
||||||
await navigateTo(`/agent/${route.params.id}/topic/${newTopicId}`);
|
await navigateTo(`/agent/${route.params.id}/topic/${newTopicId}`);
|
||||||
} else {
|
} else {
|
||||||
@@ -128,14 +133,12 @@ const handleFork = async (message: Message) => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handleDelete = async (rootMessage: Message) => {
|
const handleDelete = async (rootMessage: Message) => {
|
||||||
let messageId: string;
|
const activeMsg = getActiveMessage(rootMessage);
|
||||||
if (rootMessage.activeChildId && rootMessage.children.length > 0) {
|
if (!activeMsg) {
|
||||||
messageId = rootMessage.activeChildId;
|
return;
|
||||||
} else {
|
|
||||||
messageId = rootMessage.id;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const result = await deleteMessagesFocusedDescendant(messageId);
|
const result = await deleteMessagesFocusedDescendant(activeMsg.id);
|
||||||
if (!result.ok) {
|
if (!result.ok) {
|
||||||
console.error('Failed to delete message:', result.error);
|
console.error('Failed to delete message:', result.error);
|
||||||
return;
|
return;
|
||||||
@@ -145,7 +148,7 @@ const handleDelete = async (rootMessage: Message) => {
|
|||||||
await navigateTo(`/agent/${route.params.id}`);
|
await navigateTo(`/agent/${route.params.id}`);
|
||||||
deleteTopic(route.params.id as string, topicId.value);
|
deleteTopic(route.params.id as string, topicId.value);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
const { scrollToBottom, isAtBottom } = useAutoScroll(chatPaneWrapper);
|
const { scrollToBottom, isAtBottom } = useAutoScroll(chatPaneWrapper);
|
||||||
|
|
||||||
@@ -198,76 +201,39 @@ addShortcut(['ctrl', 'shift', 'c'], (event) => {
|
|||||||
handleCancel();
|
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.preventDefault();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
|
navigateLastMessage(-1);
|
||||||
|
});
|
||||||
|
|
||||||
const lastMessage = topic.value?.messages?.at(-1);
|
addShortcut(['ctrl', 'alt', 'arrowleft'], (event) => {
|
||||||
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) => {
|
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
|
navigateLastMessage(-1);
|
||||||
|
});
|
||||||
|
|
||||||
const lastMessage = topic.value?.messages?.at(-1);
|
addShortcut(['alt', ']'], (event) => {
|
||||||
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);
|
|
||||||
|
|
||||||
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.preventDefault();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
|
navigateLastMessage(1);
|
||||||
|
});
|
||||||
|
|
||||||
const currentIdx = lastMessage.children.findIndex(c => c?.id === lastMessage.activeChildId);
|
addShortcut(['ctrl', 'alt', 'arrowright'], (event) => {
|
||||||
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.preventDefault();
|
||||||
event.stopPropagation();
|
event.stopPropagation();
|
||||||
|
navigateLastMessage(1);
|
||||||
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', 'backspace'], async (event) => {
|
addShortcut(['ctrl', 'alt', 'backspace'], async (event) => {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
@@ -287,13 +253,12 @@ const handleCancel = async () => {
|
|||||||
method: 'POST',
|
method: 'POST',
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log("full page render took", Date.now() - rootStart);
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div class="flex flex-col h-full w-full max-w-full overflow-x-hidden">
|
<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">
|
<div class="flex items-center gap-2 max-w-full">
|
||||||
<button v-if="!sidebarOpen" @click="openSidebar"
|
<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">
|
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 -->
|
<!-- chat pane -->
|
||||||
<div ref="chatPaneWrapper"
|
<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="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">
|
<div class="w-full px-px flex flex-col flex-grow gap-2 pb-9">
|
||||||
<Suspense>
|
<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) {
|
if (!topic) {
|
||||||
console.error('Failed to create topic');
|
console.error('Failed to create topic');
|
||||||
return;
|
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));
|
||||||
|
};
|
||||||
+62
-51
@@ -3,6 +3,7 @@ import { createSerializedMarkdownParser as createComarkParser } from 'comark';
|
|||||||
import breaks from 'comark/plugins/breaks';
|
import breaks from 'comark/plugins/breaks';
|
||||||
import footnotes from 'comark/plugins/footnotes';
|
import footnotes from 'comark/plugins/footnotes';
|
||||||
import math from 'comark/plugins/math';
|
import math from 'comark/plugins/math';
|
||||||
|
import { citationPlugin } from './citations';
|
||||||
|
|
||||||
export type MarkdownTree = MarkdownDocument;
|
export type MarkdownTree = MarkdownDocument;
|
||||||
export type MarkdownAstNode = Node;
|
export type MarkdownAstNode = Node;
|
||||||
@@ -39,10 +40,10 @@ const parserPlugins = [
|
|||||||
math(),
|
math(),
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
const createConfiguredParser = (autoClose: boolean) => createComarkParser({
|
const createConfiguredParser = (autoClose: boolean, citations: boolean) => createComarkParser({
|
||||||
registerDefaultPlugins: false,
|
registerDefaultPlugins: false,
|
||||||
autoClose,
|
autoClose,
|
||||||
plugins: parserPlugins,
|
plugins: citations ? [...parserPlugins, citationPlugin] : parserPlugins,
|
||||||
});
|
});
|
||||||
|
|
||||||
const protectDollarRunsInLine = (line: string): string => {
|
const protectDollarRunsInLine = (line: string): string => {
|
||||||
@@ -89,6 +90,10 @@ const protectDollarRunsInLine = (line: string): string => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const protectDollarRuns = (content: 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');
|
const lines = content.split('\n');
|
||||||
let inFence = false;
|
let inFence = false;
|
||||||
|
|
||||||
@@ -107,13 +112,16 @@ const protectDollarRuns = (content: string): string => {
|
|||||||
}).join('\n');
|
}).join('\n');
|
||||||
};
|
};
|
||||||
|
|
||||||
export const createMarkdownParser = () => {
|
export const createMarkdownParser = (options: { citations?: boolean } = {}) => {
|
||||||
const streamingParser = createConfiguredParser(true);
|
const citations = options.citations === true;
|
||||||
const finalParser = createConfiguredParser(false);
|
const streamingParser = createConfiguredParser(true, citations);
|
||||||
|
const finalParser = createConfiguredParser(false, citations);
|
||||||
|
|
||||||
return (content: string, options: { streaming?: boolean } = {}) => {
|
return (content: string, options: { streaming?: boolean } = {}) => {
|
||||||
const protectedContent = protectDollarRuns(content);
|
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 });
|
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 => {
|
export const getNodeTag = (node: MarkdownAstNode): string | null => {
|
||||||
if (!Array.isArray(node) || node[0] === null) {
|
if (!Array.isArray(node) || node[0] === null) {
|
||||||
return null;
|
return null;
|
||||||
@@ -157,29 +168,7 @@ export const textContent = (node: MarkdownAstNode): string => {
|
|||||||
return getNodeChildren(node).map(textContent).join('');
|
return getNodeChildren(node).map(textContent).join('');
|
||||||
};
|
};
|
||||||
|
|
||||||
const cloneNode = (node: MarkdownAstNode): MarkdownAstNode => {
|
const splitParagraph = (attributes: Record<string, unknown>, children: MarkdownAstNode[]): MarkdownElementNode[] => {
|
||||||
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 paragraphs: MarkdownElementNode[] = [];
|
const paragraphs: MarkdownElementNode[] = [];
|
||||||
let current: MarkdownAstNode[] = [];
|
let current: MarkdownAstNode[] = [];
|
||||||
|
|
||||||
@@ -200,26 +189,28 @@ const splitParagraph = (node: MarkdownElementNode): MarkdownElementNode[] => {
|
|||||||
return paragraphs;
|
return paragraphs;
|
||||||
};
|
};
|
||||||
|
|
||||||
const transformChildren = (nodes: MarkdownAstNode[]): MarkdownAstNode[] => {
|
const hasBrChild = (children: MarkdownAstNode[]): boolean =>
|
||||||
const result: MarkdownAstNode[] = [];
|
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 tag = node[0];
|
||||||
const transformedChildren = transformChildren(getNodeChildren(node));
|
const children = getNodeChildren(node);
|
||||||
let transformedNode = [tag, { ...node[1] }, ...transformedChildren] as MarkdownElementNode;
|
const transformedChildren = transformChildren(children);
|
||||||
|
|
||||||
if (tag === 'p') {
|
if (tag === 'p') {
|
||||||
result.push(...splitParagraph(transformedNode));
|
if (!hasBrChild(transformedChildren)) {
|
||||||
continue;
|
if (transformedChildren === children) return [node];
|
||||||
|
return [[tag, { ...node[1] }, ...transformedChildren] as MarkdownElementNode];
|
||||||
|
}
|
||||||
|
return splitParagraph({ ...node[1] }, transformedChildren);
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((tag === 'li' || tag === 'blockquote') && transformedChildren.some((child) => getNodeTag(child) === 'br')) {
|
if ((tag === 'li' || tag === 'blockquote') && hasBrChild(transformedChildren)) {
|
||||||
const segments: MarkdownAstNode[][] = [[]];
|
const segments: MarkdownAstNode[][] = [[]];
|
||||||
for (const child of transformedChildren) {
|
for (const child of transformedChildren) {
|
||||||
if (getNodeTag(child) === 'br') {
|
if (getNodeTag(child) === 'br') {
|
||||||
@@ -229,29 +220,49 @@ const transformChildren = (nodes: MarkdownAstNode[]): MarkdownAstNode[] => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
transformedNode = [
|
return [[
|
||||||
tag,
|
tag,
|
||||||
{ ...node[1] },
|
{ ...node[1] },
|
||||||
...segments
|
...segments
|
||||||
.filter((segment) => segment.length > 0)
|
.filter((segment) => segment.length > 0)
|
||||||
.map((segment) => ['p', {}, ...segment] as MarkdownElementNode),
|
.map((segment) => ['p', {}, ...segment] as MarkdownElementNode),
|
||||||
] as MarkdownElementNode;
|
] as MarkdownElementNode];
|
||||||
}
|
}
|
||||||
|
|
||||||
result.push(transformedNode);
|
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;
|
return result ?? nodes;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Comark's breaks plugin emits `br` nodes. Promote each hard break to a
|
* Comark's breaks plugin emits `br` nodes. Promote each hard break to a
|
||||||
* sibling paragraph to keep the chat renderer's established layout.
|
* 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 => ({
|
export const splitParagraphBreaks = (tree: MarkdownTree): MarkdownTree => {
|
||||||
...tree,
|
const nodes = transformChildren(tree.nodes);
|
||||||
nodes: transformChildren(tree.nodes),
|
return nodes === tree.nodes ? tree : { ...tree, nodes };
|
||||||
});
|
};
|
||||||
|
|
||||||
export const toVueAttributes = (attributes: Record<string, unknown>): Record<string, unknown> => {
|
export const toVueAttributes = (attributes: Record<string, unknown>): Record<string, unknown> => {
|
||||||
const result: Record<string, unknown> = {};
|
const result: Record<string, unknown> = {};
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ export const formatToolValue = (stored: StoredToolValue): string => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export interface SearchSource {
|
export interface SearchSource {
|
||||||
|
sourceId?: string;
|
||||||
title: string;
|
title: string;
|
||||||
url: string;
|
url: string;
|
||||||
hostname: 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.
|
// Older tool calls stored the results array directly.
|
||||||
if (typeof value === "object" && value !== null && "results" in value) {
|
if (typeof value === "object" && value !== null && "results" in value) {
|
||||||
value = value.results;
|
value = value.results;
|
||||||
@@ -65,11 +66,12 @@ export const readSearchSources = (value: unknown): SearchSource[] | null => {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
url.hash = "";
|
url.hash = "";
|
||||||
if (seen.has(url.href)) {
|
if (options.deduplicate !== false && seen.has(url.href)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
seen.add(url.href);
|
seen.add(url.href);
|
||||||
sources.push({
|
sources.push({
|
||||||
|
...("sourceId" in item && typeof item.sourceId === "string" ? { sourceId: item.sourceId } : {}),
|
||||||
title: "title" in item && typeof item.title === "string" ? item.title : url.hostname,
|
title: "title" in item && typeof item.title === "string" ? item.title : url.hostname,
|
||||||
url: url.href,
|
url: url.href,
|
||||||
hostname: url.hostname,
|
hostname: url.hostname,
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
ALTER TABLE "topics" ADD COLUMN "rename_attempt_id" text;
|
||||||
|
--> statement-breakpoint
|
||||||
|
ALTER TABLE "topics" ADD COLUMN "rename_expires_at" timestamp with time zone;
|
||||||
|
--> statement-breakpoint
|
||||||
|
ALTER TABLE "topics" ADD COLUMN "title_source" text DEFAULT 'manual' NOT NULL;
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -122,6 +122,9 @@ export const topics = pgTable('topics', {
|
|||||||
agentId: text('agent_id').notNull().references(() => agents.id, { onDelete: 'cascade' }),
|
agentId: text('agent_id').notNull().references(() => agents.id, { onDelete: 'cascade' }),
|
||||||
name: text('name').notNull(),
|
name: text('name').notNull(),
|
||||||
renaming: boolean('renaming').default(false),
|
renaming: boolean('renaming').default(false),
|
||||||
|
renameAttemptId: text('rename_attempt_id'),
|
||||||
|
renameExpiresAt: timestamptz('rename_expires_at'),
|
||||||
|
titleSource: text('title_source').notNull().default('manual'),
|
||||||
createdAt: timestamptz('created_at').notNull().defaultNow(),
|
createdAt: timestamptz('created_at').notNull().defaultNow(),
|
||||||
}, (table) => [
|
}, (table) => [
|
||||||
index('topics_agentId_idx').on(table.agentId),
|
index('topics_agentId_idx').on(table.agentId),
|
||||||
|
|||||||
@@ -1,9 +1,22 @@
|
|||||||
|
import { and, eq, isNull, lte, or } from "drizzle-orm";
|
||||||
|
import { topics } from "~~/drizzle/schema";
|
||||||
import { db } from "~~/server/lib/db";
|
import { db } from "~~/server/lib/db";
|
||||||
|
|
||||||
export default defineEventHandler(async (event) => {
|
export default defineEventHandler(async (event) => {
|
||||||
await protectRoute(event);
|
await protectRoute(event);
|
||||||
const userId = event.context.user!.id as string;
|
const userId = event.context.user!.id as string;
|
||||||
|
|
||||||
|
// Expired leases also recover jobs interrupted by a server restart.
|
||||||
|
await db.update(topics).set({
|
||||||
|
renaming: false,
|
||||||
|
renameAttemptId: null,
|
||||||
|
renameExpiresAt: null,
|
||||||
|
}).where(and(
|
||||||
|
eq(topics.userId, userId),
|
||||||
|
eq(topics.renaming, true),
|
||||||
|
or(isNull(topics.renameExpiresAt), lte(topics.renameExpiresAt, new Date())),
|
||||||
|
));
|
||||||
|
|
||||||
const agents = await db.query.agents.findMany({
|
const agents = await db.query.agents.findMany({
|
||||||
where: {
|
where: {
|
||||||
userId,
|
userId,
|
||||||
|
|||||||
@@ -63,62 +63,106 @@ export default defineEventHandler(async (event) => {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const rootMessage = messagesMap.get(messageId);
|
const targetMessage = messagesMap.get(messageId);
|
||||||
if (!rootMessage) {
|
if (!targetMessage) {
|
||||||
throw createError({
|
throw createError({
|
||||||
statusCode: 400,
|
statusCode: 400,
|
||||||
statusMessage: 'Invalid message',
|
statusMessage: 'Invalid message',
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (rootMessage.role === 'user') {
|
if (targetMessage.role === 'user') {
|
||||||
await deeplyDeleteMessage(rootMessage.id, topicId, userId);
|
await deeplyDeleteMessage(targetMessage.id, topicId, userId);
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (rootMessage.deleted === true) {
|
if (targetMessage.parentMessageId && messagesMap.has(targetMessage.parentMessageId)) {
|
||||||
const childMessage = rootMessage.activeChildId
|
const parent = messagesMap.get(targetMessage.parentMessageId)!;
|
||||||
? rootMessage.children.find(c => c.id === rootMessage.activeChildId)
|
await deeplyDeleteMessage(targetMessage.id, topicId, userId);
|
||||||
: rootMessage.children[0];
|
|
||||||
if (!childMessage) {
|
const remainingChildren = parent.children.filter((child) => {
|
||||||
console.error('Message not found');
|
return child.id !== targetMessage.id;
|
||||||
return { ok: false };
|
});
|
||||||
|
|
||||||
|
if (parent.deleted === true && remainingChildren.length === 0) {
|
||||||
|
await deeplyDeleteMessage(parent.id, topicId, userId);
|
||||||
|
} else if (parent.activeChildId === targetMessage.id) {
|
||||||
|
const nextActiveChildId = remainingChildren.length > 0
|
||||||
|
? (parent.deleted ? remainingChildren[0]!.id : remainingChildren[remainingChildren.length - 1]!.id)
|
||||||
|
: null;
|
||||||
|
await db.update(messages).set({ activeChildId: nextActiveChildId }).where(sql`${messages.id} = ${parent.id} AND ${messages.userId} = ${userId}`);
|
||||||
|
topicEvents.emit(topicId, {
|
||||||
|
type: 'MESSAGE_UPDATED',
|
||||||
|
payload: { ...parent, activeChildId: nextActiveChildId },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return { ok: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
await deeplyDeleteMessage(childMessage.id, topicId, userId);
|
if (targetMessage.deleted === true) {
|
||||||
|
const childMessage = targetMessage.activeChildId
|
||||||
|
? targetMessage.children.find((c) => { return c.id === targetMessage.activeChildId; })
|
||||||
|
: targetMessage.children[0];
|
||||||
|
|
||||||
const remainingChildren = rootMessage.children.filter(child => child!.id !== childMessage.id);
|
if (childMessage) {
|
||||||
|
await deeplyDeleteMessage(childMessage.id, topicId, userId);
|
||||||
|
const remainingChildren = targetMessage.children.filter((child) => {
|
||||||
|
return child.id !== childMessage.id;
|
||||||
|
});
|
||||||
if (remainingChildren.length === 0) {
|
if (remainingChildren.length === 0) {
|
||||||
await deeplyDeleteMessage(rootMessage.id, topicId, userId);
|
await deeplyDeleteMessage(targetMessage.id, topicId, userId);
|
||||||
|
} else if (targetMessage.activeChildId === childMessage.id) {
|
||||||
|
const nextActiveChildId = remainingChildren[0]!.id;
|
||||||
|
await db.update(messages).set({ activeChildId: nextActiveChildId }).where(sql`${messages.id} = ${targetMessage.id} AND ${messages.userId} = ${userId}`);
|
||||||
|
topicEvents.emit(topicId, {
|
||||||
|
type: 'MESSAGE_UPDATED',
|
||||||
|
payload: { ...targetMessage, activeChildId: nextActiveChildId },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
await deeplyDeleteMessage(targetMessage.id, topicId, userId);
|
||||||
}
|
}
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (
|
if (
|
||||||
rootMessage.activeChildId
|
targetMessage.activeChildId
|
||||||
&& rootMessage.children.length > 0
|
&& targetMessage.children.length > 0
|
||||||
) {
|
) {
|
||||||
const childMessage = rootMessage.children.find(c => c.id === rootMessage.activeChildId);
|
const childMessage = targetMessage.children.find((c) => {
|
||||||
if (!childMessage) {
|
return c.id === targetMessage.activeChildId;
|
||||||
console.error('Message not found');
|
});
|
||||||
return { ok: false };
|
if (childMessage) {
|
||||||
}
|
|
||||||
|
|
||||||
await deeplyDeleteMessage(childMessage.id, topicId, userId);
|
await deeplyDeleteMessage(childMessage.id, topicId, userId);
|
||||||
|
const remainingChildren = targetMessage.children.filter((child) => {
|
||||||
|
return child.id !== childMessage.id;
|
||||||
|
});
|
||||||
|
const nextActiveChildId = remainingChildren.length > 0
|
||||||
|
? remainingChildren[remainingChildren.length - 1]!.id
|
||||||
|
: null;
|
||||||
|
await db.update(messages).set({ activeChildId: nextActiveChildId }).where(sql`${messages.id} = ${targetMessage.id} AND ${messages.userId} = ${userId}`);
|
||||||
|
topicEvents.emit(topicId, {
|
||||||
|
type: 'MESSAGE_UPDATED',
|
||||||
|
payload: { ...targetMessage, activeChildId: nextActiveChildId },
|
||||||
|
});
|
||||||
|
return { ok: true };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (targetMessage.children.length === 0) {
|
||||||
|
await deeplyDeleteMessage(targetMessage.id, topicId, userId);
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
if (rootMessage.children.length === 0) {
|
const nextActiveChildId = targetMessage.children[0]?.id ?? null;
|
||||||
await deeplyDeleteMessage(rootMessage.id, topicId, userId);
|
await db.update(messages).set({
|
||||||
return { ok: true };
|
deleted: true,
|
||||||
}
|
activeChildId: nextActiveChildId,
|
||||||
|
}).where(sql`${messages.id} = ${targetMessage.id} AND ${messages.userId} = ${userId}`);
|
||||||
await db.update(messages).set({ deleted: true }).where(sql`${messages.id} = ${rootMessage.id} AND ${messages.userId} = ${userId}`);
|
|
||||||
|
|
||||||
topicEvents.emit(topicId, {
|
topicEvents.emit(topicId, {
|
||||||
type: 'MESSAGE_UPDATED',
|
type: 'MESSAGE_UPDATED',
|
||||||
payload: { ...rootMessage, deleted: true },
|
payload: { ...targetMessage, deleted: true, activeChildId: nextActiveChildId },
|
||||||
});
|
});
|
||||||
|
|
||||||
return { ok: true };
|
return { ok: true };
|
||||||
|
|||||||
@@ -1,44 +1,39 @@
|
|||||||
import { and, eq } from 'drizzle-orm';
|
import { and, eq, isNull } from "drizzle-orm";
|
||||||
import { topics } from '~~/drizzle/schema';
|
import { topics } from "~~/drizzle/schema";
|
||||||
import { db } from '~~/server/lib/db';
|
import { db } from "~~/server/lib/db";
|
||||||
import { cancelPendingRename } from '~~/server/utils/renames';
|
import { cancelPendingRename } from "~~/server/utils/renames";
|
||||||
import { userEvents } from '~~/server/utils/events';
|
import { topicEvents, userEvents } from "~~/server/utils/events";
|
||||||
|
|
||||||
export default defineEventHandler(async (event) => {
|
export default defineEventHandler(async (event) => {
|
||||||
await protectRoute(event);
|
await protectRoute(event);
|
||||||
|
const topicId = getRouterParam(event, "topicId");
|
||||||
|
const userId = event.context.user?.id;
|
||||||
|
if (!topicId || !userId) {
|
||||||
|
setResponseStatus(event, 400);
|
||||||
|
return { ok: false };
|
||||||
|
}
|
||||||
|
|
||||||
const topicId = getRouterParam(event, 'topicId')!;
|
const topic = await db.query.topics.findFirst({ where: { id: topicId, userId } });
|
||||||
|
if (!topic) {
|
||||||
const success = cancelPendingRename(topicId);
|
setResponseStatus(event, 404);
|
||||||
if (success) {
|
return { ok: false };
|
||||||
const res = await db.update(topics).set({
|
}
|
||||||
|
const cleared = await db.update(topics).set({
|
||||||
renaming: false,
|
renaming: false,
|
||||||
}).where(and(eq(topics.id, topicId), eq(topics.userId, event.context.user!.id)));
|
renameAttemptId: null,
|
||||||
if (res.rowCount === 0) {
|
renameExpiresAt: null,
|
||||||
throw createError({
|
}).where(and(
|
||||||
statusCode: 400,
|
eq(topics.id, topicId),
|
||||||
statusMessage: 'Invalid topic',
|
eq(topics.userId, userId),
|
||||||
data: {
|
topic.renameAttemptId ? eq(topics.renameAttemptId, topic.renameAttemptId) : isNull(topics.renameAttemptId),
|
||||||
code: 'INVALID_TOPIC',
|
)).returning({ id: topics.id });
|
||||||
ok: false,
|
if (cleared.length === 0) {
|
||||||
}
|
return { ok: false };
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
cancelPendingRename(topicId, topic.renameAttemptId);
|
||||||
|
|
||||||
userEvents.emit(topicId, 'topics', {
|
const payload = { topicId, renaming: false };
|
||||||
op: 'update',
|
userEvents.emit(userId, "topics", { op: "update", payload });
|
||||||
payload: {
|
topicEvents.emit(topicId, { type: "topic_updated", payload });
|
||||||
topicId,
|
return { ok: true };
|
||||||
renaming: false,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
return {
|
|
||||||
ok: true,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
ok: false,
|
|
||||||
};
|
|
||||||
});
|
});
|
||||||
@@ -1,13 +1,16 @@
|
|||||||
import * as z from 'zod';
|
import * as z from 'zod';
|
||||||
import { renamePrompt } from '~~/prompts';
|
import { renamePrompt } from '~~/prompts';
|
||||||
import { generateText } from 'ai';
|
import { generateText, type UserContent } from "ai";
|
||||||
|
import { nanoid } from "nanoid";
|
||||||
|
import { resolveFileUrl } from "~~/utils/url";
|
||||||
|
import { generateFileToken } from "~~/server/utils/file-token";
|
||||||
import { GatewayFetchError, getProviderDetails, type ModelGateway } from '~~/server/utils/ai-provider';
|
import { GatewayFetchError, getProviderDetails, type ModelGateway } from '~~/server/utils/ai-provider';
|
||||||
import { addPendingRename } from '~~/server/utils/renames';
|
import { addPendingRename, completeRename } from "~~/server/utils/renames";
|
||||||
import { userEvents } from '~~/server/utils/events';
|
import { userEvents } from '~~/server/utils/events';
|
||||||
import { db } from '~~/server/lib/db';
|
import { db } from '~~/server/lib/db';
|
||||||
import { type Model } from '~/composables/useModels';
|
import { type Model } from '~/composables/useModels';
|
||||||
import { topics } from '~~/drizzle/schema';
|
import { topics } from '~~/drizzle/schema';
|
||||||
import { eq } from 'drizzle-orm';
|
import { and, eq, gt, isNull, lte, or } from "drizzle-orm";
|
||||||
|
|
||||||
export default defineEventHandler(async (event) => {
|
export default defineEventHandler(async (event) => {
|
||||||
await protectRoute(event);
|
await protectRoute(event);
|
||||||
@@ -94,7 +97,7 @@ export default defineEventHandler(async (event) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (topic.renaming) {
|
if (topic.renaming && topic.renameExpiresAt && topic.renameExpiresAt > new Date()) {
|
||||||
throw createError({
|
throw createError({
|
||||||
statusCode: 400,
|
statusCode: 400,
|
||||||
statusMessage: 'Already renaming',
|
statusMessage: 'Already renaming',
|
||||||
@@ -165,47 +168,70 @@ export default defineEventHandler(async (event) => {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
let prompt = firstMessage.content!;
|
const content: UserContent = [{
|
||||||
|
type: "text",
|
||||||
if (firstMessage.attachments.length > 0) {
|
text: [firstMessage.content || "Describe the attached content.",
|
||||||
for (const attachment of firstMessage.attachments) {
|
...firstMessage.attachments.map(({ file }) => `Attachment: ${file.name}`),
|
||||||
if (attachment.file.mimeType.startsWith('image/')) {
|
].join("\n").slice(0, 12000),
|
||||||
prompt += `\n`;
|
}];
|
||||||
|
if (model.inputModalities.includes("image")) {
|
||||||
|
const images = firstMessage.attachments.filter(({ file }) =>
|
||||||
|
file.mimeType.startsWith("image/") && file.size <= 10 * 1024 * 1024,
|
||||||
|
).slice(0, 2);
|
||||||
|
for (const { file } of images) {
|
||||||
|
const url = new URL(resolveFileUrl(file.url));
|
||||||
|
if (file.url.startsWith("/api/files/")) {
|
||||||
|
const secret = process.env.BETTER_AUTH_SECRET;
|
||||||
|
if (!secret) {
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
|
const { exp, sig } = generateFileToken(file.url.slice("/api/files/".length), secret);
|
||||||
|
url.searchParams.set("exp", String(exp));
|
||||||
|
url.searchParams.set("sig", sig);
|
||||||
|
}
|
||||||
|
content.push({ type: "image", image: url, mediaType: file.mimeType });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const abortController = addPendingRename(topicId);
|
const attemptId = nanoid();
|
||||||
event.waitUntil(autoRename(topicId, abortController, { gateway: gateway.gateway, model }, gateway.textTransformer, prompt, userId));
|
const claimed = await db.update(topics).set({
|
||||||
|
renaming: true,
|
||||||
|
renameAttemptId: attemptId,
|
||||||
|
renameExpiresAt: new Date(Date.now() + 90000),
|
||||||
|
}).where(and(
|
||||||
|
eq(topics.id, topicId),
|
||||||
|
eq(topics.userId, userId),
|
||||||
|
eq(topics.name, topic.name),
|
||||||
|
or(eq(topics.renaming, false), isNull(topics.renameExpiresAt), lte(topics.renameExpiresAt, new Date())),
|
||||||
|
)).returning({ id: topics.id });
|
||||||
|
if (claimed.length === 0) {
|
||||||
|
return { ok: false as const, code: "ALREADY_RENAMING" };
|
||||||
|
}
|
||||||
|
userEvents.emit(userId, "topics", {
|
||||||
|
op: "update", payload: { topicId, renaming: true },
|
||||||
|
});
|
||||||
|
const abortController = addPendingRename(topicId, attemptId);
|
||||||
|
event.waitUntil(autoRename(topicId, attemptId, abortController, { gateway: gateway.gateway, model }, gateway.textTransformer, content, userId));
|
||||||
|
|
||||||
return {
|
return {
|
||||||
ok: true,
|
ok: true as const,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
|
||||||
const autoRename = async (
|
const autoRename = async (
|
||||||
topicId: string,
|
topicId: string,
|
||||||
|
attemptId: string,
|
||||||
abortController: AbortController,
|
abortController: AbortController,
|
||||||
model: {
|
model: {
|
||||||
gateway: ModelGateway,
|
gateway: ModelGateway,
|
||||||
model: Model,
|
model: Model,
|
||||||
},
|
},
|
||||||
textTransformer: ((text: string) => string) | ((text: string) => string)[] | undefined,
|
textTransformer: ((text: string) => string) | ((text: string) => string)[] | undefined,
|
||||||
prompt: string,
|
content: UserContent,
|
||||||
userId: string,
|
userId: string,
|
||||||
) => {
|
) => {
|
||||||
|
const deadline = setTimeout(() => abortController.abort(), 90000);
|
||||||
try {
|
try {
|
||||||
await db.update(topics).set({
|
|
||||||
renaming: true,
|
|
||||||
}).where(eq(topics.id, topicId));
|
|
||||||
userEvents.emit(model.model.userId, 'topics', {
|
|
||||||
op: 'update',
|
|
||||||
payload: {
|
|
||||||
topicId,
|
|
||||||
renaming: true,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
|
|
||||||
const response = await generateText({
|
const response = await generateText({
|
||||||
model: model.gateway(model.model.externalId),
|
model: model.gateway(model.model.externalId),
|
||||||
providerOptions: {
|
providerOptions: {
|
||||||
@@ -214,10 +240,11 @@ const autoRename = async (
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
system: renamePrompt,
|
system: renamePrompt,
|
||||||
prompt,
|
messages: [{ role: "user", content }],
|
||||||
|
maxRetries: 0,
|
||||||
timeout: 90 * 1000,
|
timeout: 90 * 1000,
|
||||||
abortSignal: abortController.signal,
|
abortSignal: abortController.signal,
|
||||||
})
|
});
|
||||||
|
|
||||||
let text = response.text;
|
let text = response.text;
|
||||||
|
|
||||||
@@ -231,15 +258,30 @@ const autoRename = async (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
await db.update(topics).set({
|
text = text.trim().replace(/^['"]|['"]$/g, "").split("\n")[0]?.trim().slice(0, 120) || "";
|
||||||
|
if (!text || abortController.signal.aborted) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const updated = await db.update(topics).set({
|
||||||
renaming: false,
|
renaming: false,
|
||||||
|
renameAttemptId: null,
|
||||||
|
renameExpiresAt: null,
|
||||||
|
titleSource: "generated",
|
||||||
name: text,
|
name: text,
|
||||||
}).where(eq(topics.id, topicId));
|
}).where(and(
|
||||||
|
eq(topics.id, topicId),
|
||||||
|
eq(topics.renameAttemptId, attemptId),
|
||||||
|
gt(topics.renameExpiresAt, new Date()),
|
||||||
|
)).returning({ id: topics.id });
|
||||||
|
if (updated.length === 0) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
userEvents.emit(model.model.userId, 'topics', {
|
userEvents.emit(model.model.userId, 'topics', {
|
||||||
op: 'update',
|
op: 'update',
|
||||||
payload: {
|
payload: {
|
||||||
topicId,
|
topicId,
|
||||||
name: text,
|
name: text,
|
||||||
|
titleSource: "generated",
|
||||||
renaming: false,
|
renaming: false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
@@ -248,29 +290,26 @@ const autoRename = async (
|
|||||||
payload: {
|
payload: {
|
||||||
topicId,
|
topicId,
|
||||||
name: text,
|
name: text,
|
||||||
|
titleSource: "generated",
|
||||||
renaming: false,
|
renaming: false,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Failed to auto-rename:', error);
|
if (!abortController.signal.aborted) {
|
||||||
await db.update(topics).set({
|
console.error("Failed to auto-rename:", error);
|
||||||
renaming: false,
|
}
|
||||||
}).where(eq(topics.id, topicId));
|
|
||||||
userEvents.emit(model.model.userId, 'topics', {
|
|
||||||
op: 'update',
|
|
||||||
payload: {
|
|
||||||
topicId,
|
|
||||||
renaming: false,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
topicEvents.emit(topicId, {
|
|
||||||
type: 'topic_updated',
|
|
||||||
payload: {
|
|
||||||
topicId,
|
|
||||||
renaming: false,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} finally {
|
} finally {
|
||||||
completeRename(topicId);
|
clearTimeout(deadline);
|
||||||
|
completeRename(topicId, attemptId);
|
||||||
|
const cleared = await db.update(topics).set({
|
||||||
|
renaming: false,
|
||||||
|
renameAttemptId: null,
|
||||||
|
renameExpiresAt: null,
|
||||||
|
}).where(and(eq(topics.id, topicId), eq(topics.renameAttemptId, attemptId))).returning({ id: topics.id });
|
||||||
|
if (cleared.length > 0) {
|
||||||
|
const payload = { topicId, renaming: false };
|
||||||
|
userEvents.emit(userId, "topics", { op: "update", payload });
|
||||||
|
topicEvents.emit(topicId, { type: "topic_updated", payload });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -433,7 +433,21 @@ async function generateResponse(
|
|||||||
|
|
||||||
if (search) {
|
if (search) {
|
||||||
tools.search = tool({
|
tools.search = tool({
|
||||||
description: 'Searches the web. Choose how many results to return on every call using the required results argument.',
|
description: `Searches the web. Choose how many results to return on every call using the required results argument.
|
||||||
|
|
||||||
|
CITATION FORMAT:
|
||||||
|
Every result includes a sourceId. Cite supporting results immediately after the claim using this exact construction:
|
||||||
|
"[[cite:" + the result's sourceId + "]]"
|
||||||
|
The prefix "cite:" is mandatory literal text. Copy the sourceId unchanged after that prefix. Do not output the word "sourceId" as a placeholder.
|
||||||
|
|
||||||
|
Example: if a result has sourceId "sd625ebbd4d3544e4914f5a51840d7632":
|
||||||
|
CORRECT: The report describes rising prices. [[cite:sd625ebbd4d3544e4914f5a51840d7632]]
|
||||||
|
INCORRECT: The report describes rising prices. [[sd625ebbd4d3544e4914f5a51840d7632]]
|
||||||
|
The incorrect form is missing "cite:" and will not render as a citation.
|
||||||
|
|
||||||
|
For multiple sources, put their exact IDs after a single "cite:" prefix, separated by commas without spaces: [[cite:ID_FROM_FIRST_RESULT,ID_FROM_SECOND_RESULT]]. Replace both placeholders with returned sourceId values. Separate complete citations are also valid: [[cite:ID_FROM_FIRST_RESULT]] [[cite:ID_FROM_SECOND_RESULT]].
|
||||||
|
Use only IDs returned by searches during this response; never invent IDs or copy the example ID unless it actually appears in a result. Write citation markers directly in answer text, not inside backticks or code blocks. Do not repeat URLs or add footnote definitions for these citations.
|
||||||
|
Search snippets are excerpts, not full-page reads.`,
|
||||||
inputSchema: searchInputSchema,
|
inputSchema: searchInputSchema,
|
||||||
outputSchema: searchOutputSchema,
|
outputSchema: searchOutputSchema,
|
||||||
execute: async ({ query, results }) => {
|
execute: async ({ query, results }) => {
|
||||||
@@ -652,6 +666,7 @@ async function generateResponse(
|
|||||||
partId: part.id,
|
partId: part.id,
|
||||||
lastUpdatedAt: new Date(),
|
lastUpdatedAt: new Date(),
|
||||||
content: token.text,
|
content: token.text,
|
||||||
|
offset: part.accumulatedContent.length - token.text.length,
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -1244,6 +1259,7 @@ async function generateResponse(
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
} finally {
|
} finally {
|
||||||
|
topicEvents.clearLiveText(topicId, message.id);
|
||||||
completeGeneration(generationId);
|
completeGeneration(generationId);
|
||||||
if (logFile !== undefined) logFile.close();
|
if (logFile !== undefined) logFile.close();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,95 +1,60 @@
|
|||||||
import { db } from "~~/server/lib/db";
|
import { db } from '~~/server/lib/db';
|
||||||
import { topicEvents } from "~~/server/utils/events";
|
import { topicEvents } from '~~/server/utils/events';
|
||||||
|
import { createTopicSnapshotStream } from '~~/server/utils/topic-snapshot-stream';
|
||||||
|
|
||||||
export default defineEventHandler(async (event) => {
|
export default defineEventHandler(async (event) => {
|
||||||
await protectRoute(event);
|
await protectRoute(event);
|
||||||
|
|
||||||
const topicId = getRouterParam(event, 'topicId')!;
|
const topicId = getRouterParam(event, 'topicId')!;
|
||||||
const isSSE = getHeader(event, 'accept')?.includes('text/event-stream') ?? false;
|
|
||||||
|
|
||||||
const userId = event.context.user!.id as string;
|
const userId = event.context.user!.id as string;
|
||||||
|
const isSSE = getHeader(event, 'accept')?.includes('text/event-stream') ?? false;
|
||||||
const topic = await db.query.topics.findFirst({
|
const readTopic = () => db.query.topics.findFirst({
|
||||||
where: {
|
where: { id: topicId, userId },
|
||||||
id: topicId,
|
|
||||||
userId,
|
|
||||||
},
|
|
||||||
with: {
|
with: {
|
||||||
messages: {
|
messages: {
|
||||||
orderBy: {
|
orderBy: { createdAt: 'asc' },
|
||||||
createdAt: 'asc',
|
|
||||||
},
|
|
||||||
with: {
|
with: {
|
||||||
parts: {
|
parts: {
|
||||||
orderBy: {
|
orderBy: { createdAt: 'asc' },
|
||||||
createdAt: 'asc',
|
with: { toolCall: true },
|
||||||
},
|
|
||||||
with: {
|
|
||||||
toolCall: true,
|
|
||||||
}
|
|
||||||
},
|
|
||||||
attachments: {
|
|
||||||
with: {
|
|
||||||
file: true,
|
|
||||||
}
|
|
||||||
},
|
},
|
||||||
|
attachments: { with: { file: true } },
|
||||||
generation: true,
|
generation: true,
|
||||||
}
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (!isSSE) {
|
||||||
|
const topic = await readTopic();
|
||||||
if (!topic) {
|
if (!topic) {
|
||||||
console.log("topic not found");
|
setResponseStatus(event, 404);
|
||||||
throw createError({
|
return { ok: false, error: 'Topic not found' };
|
||||||
statusCode: 404,
|
|
||||||
statusMessage: 'Not Found',
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
topicEvents.applyLiveText(topicId, topic.messages);
|
||||||
if (isSSE === false) {
|
|
||||||
return topic;
|
return topic;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Authorize before subscribing; no topic data is exposed before this check.
|
||||||
|
const ownedTopic = await db.query.topics.findFirst({
|
||||||
|
where: { id: topicId, userId },
|
||||||
|
columns: { id: true },
|
||||||
|
});
|
||||||
|
if (!ownedTopic) {
|
||||||
|
setResponseStatus(event, 404);
|
||||||
|
return { ok: false, error: 'Topic not found' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const subscription = createTopicSnapshotStream(topicId, getQuery(event).snapshot);
|
||||||
|
event.node.res.once('close', subscription.close);
|
||||||
|
const stream = await subscription.open(readTopic);
|
||||||
|
if (!stream.ok) {
|
||||||
|
setResponseStatus(event, stream.error === 'read-failed' ? 500 : 404);
|
||||||
|
return { ok: false, error: stream.error };
|
||||||
|
}
|
||||||
setHeader(event, 'Content-Type', 'text/event-stream');
|
setHeader(event, 'Content-Type', 'text/event-stream');
|
||||||
setHeader(event, 'Cache-Control', 'no-cache');
|
setHeader(event, 'Cache-Control', 'no-cache');
|
||||||
setHeader(event, 'Connection', 'keep-alive');
|
setHeader(event, 'X-Accel-Buffering', 'no');
|
||||||
|
|
||||||
const { lastUpdate, count } = getQuery(event);
|
return sendStream(event, stream.data);
|
||||||
const serverLastUpdate = topic.messages.at(-1)?.updatedAt;
|
|
||||||
const serverCount = topic.messages.length;
|
|
||||||
|
|
||||||
// TODO: there is potentially a race condition here where the client could
|
|
||||||
// connect at milisecond 87, and the last database write was at 0 (there
|
|
||||||
// is a write every 100ms for some operations), if there were tokens sent
|
|
||||||
// at 20 40 and 60, those tokens are lost to the client.
|
|
||||||
let streamController: ReadableStreamDefaultController;
|
|
||||||
let interval: NodeJS.Timeout;
|
|
||||||
const stream = new ReadableStream({
|
|
||||||
start(controller) {
|
|
||||||
streamController = controller;
|
|
||||||
controller.enqueue(`:connected\n\n`);
|
|
||||||
|
|
||||||
if ((lastUpdate && count) && (lastUpdate === serverLastUpdate?.toISOString() && count === serverCount)) {
|
|
||||||
controller.enqueue(':already_synced\n\n')
|
|
||||||
} else {
|
|
||||||
controller.enqueue(`data: ${JSON.stringify({
|
|
||||||
type: 'initial_state',
|
|
||||||
payload: topic
|
|
||||||
})}\n\n`);
|
|
||||||
}
|
|
||||||
|
|
||||||
interval = setInterval(() => {
|
|
||||||
controller.enqueue(`:heartbeat\n\n`);
|
|
||||||
}, 15000);
|
|
||||||
|
|
||||||
topicEvents.subscribe(topicId, streamController);
|
|
||||||
},
|
|
||||||
cancel() {
|
|
||||||
topicEvents.unsubscribe(topicId, streamController);
|
|
||||||
clearInterval(interval);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return sendStream(event, stream);
|
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -29,6 +29,12 @@ export default defineEventHandler(async (event) => {
|
|||||||
const res = await db.update(topics)
|
const res = await db.update(topics)
|
||||||
.set({
|
.set({
|
||||||
name,
|
name,
|
||||||
|
...(name === undefined ? {} : {
|
||||||
|
titleSource: "manual",
|
||||||
|
renaming: false,
|
||||||
|
renameAttemptId: null,
|
||||||
|
renameExpiresAt: null,
|
||||||
|
}),
|
||||||
})
|
})
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
|
|||||||
@@ -30,6 +30,7 @@ export default defineEventHandler(async (event) => {
|
|||||||
id,
|
id,
|
||||||
userId,
|
userId,
|
||||||
name,
|
name,
|
||||||
|
titleSource: "provisional",
|
||||||
agentId,
|
agentId,
|
||||||
createdAt: new Date(),
|
createdAt: new Date(),
|
||||||
});
|
});
|
||||||
|
|||||||
+14
-6
@@ -1,5 +1,9 @@
|
|||||||
|
import { createLiveTopicText } from './live-topic-text';
|
||||||
|
|
||||||
|
type StreamSink = Pick<ReadableStreamDefaultController, 'enqueue'>;
|
||||||
|
|
||||||
interface StreamConnection {
|
interface StreamConnection {
|
||||||
controller: ReadableStreamDefaultController;
|
controller: StreamSink;
|
||||||
lastPing: number;
|
lastPing: number;
|
||||||
subscribedAt: number;
|
subscribedAt: number;
|
||||||
}
|
}
|
||||||
@@ -91,9 +95,13 @@ export const userEvents = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const topicSubscribers = new Map<string, Set<StreamConnection>>();
|
const topicSubscribers = new Map<string, Set<StreamConnection>>();
|
||||||
|
const liveTopicText = createLiveTopicText();
|
||||||
|
|
||||||
export const topicEvents = {
|
export const topicEvents = {
|
||||||
subscribe(topicId: string, controller: ReadableStreamDefaultController) {
|
applyLiveText: liveTopicText.apply,
|
||||||
|
clearLiveText: liveTopicText.removeMessage,
|
||||||
|
|
||||||
|
subscribe(topicId: string, controller: StreamSink) {
|
||||||
if (!topicSubscribers.has(topicId)) {
|
if (!topicSubscribers.has(topicId)) {
|
||||||
topicSubscribers.set(topicId, new Set());
|
topicSubscribers.set(topicId, new Set());
|
||||||
}
|
}
|
||||||
@@ -120,7 +128,7 @@ export const topicEvents = {
|
|||||||
(conn as any).pingInterval = pingInterval;
|
(conn as any).pingInterval = pingInterval;
|
||||||
},
|
},
|
||||||
|
|
||||||
unsubscribe(topicId: string, controller: ReadableStreamDefaultController) {
|
unsubscribe(topicId: string, controller: StreamSink) {
|
||||||
const connections = topicSubscribers.get(topicId);
|
const connections = topicSubscribers.get(topicId);
|
||||||
if (!connections) return;
|
if (!connections) return;
|
||||||
|
|
||||||
@@ -137,14 +145,14 @@ export const topicEvents = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
async emit(topicId: string, events: Array<{ type: string; payload: any; timestamp?: number }> | { type: string; payload: any; timestamp?: number }) {
|
async emit(topicId: string, events: Array<{ type: string; payload: any; timestamp?: number }> | { type: string; payload: any; timestamp?: number }) {
|
||||||
const connections = topicSubscribers.get(topicId);
|
|
||||||
if (!connections || connections.size === 0) return;
|
|
||||||
|
|
||||||
if (!Array.isArray(events)) {
|
if (!Array.isArray(events)) {
|
||||||
events = [events];
|
events = [events];
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const event of events) {
|
for (const event of events) {
|
||||||
|
liveTopicText.update(topicId, event);
|
||||||
|
const connections = topicSubscribers.get(topicId);
|
||||||
|
if (!connections || connections.size === 0) continue;
|
||||||
const timestamp = event.timestamp ?? Date.now();
|
const timestamp = event.timestamp ?? Date.now();
|
||||||
const data = `data: ${JSON.stringify({ ...event, timestamp })}\n\n`;
|
const data = `data: ${JSON.stringify({ ...event, timestamp })}\n\n`;
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
import { appendTextDelta } from '../../utils/topic-sync';
|
||||||
|
|
||||||
|
interface LivePart {
|
||||||
|
messageId: string;
|
||||||
|
part: Record<string, any> & { id: string; content: string };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Covers the interval between an emitted delta and its throttled DB write. */
|
||||||
|
export const createLiveTopicText = () => {
|
||||||
|
const topics = new Map<string, Map<string, LivePart>>();
|
||||||
|
|
||||||
|
const removeMessage = (topicId: string, messageId: string) => {
|
||||||
|
const parts = topics.get(topicId);
|
||||||
|
if (!parts) return;
|
||||||
|
for (const [id, entry] of parts) {
|
||||||
|
if (entry.messageId === messageId) parts.delete(id);
|
||||||
|
}
|
||||||
|
if (parts.size === 0) topics.delete(topicId);
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
update(topicId: string, event: { type: string; payload: any }) {
|
||||||
|
const { type, payload } = event;
|
||||||
|
if (type === 'text-start') {
|
||||||
|
let parts = topics.get(topicId);
|
||||||
|
if (!parts) topics.set(topicId, parts = new Map());
|
||||||
|
parts.set(payload.part.id, {
|
||||||
|
messageId: payload.messageId,
|
||||||
|
part: { ...payload.part, toolCall: null, content: payload.part.content ?? '' },
|
||||||
|
});
|
||||||
|
} else if (type === 'text-delta') {
|
||||||
|
const entry = topics.get(topicId)?.get(payload.partId);
|
||||||
|
if (entry) {
|
||||||
|
entry.part.content = appendTextDelta(entry.part.content, payload.content, payload.offset);
|
||||||
|
entry.part.lastUpdatedAt = payload.lastUpdatedAt;
|
||||||
|
}
|
||||||
|
} else if (type === 'text-end' || type === 'text-delete') {
|
||||||
|
const parts = topics.get(topicId);
|
||||||
|
parts?.delete(payload.partId);
|
||||||
|
if (parts?.size === 0) topics.delete(topicId);
|
||||||
|
} else if (type === 'MESSAGE_DELETED') {
|
||||||
|
removeMessage(topicId, payload.id);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
apply(topicId: string, messages: { id: string; parts: any[] }[]) {
|
||||||
|
const parts = topics.get(topicId);
|
||||||
|
if (!parts) return;
|
||||||
|
const byId = new Map(messages.map(message => [message.id, message]));
|
||||||
|
for (const entry of parts.values()) {
|
||||||
|
const message = byId.get(entry.messageId);
|
||||||
|
if (!message) continue;
|
||||||
|
const existing = message.parts.find(part => part.id === entry.part.id);
|
||||||
|
if (existing) {
|
||||||
|
if (!existing.finished && (existing.content?.length ?? 0) <= entry.part.content.length) {
|
||||||
|
existing.content = entry.part.content;
|
||||||
|
existing.lastUpdatedAt = entry.part.lastUpdatedAt;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
message.parts.push({ ...entry.part });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
removeMessage,
|
||||||
|
};
|
||||||
|
};
|
||||||
+15
-25
@@ -1,31 +1,21 @@
|
|||||||
interface PendingRename {
|
const pendingRenames = new Map<string, { attemptId: string; controller: AbortController }>();
|
||||||
topicId: string;
|
|
||||||
abortController: AbortController;
|
|
||||||
}
|
|
||||||
|
|
||||||
const pendingRenames: Map<string, AbortController> = new Map();
|
export const cancelPendingRename = (topicId: string, attemptId?: string | null) => {
|
||||||
|
const pending = pendingRenames.get(topicId);
|
||||||
export const cancelPendingRename = (topicId: string) => {
|
if (pending && pending.attemptId === attemptId) {
|
||||||
const pendingRename = pendingRenames.get(topicId);
|
pending.controller.abort();
|
||||||
if (pendingRename) {
|
|
||||||
pendingRename.abort();
|
|
||||||
pendingRenames.delete(topicId);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
return false;
|
|
||||||
};
|
|
||||||
|
|
||||||
export const completeRename = (topicId: string) => {
|
|
||||||
const controller = pendingRenames.get(topicId);
|
|
||||||
if (controller) {
|
|
||||||
pendingRenames.delete(topicId);
|
pendingRenames.delete(topicId);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const addPendingRename = (topicId: string) => {
|
export const completeRename = (topicId: string, attemptId: string) => {
|
||||||
const abortController = new AbortController();
|
if (pendingRenames.get(topicId)?.attemptId === attemptId) {
|
||||||
|
pendingRenames.delete(topicId);
|
||||||
pendingRenames.set(topicId, abortController);
|
}
|
||||||
return abortController;
|
};
|
||||||
|
|
||||||
|
export const addPendingRename = (topicId: string, attemptId: string) => {
|
||||||
|
const controller = new AbortController();
|
||||||
|
pendingRenames.set(topicId, { attemptId, controller });
|
||||||
|
return controller;
|
||||||
};
|
};
|
||||||
@@ -1,4 +1,5 @@
|
|||||||
import type { Result } from "../../types/result";
|
import type { Result } from "../../types/result";
|
||||||
|
import { randomUUID } from "node:crypto";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { Err, Ok } from "../../types/result";
|
import { Err, Ok } from "../../types/result";
|
||||||
|
|
||||||
@@ -20,6 +21,7 @@ export const searchOutputSchema = z.object({
|
|||||||
results: z.array(z.object({
|
results: z.array(z.object({
|
||||||
title: z.string(),
|
title: z.string(),
|
||||||
link: z.string(),
|
link: z.string(),
|
||||||
|
sourceId: z.string().describe('Copy this exact ID into [[cite:ID]]. The literal "cite:" prefix is required; [[ID]] is invalid.').optional(),
|
||||||
snippet: z.string(),
|
snippet: z.string(),
|
||||||
})),
|
})),
|
||||||
warnings: z.array(z.object({ engine: z.string(), reason: z.string() })),
|
warnings: z.array(z.object({ engine: z.string(), reason: z.string() })),
|
||||||
@@ -43,6 +45,7 @@ export const readSearchResponse = (body: unknown): Result<SearchOutput, string>
|
|||||||
}
|
}
|
||||||
return Ok({
|
return Ok({
|
||||||
results: parsed.data.results.map(item => ({
|
results: parsed.data.results.map(item => ({
|
||||||
|
sourceId: `s${randomUUID().replaceAll("-", "")}`,
|
||||||
title: item.title,
|
title: item.title,
|
||||||
link: item.url,
|
link: item.url,
|
||||||
snippet: item.content,
|
snippet: item.content,
|
||||||
|
|||||||
@@ -0,0 +1,70 @@
|
|||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import { Err, Ok } from '../../types/result';
|
||||||
|
import { serializeTopicSnapshot } from '../../utils/topic-sync';
|
||||||
|
import { topicEvents } from './events';
|
||||||
|
|
||||||
|
interface TopicSnapshot {
|
||||||
|
messages: { id: string; parts: any[] }[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export const createTopicSnapshotStream = (topicId: string, offeredFingerprint: unknown) => {
|
||||||
|
let controller: ReadableStreamDefaultController | undefined;
|
||||||
|
let closed = false;
|
||||||
|
const buffered: string[] = [];
|
||||||
|
const sink = {
|
||||||
|
enqueue(frame: string) {
|
||||||
|
if (closed) return;
|
||||||
|
if (controller) controller.enqueue(frame);
|
||||||
|
else buffered.push(frame);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
const close = () => {
|
||||||
|
closed = true;
|
||||||
|
topicEvents.unsubscribe(topicId, sink);
|
||||||
|
buffered.length = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
close,
|
||||||
|
async open(readSnapshot: () => Promise<TopicSnapshot | undefined>) {
|
||||||
|
if (closed) return Err('closed' as const);
|
||||||
|
// Subscribe before reading: changes during the query must not be lost.
|
||||||
|
topicEvents.subscribe(topicId, sink);
|
||||||
|
let topic;
|
||||||
|
try {
|
||||||
|
topic = await readSnapshot();
|
||||||
|
} catch (error) {
|
||||||
|
close();
|
||||||
|
console.error('Failed to read topic snapshot', error);
|
||||||
|
return Err('read-failed' as const);
|
||||||
|
}
|
||||||
|
if (closed || !topic) {
|
||||||
|
close();
|
||||||
|
return Err('not-found' as const);
|
||||||
|
}
|
||||||
|
// Include deltas already emitted but not yet flushed to PostgreSQL.
|
||||||
|
topicEvents.applyLiveText(topicId, topic.messages);
|
||||||
|
const fingerprint = createHash('sha256').update(serializeTopicSnapshot(topic)).digest('hex');
|
||||||
|
const matches = offeredFingerprint === fingerprint;
|
||||||
|
|
||||||
|
return Ok(new ReadableStream<string>({
|
||||||
|
start(streamController) {
|
||||||
|
controller = streamController;
|
||||||
|
controller.enqueue(`data: ${JSON.stringify(matches
|
||||||
|
? { type: 'synced', payload: { id: topicId } }
|
||||||
|
: { type: 'initial_state', payload: topic })}\n\n`);
|
||||||
|
for (const frame of buffered) {
|
||||||
|
if (frame.startsWith('data: ')) {
|
||||||
|
const replay = { ...JSON.parse(frame.slice(6)), replay: true };
|
||||||
|
controller.enqueue(`data: ${JSON.stringify(replay)}\n\n`);
|
||||||
|
} else {
|
||||||
|
controller.enqueue(frame);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buffered.length = 0;
|
||||||
|
},
|
||||||
|
cancel: close,
|
||||||
|
}));
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import { collectCitationSources } from "../app/utils/citations";
|
||||||
|
import { createMarkdownParser, getNodeChildren, getNodeTag } from "../app/utils/markdown";
|
||||||
|
import type { MarkdownAstNode } from "../app/utils/markdown";
|
||||||
|
import { readSearchResponse } from "../server/utils/search";
|
||||||
|
|
||||||
|
const citations = (nodes: MarkdownAstNode[]): MarkdownAstNode[] => nodes.flatMap(node =>
|
||||||
|
getNodeTag(node) === "source-cite" ? [node] : citations(getNodeChildren(node)),
|
||||||
|
);
|
||||||
|
|
||||||
|
describe("citation parsing", () => {
|
||||||
|
test("keeps citation markers as text unless explicitly enabled", async () => {
|
||||||
|
const content = "Claim [[cite:1234]] and [[cite:s7,s9]].";
|
||||||
|
for (const options of [{}, { citations: false }]) {
|
||||||
|
for (const streaming of [false, true]) {
|
||||||
|
const tree = await createMarkdownParser(options)(content, { streaming });
|
||||||
|
expect(citations(tree.nodes)).toEqual([]);
|
||||||
|
expect(getNodeChildren(tree.nodes[0] ?? "")).toEqual([content]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("renders single and grouped references as dedicated nodes", async () => {
|
||||||
|
const tree = await createMarkdownParser({ citations: true })("Claim [[cite:s7]]. Another [[cite:s7,s9]].");
|
||||||
|
expect(citations(tree.nodes)).toEqual([
|
||||||
|
["source-cite", { ids: "s7" }],
|
||||||
|
["source-cite", { ids: "s7,s9" }],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not interpret code, escaped references, or link labels", async () => {
|
||||||
|
for (const content of [
|
||||||
|
"`[[cite:s7]]`",
|
||||||
|
"```text\n[[cite:s7]]\n```",
|
||||||
|
"\\[[cite:s7]]",
|
||||||
|
"[Claim [[cite:s7]]](https://example.com)",
|
||||||
|
]) {
|
||||||
|
const tree = await createMarkdownParser({ citations: true })(content);
|
||||||
|
expect(citations(tree.nodes)).toEqual([]);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("streaming never auto-completes a citation", async () => {
|
||||||
|
const parse = createMarkdownParser({ citations: true });
|
||||||
|
const content = "Claim [[cite:s7,s9]]";
|
||||||
|
for (let length = 1; length < content.length; length++) {
|
||||||
|
expect(citations((await parse(content.slice(0, length), { streaming: true })).nodes)).toEqual([]);
|
||||||
|
}
|
||||||
|
expect(citations((await parse(content, { streaming: true })).nodes)).toHaveLength(1);
|
||||||
|
expect(citations((await parse(content)).nodes)).toHaveLength(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("citation sources", () => {
|
||||||
|
test("IDs survive storage, including duplicate URLs and multiple searches", () => {
|
||||||
|
const first = readSearchResponse({ results: [
|
||||||
|
{ title: "One", url: "https://example.com" },
|
||||||
|
{ title: "Two", url: "https://example.com" },
|
||||||
|
] });
|
||||||
|
const second = readSearchResponse({ results: [{ title: "Three", url: "https://example.com" }] });
|
||||||
|
expect(first.ok && second.ok).toBe(true);
|
||||||
|
if (!first.ok || !second.ok) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const parts = [first.data, second.data].map(output => ({
|
||||||
|
toolCall: { toolName: "search", output: { type: "json", value: JSON.stringify(output) } },
|
||||||
|
}));
|
||||||
|
const sources = collectCitationSources(parts);
|
||||||
|
expect(sources.size).toBe(3);
|
||||||
|
expect(sources.get(first.data.results[0]?.sourceId ?? "")?.title).toBe("One");
|
||||||
|
expect(collectCitationSources(JSON.parse(JSON.stringify(parts)))).toEqual(sources);
|
||||||
|
expect(sources.has("invented")).toBe(false);
|
||||||
|
expect(collectCitationSources([]).size).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("ignores legacy results, non-search tools, and unsafe URLs", () => {
|
||||||
|
const output = { type: "json", value: JSON.stringify({ results: [
|
||||||
|
{ title: "Legacy", link: "https://example.com" },
|
||||||
|
{ sourceId: "bad", title: "Bad", link: "javascript:alert(1)" },
|
||||||
|
] }) };
|
||||||
|
expect(collectCitationSources([{ toolCall: { toolName: "search", output } }]).size).toBe(0);
|
||||||
|
expect(collectCitationSources([{ toolCall: { toolName: "python", output } }]).size).toBe(0);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
import { getComposerHeight } from '../app/utils/composer-size';
|
||||||
|
|
||||||
|
describe('composer height stability', () => {
|
||||||
|
test('subpixel noise never oscillates around the two-line minimum', () => {
|
||||||
|
const heights = [47.99999, 48, 48.01].map(height => getComposerHeight(height, 24, 0, 0, true));
|
||||||
|
expect(heights).toEqual([48, 48, 48]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('grows and shrinks for actual lines, capped at ten lines', () => {
|
||||||
|
expect([24, 48, 72, 264, 72, 24].map(height => getComposerHeight(height, 24, 0, 0, true)))
|
||||||
|
.toEqual([48, 48, 72, 240, 72, 48]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('accounts for padding and borders according to box sizing', () => {
|
||||||
|
expect(getComposerHeight(80, 24, 8, 2, true)).toBe(82);
|
||||||
|
expect(getComposerHeight(80, 24, 8, 2, false)).toBe(72);
|
||||||
|
expect(getComposerHeight(10, 24, 8, 2, true)).toBe(58);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('respects fractional typography rather than hardcoding a 24px line', () => {
|
||||||
|
expect(getComposerHeight(40, 20.25, 0, 0, true)).toBe(41);
|
||||||
|
expect(getComposerHeight(1000, 20.25, 0, 0, true)).toBe(203);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
import type { MarkdownTree } from '../app/utils/markdown';
|
||||||
|
import { expect, test } from 'bun:test';
|
||||||
|
import { splitParagraphBreaks } from '../app/utils/markdown';
|
||||||
|
|
||||||
|
test('paragraph splitting preserves nested formatting without mutating a cached parser tree', () => {
|
||||||
|
const tree = { nodes: [
|
||||||
|
['p', {}, 'before', ['br', {}], ['strong', {}, 'after']],
|
||||||
|
['blockquote', {}, 'one', ['br', {}], ['em', {}, 'two']],
|
||||||
|
] } as MarkdownTree;
|
||||||
|
const original = structuredClone(tree);
|
||||||
|
const result = splitParagraphBreaks(tree);
|
||||||
|
expect(result.nodes).toEqual([
|
||||||
|
['p', {}, 'before'],
|
||||||
|
['p', {}, ['strong', {}, 'after']],
|
||||||
|
['blockquote', {}, ['p', {}, 'one'], ['p', {}, ['em', {}, 'two']]],
|
||||||
|
]);
|
||||||
|
expect(tree).toEqual(original);
|
||||||
|
expect(splitParagraphBreaks(tree)).toEqual(result);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('br-free trees return by reference with no allocation', () => {
|
||||||
|
const tree = { nodes: [
|
||||||
|
['p', {}, 'plain ', ['strong', {}, 'text']],
|
||||||
|
['ul', {}, ['li', {}, 'one'], ['li', {}, 'two']],
|
||||||
|
] } as MarkdownTree;
|
||||||
|
expect(splitParagraphBreaks(tree)).toBe(tree);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('single newlines still split into sibling paragraphs', () => {
|
||||||
|
const tree = { nodes: [
|
||||||
|
['p', {}, 'line one', ['br', {}], 'line two'],
|
||||||
|
] } as MarkdownTree;
|
||||||
|
expect(splitParagraphBreaks(tree).nodes).toEqual([
|
||||||
|
['p', {}, 'line one'],
|
||||||
|
['p', {}, 'line two'],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('nested changes rebuild only the affected path', () => {
|
||||||
|
const tree = { nodes: [
|
||||||
|
['blockquote', {}, ['p', {}, 'kept']],
|
||||||
|
['p', {}, 'split', ['br', {}], 'me'],
|
||||||
|
] } as MarkdownTree;
|
||||||
|
const result = splitParagraphBreaks(tree);
|
||||||
|
expect(result).not.toBe(tree);
|
||||||
|
expect(result.nodes[0]).toBe(tree.nodes[0]);
|
||||||
|
expect(result.nodes).toEqual([
|
||||||
|
['blockquote', {}, ['p', {}, 'kept']],
|
||||||
|
['p', {}, 'split'],
|
||||||
|
['p', {}, 'me'],
|
||||||
|
]);
|
||||||
|
});
|
||||||
@@ -0,0 +1,190 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import {
|
||||||
|
buildFocusedMessageTree,
|
||||||
|
buildMessageTree,
|
||||||
|
getActiveMessage,
|
||||||
|
getCurrentChildIndex,
|
||||||
|
getMessageCount,
|
||||||
|
getNextActiveChildId,
|
||||||
|
} from "../utils/message";
|
||||||
|
|
||||||
|
describe("message focus and versioning", () => {
|
||||||
|
test("reproduces and fixes the 3/2 focus bug after deleting root message and regenerating", () => {
|
||||||
|
// Step 1: Generate initial assistant message (A)
|
||||||
|
const msgA = {
|
||||||
|
id: "msg_a",
|
||||||
|
userId: "user_1",
|
||||||
|
topicId: "topic_1",
|
||||||
|
role: "assistant" as const,
|
||||||
|
content: "Response 1",
|
||||||
|
parentMessageId: null,
|
||||||
|
generationId: null,
|
||||||
|
activeChildId: null,
|
||||||
|
deleted: false,
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
parts: [],
|
||||||
|
generation: null,
|
||||||
|
attachments: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
let tree = buildMessageTree([msgA]);
|
||||||
|
expect(tree.length).toBe(1);
|
||||||
|
expect(getMessageCount(tree[0]!)).toBe(1);
|
||||||
|
expect(getCurrentChildIndex(tree[0]!)).toBe(0);
|
||||||
|
expect(getActiveMessage(tree[0]!)?.id).toBe("msg_a");
|
||||||
|
|
||||||
|
// Step 2: Regenerate the message -> creates child B, activeChildId points to B
|
||||||
|
const msgB = {
|
||||||
|
...msgA,
|
||||||
|
id: "msg_b",
|
||||||
|
content: "Response 2",
|
||||||
|
parentMessageId: "msg_a",
|
||||||
|
};
|
||||||
|
msgA.activeChildId = "msg_b";
|
||||||
|
|
||||||
|
tree = buildMessageTree([msgA, msgB]);
|
||||||
|
expect(tree.length).toBe(1);
|
||||||
|
expect(tree[0]!.children.length).toBe(1);
|
||||||
|
expect(getMessageCount(tree[0]!)).toBe(2);
|
||||||
|
// Variant 2 of 2: index should be 1 (displayed as 1 + 1 = 2)
|
||||||
|
expect(getCurrentChildIndex(tree[0]!)).toBe(1);
|
||||||
|
expect(getActiveMessage(tree[0]!)?.id).toBe("msg_b");
|
||||||
|
|
||||||
|
// Step 3: Switch focus to first, root message (A)
|
||||||
|
const prevId = getNextActiveChildId(tree[0]!, -1);
|
||||||
|
expect(prevId).toBeNull();
|
||||||
|
msgA.activeChildId = null;
|
||||||
|
|
||||||
|
tree = buildMessageTree([msgA, msgB]);
|
||||||
|
expect(getMessageCount(tree[0]!)).toBe(2);
|
||||||
|
// Variant 1 of 2: index should be 0 (displayed as 0 + 1 = 1)
|
||||||
|
expect(getCurrentChildIndex(tree[0]!)).toBe(0);
|
||||||
|
expect(getActiveMessage(tree[0]!)?.id).toBe("msg_a");
|
||||||
|
|
||||||
|
// Step 4: Delete the root message (A)
|
||||||
|
// Root is soft-deleted, active child switches to B
|
||||||
|
msgA.deleted = true;
|
||||||
|
msgA.activeChildId = "msg_b";
|
||||||
|
|
||||||
|
tree = buildMessageTree([msgA, msgB]);
|
||||||
|
expect(tree.length).toBe(1);
|
||||||
|
expect(tree[0]!.deleted).toBe(true);
|
||||||
|
expect(getMessageCount(tree[0]!)).toBe(1);
|
||||||
|
expect(getCurrentChildIndex(tree[0]!)).toBe(0);
|
||||||
|
expect(getActiveMessage(tree[0]!)?.id).toBe("msg_b");
|
||||||
|
|
||||||
|
// Step 5: Regenerate the message -> creates child C with parentMessageId: msg_a
|
||||||
|
const msgC = {
|
||||||
|
...msgA,
|
||||||
|
id: "msg_c",
|
||||||
|
content: "Response 3",
|
||||||
|
parentMessageId: "msg_a",
|
||||||
|
deleted: false,
|
||||||
|
};
|
||||||
|
msgA.activeChildId = "msg_c";
|
||||||
|
|
||||||
|
tree = buildMessageTree([msgA, msgB, msgC]);
|
||||||
|
expect(tree.length).toBe(1);
|
||||||
|
expect(tree[0]!.children.length).toBe(2);
|
||||||
|
expect(getMessageCount(tree[0]!)).toBe(2);
|
||||||
|
// Crucial test: When C (second child) is active, index must be 1 (displayed as 2/2, NOT 3/2!)
|
||||||
|
expect(getCurrentChildIndex(tree[0]!)).toBe(1);
|
||||||
|
expect(getActiveMessage(tree[0]!)?.id).toBe("msg_c");
|
||||||
|
|
||||||
|
// Verify switching focus back to B works seamlessly
|
||||||
|
const backToB = getNextActiveChildId(tree[0]!, -1);
|
||||||
|
expect(backToB).toBe("msg_b");
|
||||||
|
msgA.activeChildId = backToB;
|
||||||
|
|
||||||
|
tree = buildMessageTree([msgA, msgB, msgC]);
|
||||||
|
expect(getCurrentChildIndex(tree[0]!)).toBe(0);
|
||||||
|
expect(getActiveMessage(tree[0]!)?.id).toBe("msg_b");
|
||||||
|
|
||||||
|
// Verify switching forward to C works seamlessly
|
||||||
|
const forwardToC = getNextActiveChildId(tree[0]!, 1);
|
||||||
|
expect(forwardToC).toBe("msg_c");
|
||||||
|
msgA.activeChildId = forwardToC;
|
||||||
|
|
||||||
|
tree = buildMessageTree([msgA, msgB, msgC]);
|
||||||
|
expect(getCurrentChildIndex(tree[0]!)).toBe(1);
|
||||||
|
expect(getActiveMessage(tree[0]!)?.id).toBe("msg_c");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("buildFocusedMessageTree excludes soft-deleted root messages", () => {
|
||||||
|
const root = {
|
||||||
|
id: "root",
|
||||||
|
userId: "user_1",
|
||||||
|
topicId: "topic_1",
|
||||||
|
role: "assistant" as const,
|
||||||
|
content: "Root",
|
||||||
|
parentMessageId: null,
|
||||||
|
generationId: null,
|
||||||
|
activeChildId: "child_1",
|
||||||
|
deleted: true,
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
parts: [],
|
||||||
|
generation: null,
|
||||||
|
attachments: [],
|
||||||
|
};
|
||||||
|
const child1 = {
|
||||||
|
...root,
|
||||||
|
id: "child_1",
|
||||||
|
content: "Child 1",
|
||||||
|
parentMessageId: "root",
|
||||||
|
activeChildId: null,
|
||||||
|
deleted: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const tree = buildMessageTree([root, child1]);
|
||||||
|
const focused = buildFocusedMessageTree(tree);
|
||||||
|
|
||||||
|
expect(focused.length).toBe(1);
|
||||||
|
expect(focused[0]!.id).toBe("child_1");
|
||||||
|
expect(focused[0]!.deleted).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("buildMessageTree filters out deleted roots with no children", () => {
|
||||||
|
const deletedEmptyRoot = {
|
||||||
|
id: "deleted_root",
|
||||||
|
userId: "user_1",
|
||||||
|
topicId: "topic_1",
|
||||||
|
role: "assistant" as const,
|
||||||
|
content: "Empty",
|
||||||
|
parentMessageId: null,
|
||||||
|
generationId: null,
|
||||||
|
activeChildId: null,
|
||||||
|
deleted: true,
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
parts: [],
|
||||||
|
generation: null,
|
||||||
|
attachments: [],
|
||||||
|
};
|
||||||
|
|
||||||
|
const tree = buildMessageTree([deletedEmptyRoot]);
|
||||||
|
expect(tree.length).toBe(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("getNextActiveChildId clamps to bounds and handles null fallback", () => {
|
||||||
|
const root = {
|
||||||
|
id: "root",
|
||||||
|
deleted: true,
|
||||||
|
activeChildId: null as string | null,
|
||||||
|
children: [
|
||||||
|
{ id: "child_a" },
|
||||||
|
{ id: "child_b" },
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
|
// If activeChildId is null and root is deleted, going left stays at child_a
|
||||||
|
expect(getNextActiveChildId(root, -1)).toBe("child_a");
|
||||||
|
// Going right moves to child_b
|
||||||
|
expect(getNextActiveChildId(root, 1)).toBe("child_b");
|
||||||
|
|
||||||
|
// When at child_b, going right clamps to child_b
|
||||||
|
root.activeChildId = "child_b";
|
||||||
|
expect(getNextActiveChildId(root, 1)).toBe("child_b");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import { addPendingRename, cancelPendingRename, completeRename } from "../server/utils/renames";
|
||||||
|
import { provisionalTopicTitle } from "../utils/topic-title";
|
||||||
|
|
||||||
|
describe("rename attempt ownership", () => {
|
||||||
|
test("an old completion cannot remove a newer attempt", () => {
|
||||||
|
addPendingRename("topic", "old");
|
||||||
|
const current = addPendingRename("topic", "new");
|
||||||
|
completeRename("topic", "old");
|
||||||
|
cancelPendingRename("topic", "new");
|
||||||
|
expect(current.signal.aborted).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("an old cancellation cannot abort a newer attempt", () => {
|
||||||
|
const current = addPendingRename("topic", "new");
|
||||||
|
cancelPendingRename("topic", "old");
|
||||||
|
expect(current.signal.aborted).toBe(false);
|
||||||
|
completeRename("topic", "new");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("cancellation is safe after completion or restart", () => {
|
||||||
|
cancelPendingRename("missing", "old");
|
||||||
|
const current = addPendingRename("topic", "new");
|
||||||
|
completeRename("topic", "new");
|
||||||
|
cancelPendingRename("topic", "new");
|
||||||
|
expect(current.signal.aborted).toBe(false);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("provisional titles", () => {
|
||||||
|
test("uses the first meaningful line and normalizes whitespace", () => {
|
||||||
|
expect(provisionalTopicTitle({ content: "\n Help me debug this\nMore details" })).toBe("Help me debug this");
|
||||||
|
});
|
||||||
|
test("names attachment-only conversations", () => {
|
||||||
|
expect(provisionalTopicTitle({ content: "", files: [{ name: "photo.jpg" }] })).toBe("photo.jpg");
|
||||||
|
expect(provisionalTopicTitle({ content: "", fileIds: ["image"] })).toBe("Attached files");
|
||||||
|
});
|
||||||
|
test("bounds title length and handles empty input", () => {
|
||||||
|
expect(provisionalTopicTitle({ content: "a".repeat(200) })).toHaveLength(100);
|
||||||
|
expect(provisionalTopicTitle()).toBe("New Topic");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,131 @@
|
|||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
import { createHash } from 'node:crypto';
|
||||||
|
import { topicEvents } from '../server/utils/events';
|
||||||
|
import { createTopicSnapshotStream } from '../server/utils/topic-snapshot-stream';
|
||||||
|
import { appendTextDelta, serializeTopicSnapshot } from '../utils/topic-sync';
|
||||||
|
|
||||||
|
const snapshot = () => ({
|
||||||
|
id: 'topic',
|
||||||
|
name: 'Example',
|
||||||
|
messages: [{
|
||||||
|
id: 'message',
|
||||||
|
activeChildId: null as string | null,
|
||||||
|
updatedAt: new Date('2026-09-27T00:00:00Z'),
|
||||||
|
generation: { status: 'pending', tokens: null as unknown },
|
||||||
|
parts: [{ id: 'part', type: 'text', content: 'hello', finished: false }],
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
const fingerprint = (value: unknown) => createHash('sha256').update(serializeTopicSnapshot(value)).digest('hex');
|
||||||
|
const readEvent = async (reader: ReadableStreamDefaultReader<string>) => {
|
||||||
|
const { value } = await reader.read();
|
||||||
|
return JSON.parse(value!.slice(6));
|
||||||
|
};
|
||||||
|
|
||||||
|
describe('topic snapshot synchronization', () => {
|
||||||
|
test('matches database Dates and hydrated JSON regardless of object key order', () => {
|
||||||
|
const topic = snapshot();
|
||||||
|
const hydrated = JSON.parse(JSON.stringify(topic));
|
||||||
|
expect(fingerprint({ messages: hydrated.messages, name: hydrated.name, id: hydrated.id })).toBe(fingerprint(topic));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('detects older-message, part, generation, variant, and topic changes without relying on count', () => {
|
||||||
|
const original = fingerprint(snapshot());
|
||||||
|
for (const change of [
|
||||||
|
(topic: ReturnType<typeof snapshot>) => topic.name = 'Renamed',
|
||||||
|
(topic: ReturnType<typeof snapshot>) => topic.messages[0]!.activeChildId = 'variant',
|
||||||
|
(topic: ReturnType<typeof snapshot>) => topic.messages[0]!.parts[0]!.content = 'edited',
|
||||||
|
(topic: ReturnType<typeof snapshot>) => topic.messages[0]!.parts[0]!.finished = true,
|
||||||
|
(topic: ReturnType<typeof snapshot>) => topic.messages[0]!.generation.tokens = { output: 123 },
|
||||||
|
]) {
|
||||||
|
const topic = snapshot();
|
||||||
|
change(topic);
|
||||||
|
expect(fingerprint(topic)).not.toBe(original);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('matching state receives a small ready event, then live changes', async () => {
|
||||||
|
const topic = snapshot();
|
||||||
|
const subscription = createTopicSnapshotStream('match', fingerprint(topic));
|
||||||
|
const result = await subscription.open(async () => topic);
|
||||||
|
expect(result.ok).toBe(true);
|
||||||
|
if (!result.ok) return;
|
||||||
|
const reader = result.data.getReader();
|
||||||
|
try {
|
||||||
|
expect(await readEvent(reader)).toEqual({ type: 'synced', payload: { id: 'match' } });
|
||||||
|
await topicEvents.emit('match', { type: 'topic_updated', payload: { name: 'New' } });
|
||||||
|
expect((await readEvent(reader)).payload).toEqual({ name: 'New' });
|
||||||
|
} finally {
|
||||||
|
await reader.cancel();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('stale or missing fingerprints receive a full replacement snapshot', async () => {
|
||||||
|
for (const offered of [undefined, fingerprint(snapshot())]) {
|
||||||
|
const topic = snapshot();
|
||||||
|
topic.messages[0]!.parts[0]!.content = 'changed';
|
||||||
|
const subscription = createTopicSnapshotStream('stale', offered);
|
||||||
|
const result = await subscription.open(async () => topic);
|
||||||
|
expect(result.ok).toBe(true);
|
||||||
|
if (!result.ok) continue;
|
||||||
|
const reader = result.data.getReader();
|
||||||
|
try {
|
||||||
|
const event = await readEvent(reader);
|
||||||
|
expect(event.type).toBe('initial_state');
|
||||||
|
expect(event.payload.messages[0].parts[0].content).toBe('changed');
|
||||||
|
} finally {
|
||||||
|
await reader.cancel();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('captures events during the DB query and includes text not yet persisted', async () => {
|
||||||
|
const id = 'query-race';
|
||||||
|
const initial = snapshot();
|
||||||
|
await topicEvents.emit(id, {
|
||||||
|
type: 'text-start', payload: { messageId: 'message', part: initial.messages[0]!.parts[0] },
|
||||||
|
});
|
||||||
|
// This delta predates subscription and has not reached the database yet.
|
||||||
|
await topicEvents.emit(id, {
|
||||||
|
type: 'text-delta', payload: { messageId: 'message', partId: 'part', content: ' world', offset: 5 },
|
||||||
|
});
|
||||||
|
const pending = Promise.withResolvers<ReturnType<typeof snapshot>>();
|
||||||
|
const subscription = createTopicSnapshotStream(id, fingerprint(initial));
|
||||||
|
const opening = subscription.open(() => pending.promise);
|
||||||
|
await topicEvents.emit(id, {
|
||||||
|
type: 'text-delta', payload: { messageId: 'message', partId: 'part', content: '!', offset: 11 },
|
||||||
|
});
|
||||||
|
pending.resolve(snapshot());
|
||||||
|
const result = await opening;
|
||||||
|
expect(result.ok).toBe(true);
|
||||||
|
if (!result.ok) return;
|
||||||
|
const reader = result.data.getReader();
|
||||||
|
try {
|
||||||
|
const state = await readEvent(reader);
|
||||||
|
expect(state.type).toBe('initial_state');
|
||||||
|
const text = state.payload.messages[0].parts[0].content;
|
||||||
|
expect(text).toBe('hello world!');
|
||||||
|
const replay = await readEvent(reader);
|
||||||
|
expect(replay.replay).toBe(true);
|
||||||
|
expect(appendTextDelta(text, replay.payload.content, replay.payload.offset)).toBe(text);
|
||||||
|
} finally {
|
||||||
|
await reader.cancel();
|
||||||
|
topicEvents.clearLiveText(id, 'message');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('cancellation during snapshot loading does not establish a stream', async () => {
|
||||||
|
const pending = Promise.withResolvers<ReturnType<typeof snapshot>>();
|
||||||
|
const subscription = createTopicSnapshotStream('cancelled', undefined);
|
||||||
|
const opening = subscription.open(() => pending.promise);
|
||||||
|
subscription.close();
|
||||||
|
pending.resolve(snapshot());
|
||||||
|
expect((await opening).ok).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('text offsets handle partial overlaps, duplicates, and gaps', () => {
|
||||||
|
expect(appendTextDelta('hello w', ' world', 5)).toBe('hello world');
|
||||||
|
expect(appendTextDelta('hello world', ' world', 5)).toBe('hello world');
|
||||||
|
expect(appendTextDelta('hello', '!', 5)).toBe('hello!');
|
||||||
|
expect(appendTextDelta('hello', '!', 10)).toBe('hello');
|
||||||
|
});
|
||||||
|
});
|
||||||
+88
-16
@@ -1,9 +1,86 @@
|
|||||||
import type { AssistantContent, FilePart, ImagePart, JSONValue, ModelMessage, ToolContent } from "ai";
|
import type { AssistantContent, FilePart, ImagePart, JSONValue, ModelMessage, ToolContent } from "ai";
|
||||||
import { ToolCallType } from "~~/drizzle/schema";
|
import { ToolCallType } from "../drizzle/schema";
|
||||||
import { Err, Ok, type Result } from "~~/types/result";
|
import { Err, Ok, type Result } from "../types/result";
|
||||||
import type { Message, MessageEntity } from "~/composables/useChat";
|
import type { Message, MessageEntity } from "../app/composables/useChat";
|
||||||
import type { Agent } from "~/composables/useAgents";
|
import type { Agent } from "../app/composables/useAgents";
|
||||||
import { resolveFileUrl } from "~~/utils/url";
|
import { resolveFileUrl } from "./url";
|
||||||
|
|
||||||
|
export const getActiveMessage = <T extends { id: string; deleted?: boolean | null; activeChildId?: string | null; children: (T | undefined)[] }>(
|
||||||
|
message: T
|
||||||
|
): T | null => {
|
||||||
|
if (message.activeChildId && message.children.length > 0) {
|
||||||
|
const child = message.children.find(c => c?.id === message.activeChildId);
|
||||||
|
if (child) {
|
||||||
|
return child;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message.deleted === true) {
|
||||||
|
if (message.children.length > 0 && message.children[0]) {
|
||||||
|
return message.children[0];
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return message;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getMessageCount = (message: {
|
||||||
|
deleted?: boolean | null;
|
||||||
|
children: unknown[];
|
||||||
|
}): number => {
|
||||||
|
if (message.deleted === true) {
|
||||||
|
return message.children.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
return message.children.length + 1;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getCurrentChildIndex = (message: {
|
||||||
|
deleted?: boolean | null;
|
||||||
|
activeChildId?: string | null;
|
||||||
|
children: ({ id: string } | undefined)[];
|
||||||
|
}): number => {
|
||||||
|
if (message.deleted === true) {
|
||||||
|
if (!message.activeChildId) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const idx = message.children.findIndex(c => c?.id === message.activeChildId);
|
||||||
|
return idx >= 0 ? idx : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!message.activeChildId) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const idx = message.children.findIndex(c => c?.id === message.activeChildId);
|
||||||
|
return idx >= 0 ? idx + 1 : 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getNextActiveChildId = (
|
||||||
|
message: {
|
||||||
|
deleted?: boolean | null;
|
||||||
|
activeChildId?: string | null;
|
||||||
|
children: ({ id: string } | undefined)[];
|
||||||
|
},
|
||||||
|
direction: -1 | 1
|
||||||
|
): string | null => {
|
||||||
|
const allItems = message.deleted === true
|
||||||
|
? message.children
|
||||||
|
: [null, ...message.children];
|
||||||
|
|
||||||
|
const currentIdx = allItems.findIndex(item => {
|
||||||
|
if (!item) {
|
||||||
|
return !message.activeChildId;
|
||||||
|
}
|
||||||
|
return item.id === message.activeChildId;
|
||||||
|
});
|
||||||
|
|
||||||
|
const validCurrentIdx = currentIdx >= 0 ? currentIdx : 0;
|
||||||
|
const newIdx = Math.max(0, Math.min(allItems.length - 1, validCurrentIdx + direction));
|
||||||
|
const newItem = allItems[newIdx];
|
||||||
|
|
||||||
|
return newItem?.id ?? null;
|
||||||
|
};
|
||||||
|
|
||||||
export const buildMessageTree = (flatMessages: MessageEntity[]) => {
|
export const buildMessageTree = (flatMessages: MessageEntity[]) => {
|
||||||
const messagesMap = new Map(flatMessages.map(m => [m.id, { ...m, children: [] as MessageEntity[] }]));
|
const messagesMap = new Map(flatMessages.map(m => [m.id, { ...m, children: [] as MessageEntity[] }]));
|
||||||
@@ -16,26 +93,21 @@ export const buildMessageTree = (flatMessages: MessageEntity[]) => {
|
|||||||
roots.push(msg);
|
roots.push(msg);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return roots;
|
return roots.filter(root => !root.deleted || root.children.length > 0);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const buildFocusedMessageTree = (messages: Readonly<Message[]>): MessageEntity[] => {
|
export const buildFocusedMessageTree = (messages: Readonly<Message[]>): MessageEntity[] => {
|
||||||
let focusedMessageTree: MessageEntity[] = [];
|
const focusedMessageTree: MessageEntity[] = [];
|
||||||
|
|
||||||
for (const message of messages) {
|
for (const message of messages) {
|
||||||
if (message.activeChildId && message.children.length > 0) {
|
const activeMessage = getActiveMessage(message);
|
||||||
const activeChild = message.children.find(c => c?.id === message.activeChildId);
|
if (activeMessage) {
|
||||||
if (activeChild) {
|
focusedMessageTree.push(activeMessage);
|
||||||
focusedMessageTree.push(activeChild);
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
focusedMessageTree.push(message);
|
|
||||||
}
|
|
||||||
|
|
||||||
return focusedMessageTree;
|
return focusedMessageTree;
|
||||||
}
|
};
|
||||||
|
|
||||||
export interface MarshallOptions {
|
export interface MarshallOptions {
|
||||||
signFileUrl?: (fileKey: string) => string;
|
signFileUrl?: (fileKey: string) => string;
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
/** Stable across database Dates, JSON SSE payloads, and Nuxt hydration. */
|
||||||
|
export const serializeTopicSnapshot = (topic: unknown): string => JSON.stringify(topic, (_key, value) => {
|
||||||
|
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Object.fromEntries(Object.keys(value).sort().map(key => [key, value[key]]));
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Absolute offsets make replay across a snapshot boundary idempotent. */
|
||||||
|
export const appendTextDelta = (current: string, content: string, offset?: number): string => {
|
||||||
|
if (offset === undefined) {
|
||||||
|
return current + content;
|
||||||
|
}
|
||||||
|
if (offset > current.length) {
|
||||||
|
// A gap requires reconciliation, not silently concatenating corrupt text.
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
const overlap = current.length - offset;
|
||||||
|
return overlap >= content.length ? current : current + content.slice(overlap);
|
||||||
|
};
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
export const provisionalTopicTitle = (message?: {
|
||||||
|
content: string;
|
||||||
|
files?: { name: string }[];
|
||||||
|
fileIds?: string[];
|
||||||
|
}): string => {
|
||||||
|
const line = message?.content.split(/\r?\n/).map(line => line.trim()).find(Boolean);
|
||||||
|
const title = line || message?.files?.[0]?.name || (message?.fileIds?.length ? "Attached files" : "New Topic");
|
||||||
|
return title.replace(/\s+/g, " ").slice(0, 100);
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user