This commit is contained in:
Timothy Jaeryang Baek
2026-07-15 23:21:06 -04:00
parent f7af03ff26
commit ee000c503c
7 changed files with 382 additions and 233 deletions
+12 -85
View File
@@ -107,8 +107,6 @@
import EventConfirmDialog from '../common/ConfirmDialog.svelte';
import DeleteConfirmDialog from '../common/ConfirmDialog.svelte';
import WebSearchConfirmDialog from '../common/ConfirmDialog.svelte';
import Dropdown from '../common/Dropdown.svelte';
import DropdownMenu from '../common/DropdownMenu.svelte';
import Placeholder from './Placeholder.svelte';
import FilesOverlay from './MessageInput/FilesOverlay.svelte';
import NotificationToast from '../NotificationToast.svelte';
@@ -118,9 +116,7 @@
import Sidebar from '../icons/Sidebar.svelte';
import Image from '../common/Image.svelte';
import XMark from '../icons/XMark.svelte';
import EditPencilIcon from '../layout/Sidebar/icons/EditPencil.svelte';
import ChevronRight from '../icons/ChevronRight.svelte';
import EmbeddedChatHistoryItem from './EmbeddedChatHistoryItem.svelte';
import EmbeddedChatHistoryDropdown from './EmbeddedChatHistoryDropdown.svelte';
export let chatIdProp = '';
export let embedded = false;
@@ -146,9 +142,6 @@
'Extract action items from this note.',
'Rewrite the selected text.'
];
let showEmbeddedChatHistory = false;
let embeddedChatOptionsId = '';
let deletingEmbeddedChatId = '';
const eventTarget = new EventTarget();
let controlPane: Pane | undefined;
@@ -402,7 +395,7 @@
};
const withSelectedText = (text: string) =>
embedded && selectedText?.trim()
? `${text}\n\nSelected note text:\n${selectedText.trim()}`
? `${text}\n\nSelected note text for replace_note_content operations:\n${selectedText.trim()}`
: text;
const noteChatDebug = (message: string, data: Record<string, unknown> = {}) => {
if (!embedded) return;
@@ -3622,82 +3615,16 @@
class="h-10 shrink-0 flex items-center justify-between gap-2 border-b border-gray-50/80 px-3 text-gray-700 dark:border-gray-850/40 dark:text-gray-200"
>
<div class="flex min-w-0 items-center gap-2">
<Dropdown
bind:show={showEmbeddedChatHistory}
align="start"
sideOffset={6}
closeOnOutsideClick={embeddedChatOptionsId === ''}
onOpenChange={(state) => {
if (!state) embeddedChatOptionsId = '';
}}
>
<button
type="button"
class="group flex min-w-0 items-center gap-1 text-[13px] font-normal text-gray-600 transition hover:text-gray-900 dark:text-gray-300 dark:hover:text-white"
aria-label={$i18n.t('Chat history')}
>
<span class="min-w-0 truncate">{embeddedHeaderTitle}</span>
<ChevronRight
className="size-3.5 shrink-0 text-gray-400/70 opacity-0 transition-opacity group-hover:opacity-100 dark:text-gray-500/70"
strokeWidth="2"
/>
</button>
<div slot="content">
<DropdownMenu
className="min-w-56 max-w-72 max-h-80 overflow-y-auto scrollbar-hidden"
>
{#if onNewEmbeddedChat && Object.keys(history?.messages ?? {}).length > 0 && !loading}
<button
type="button"
class="text-left"
on:click={async () => {
showEmbeddedChatHistory = false;
await onNewEmbeddedChat?.();
}}
>
<EditPencilIcon className="size-3.5" strokeWidth="1.5" />
<span class="min-w-0 truncate">{$i18n.t('New chat')}</span>
</button>
<hr class="border-gray-100/70 dark:border-gray-800/60" />
{/if}
{#if embeddedChats.length > 0}
{#each embeddedChats as item}
<EmbeddedChatHistoryItem
{item}
title={item?.id === $chatId
? embeddedHeaderTitle
: item?.title || item?.chat?.title || $i18n.t('Chat')}
selected={item.id === $chatId}
deleting={deletingEmbeddedChatId === item.id}
onSelect={async () => {
showEmbeddedChatHistory = false;
await onSelectEmbeddedChat?.(item.id);
}}
onDelete={async (id) => {
if (!id || deletingEmbeddedChatId) return;
deletingEmbeddedChatId = id;
embeddedChatOptionsId = '';
try {
await onDeleteEmbeddedChat?.(id);
} finally {
deletingEmbeddedChatId = '';
}
}}
onMenuOpenChange={(id, state) => {
embeddedChatOptionsId = state ? id : '';
}}
/>
{/each}
{:else}
<div class="px-2 py-1.5 text-[13px] text-gray-400 dark:text-gray-500">
{$i18n.t('No chat history')}
</div>
{/if}
</DropdownMenu>
</div>
</Dropdown>
<EmbeddedChatHistoryDropdown
title={embeddedHeaderTitle}
chats={embeddedChats}
canCreateNew={!!onNewEmbeddedChat &&
Object.keys(history?.messages ?? {}).length > 0}
{loading}
onNewChat={onNewEmbeddedChat}
onSelectChat={onSelectEmbeddedChat}
onDeleteChat={onDeleteEmbeddedChat}
/>
</div>
<Tooltip content={$i18n.t('Close')} placement="bottom">
<button
@@ -0,0 +1,101 @@
<script lang="ts">
import { getContext } from 'svelte';
import { chatId } from '$lib/stores';
import Dropdown from '$lib/components/common/Dropdown.svelte';
import DropdownMenu from '$lib/components/common/DropdownMenu.svelte';
import ChevronRight from '$lib/components/icons/ChevronRight.svelte';
import EditPencilIcon from '$lib/components/layout/Sidebar/icons/EditPencil.svelte';
import EmbeddedChatHistoryItem from './EmbeddedChatHistoryItem.svelte';
const i18n = getContext('i18n');
export let title = '';
export let chats = [];
export let canCreateNew = false;
export let loading = false;
export let onNewChat: (() => void | Promise<void>) | null = null;
export let onSelectChat: ((chatId: string) => void | Promise<void>) | null = null;
export let onDeleteChat: ((chatId: string) => void | Promise<void>) | null = null;
let show = false;
let optionsChatId = '';
let deletingChatId = '';
</script>
<Dropdown
bind:show
align="start"
sideOffset={6}
closeOnOutsideClick={optionsChatId === ''}
onOpenChange={(state) => {
if (!state) optionsChatId = '';
}}
>
<button
type="button"
class="group flex min-w-0 items-center gap-1 text-[13px] font-normal text-gray-600 transition hover:text-gray-900 dark:text-gray-300 dark:hover:text-white"
aria-label={$i18n.t('Chat history')}
>
<span class="min-w-0 truncate">{title}</span>
<ChevronRight
className="size-3.5 shrink-0 text-gray-400/70 opacity-0 transition-opacity group-hover:opacity-100 dark:text-gray-500/70"
strokeWidth="2"
/>
</button>
<div slot="content">
<DropdownMenu className="min-w-56 max-w-72 max-h-80 overflow-y-auto scrollbar-hidden">
{#if canCreateNew && !loading}
<button
type="button"
class="text-left"
on:click={async () => {
show = false;
await onNewChat?.();
}}
>
<EditPencilIcon className="size-3.5" strokeWidth="1.5" />
<span class="min-w-0 truncate">{$i18n.t('New chat')}</span>
</button>
<hr class="border-gray-100/70 dark:border-gray-800/60" />
{/if}
{#if chats.length > 0}
{#each chats as item}
<EmbeddedChatHistoryItem
{item}
title={item?.id === $chatId
? title
: item?.title || item?.chat?.title || $i18n.t('Chat')}
selected={item.id === $chatId}
deleting={deletingChatId === item.id}
onSelect={async () => {
show = false;
await onSelectChat?.(item.id);
}}
onDelete={async (id) => {
if (!id || deletingChatId) return;
deletingChatId = id;
optionsChatId = '';
try {
await onDeleteChat?.(id);
} finally {
deletingChatId = '';
}
}}
onMenuOpenChange={(id, state) => {
optionsChatId = state ? id : '';
}}
/>
{/each}
{:else}
<div class="px-2 py-1.5 text-[13px] text-gray-400 dark:text-gray-500">
{$i18n.t('No chat history')}
</div>
{/if}
</DropdownMenu>
</div>
</Dropdown>
@@ -21,14 +21,16 @@
let showMenu = false;
</script>
<button
type="button"
class="group/item flex h-8 w-full cursor-pointer select-none items-center rounded-xl px-2 text-left text-[13px] font-normal text-gray-700 outline-hidden transition-colors duration-75 hover:bg-gray-50/40 dark:text-gray-100 dark:hover:bg-gray-800/40 {selected
<div
class="group/item flex h-[1.6875rem] w-full cursor-pointer select-none items-center rounded-xl px-2 text-left text-[13px] font-normal text-gray-700 outline-hidden transition-colors duration-75 hover:bg-gray-50/40 dark:text-gray-100 dark:hover:bg-gray-800/40 [&_button:hover]:bg-transparent! dark:[&_button:hover]:bg-transparent! {selected
? 'bg-gray-50/70 dark:bg-gray-800/60'
: ''}"
on:click={() => onSelect(item.id)}
>
<div class="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">
<button
type="button"
class="flex h-full min-w-0 flex-1 items-center gap-2 overflow-hidden p-0 text-left outline-hidden"
on:click={() => onSelect(item.id)}
>
<div class="min-w-0 truncate">{title}</div>
{#if selected}
@@ -36,9 +38,13 @@
{$i18n.t('Current')}
</div>
{/if}
</div>
</button>
<div class="ml-auto flex shrink-0 items-center gap-1.5 pl-2">
<div
class="{showMenu
? 'visible'
: 'invisible group-hover/item:visible'} ml-auto flex shrink-0 items-center gap-1.5 pl-2"
>
<Dropdown
bind:show={showMenu}
align="end"
@@ -52,7 +58,7 @@
<button
type="button"
aria-label={$i18n.t('More Options')}
class="flex"
class="flex size-5 items-center justify-center self-center transition dark:hover:text-white"
on:click={(e) => {
e.preventDefault();
e.stopPropagation();
@@ -85,4 +91,4 @@
</div>
</Dropdown>
</div>
</button>
</div>
+125 -22
View File
@@ -143,6 +143,9 @@
let selectedContent = null;
let noteChatFiles = [];
let pendingNoteEvent = null;
let pendingNoteEventTimer = null;
let lastLocalContentChangeAt = 0;
$: {
const seen = new Set();
noteChatFiles = note
@@ -186,15 +189,14 @@
}
files = res.data.files || [];
if (note?.write_access) {
$socket?.emit('join-note', {
note_id: id,
auth: {
token: localStorage.token
}
});
$socket?.on('events:note', noteEventHandler);
}
$socket?.emit('join-note', {
note_id: id,
auth: {
token: localStorage.token
}
});
$socket?.off('events:note', noteEventHandler);
$socket?.on('events:note', noteEventHandler);
} else {
goto('/');
return;
@@ -227,6 +229,94 @@
}, 200);
};
const applyExternalNoteContent = async (_note) => {
const incomingContent = _note.data?.content;
const contentLength = incomingContent?.md?.length ?? incomingContent?.html?.length ?? 0;
console.info('[note-chat] external note event apply requested', {
noteId: _note.id,
eventUpdatedAt: _note.updated_at,
currentUpdatedAt: note?.updated_at,
editorPresent: !!editor,
contentLength
});
if (_note.updated_at && note?.updated_at && _note.updated_at < note.updated_at) {
console.info('[note-chat] external note event skipped', {
noteId: _note.id,
reason: 'stale',
eventUpdatedAt: _note.updated_at,
currentUpdatedAt: note.updated_at,
contentLength
});
return false;
}
const elapsed = Date.now() - lastLocalContentChangeAt;
if (elapsed < 800) {
pendingNoteEvent = _note;
if (pendingNoteEventTimer) {
clearTimeout(pendingNoteEventTimer);
}
pendingNoteEventTimer = setTimeout(async () => {
const event = pendingNoteEvent;
pendingNoteEvent = null;
if (event) {
await applyExternalNoteContent(event);
}
}, 850 - elapsed);
console.info('[note-chat] external note event deferred', {
noteId: _note.id,
reason: 'local-edit-settling',
eventUpdatedAt: _note.updated_at,
contentLength
});
return false;
}
note.data.content = {
...note.data.content,
...incomingContent
};
if (_note.updated_at) {
note.updated_at = _note.updated_at;
}
if (!editor) {
console.info('[note-chat] external note event applied', {
noteId: _note.id,
reason: 'no-editor',
eventUpdatedAt: _note.updated_at,
contentLength
});
return true;
}
const selection = editor.state.selection;
editor.commands.setContent(incomingContent.html || marked.parse(incomingContent.md ?? ''));
await tick();
const docSize = editor.state.doc.content.size;
const from = Math.min(selection.from, docSize);
const to = Math.min(selection.to, docSize);
if (from < to) {
editor.commands.setTextSelection({ from, to });
const text = editor.state.doc.textBetween(from, to, ' ');
selectedContent = text ? { text, from, to } : null;
} else {
selectedContent = null;
}
console.info('[note-chat] external note event applied', {
noteId: _note.id,
reason: 'content',
eventUpdatedAt: _note.updated_at,
contentLength
});
return true;
};
$: if (id) {
init();
}
@@ -754,6 +844,17 @@ ${content}
console.log('noteEventHandler', _note);
if (_note.id !== id) return;
if (_note.updated_at && note?.updated_at && _note.updated_at < note.updated_at) {
console.info('[note-chat] external note event skipped', {
noteId: _note.id,
reason: 'stale-event',
eventUpdatedAt: _note.updated_at,
currentUpdatedAt: note.updated_at,
contentLength: _note.data?.content?.md?.length ?? _note.data?.content?.html?.length ?? 0
});
return;
}
if (_note.access_grants && _note.access_grants !== note.access_grants) {
note.access_grants = _note.access_grants;
}
@@ -764,22 +865,20 @@ ${content}
}
if (_note.data?.content) {
note.data.content = {
...note.data.content,
..._note.data.content
};
if (editor) {
editor.commands.setContent(
_note.data.content.html || marked.parse(_note.data.content.md ?? '')
);
}
await applyExternalNoteContent(_note);
}
if (_note.title && _note.title) {
note.title = _note.title;
}
editor.storage.files = files;
if (_note.updated_at) {
note.updated_at = _note.updated_at;
}
if (editor) {
editor.storage.files = files;
}
await tick();
for (const file of files) {
@@ -830,6 +929,9 @@ ${content}
onDestroy(() => {
console.log('destroy');
$socket?.off('events:note', noteEventHandler);
if (pendingNoteEventTimer) {
clearTimeout(pendingNoteEventTimer);
}
const dropzoneElement = document.getElementById('note-editor');
@@ -945,11 +1047,11 @@ ${content}
{#if titleInputFocused && !titleGenerating}
<div
class="flex self-center items-center space-x-1.5 z-10 translate-y-[0.5px] -translate-x-[0.5px] pl-2"
class="flex self-center items-center space-x-1.5 z-10 translate-y-[0.5px] -translate-x-[0.5px] pl-2 pr-0.5"
>
<Tooltip content={$i18n.t('Generate')}>
<button
class=" self-center dark:hover:text-white transition"
class="flex size-5 items-center justify-center self-center dark:hover:text-white transition disabled:cursor-not-allowed"
id="generate-title-button"
disabled={(note?.user_id !== $user?.id && $user?.role !== 'admin') ||
titleGenerating}
@@ -965,7 +1067,7 @@ ${content}
titleInputFocused = false;
}}
>
<Sparkles strokeWidth="2" />
<Sparkles strokeWidth="1.5" />
</button>
</Tooltip>
</div>
@@ -1222,6 +1324,7 @@ ${content}
}
}}
onChange={(content) => {
lastLocalContentChangeAt = Date.now();
note.data.content.html = content.html;
note.data.content.md = content.md;