mirror of
https://github.com/MODSetter/SurfSense.git
synced 2026-05-23 19:05:16 +02:00
Merge remote-tracking branch 'upstream/dev' into feat/ui-revamp
This commit is contained in:
commit
87caa4b6d0
29 changed files with 1622 additions and 891 deletions
|
|
@ -24,6 +24,8 @@ import dynamic from "next/dynamic";
|
|||
import type { FC } from "react";
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import { commentsEnabledAtom, targetCommentIdAtom } from "@/atoms/chat/current-thread.atom";
|
||||
import { tryGetHostname } from "@/lib/url";
|
||||
|
||||
import {
|
||||
globalNewLLMConfigsAtom,
|
||||
newLLMConfigsAtom,
|
||||
|
|
@ -99,20 +101,12 @@ const GenerateImageToolUI = dynamic(
|
|||
import("@/components/tool-ui/generate-image").then((m) => ({ default: m.GenerateImageToolUI })),
|
||||
{ ssr: false }
|
||||
);
|
||||
function extractDomain(url: string): string | undefined {
|
||||
try {
|
||||
return new URL(url).hostname.replace(/^www\./, "");
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function useCitationsFromMetadata(): SerializableCitation[] {
|
||||
const allCitations = useAllCitationMetadata();
|
||||
return useMemo(() => {
|
||||
const result: SerializableCitation[] = [];
|
||||
for (const [url, meta] of allCitations) {
|
||||
const domain = extractDomain(url);
|
||||
const domain = tryGetHostname(url);
|
||||
result.push({
|
||||
id: `url-cite-${url}`,
|
||||
href: url,
|
||||
|
|
|
|||
|
|
@ -242,14 +242,7 @@ const SurfsenseDocPreviewContent: FC<{
|
|||
);
|
||||
};
|
||||
|
||||
function extractDomain(url: string): string {
|
||||
try {
|
||||
const hostname = new URL(url).hostname;
|
||||
return hostname.replace(/^www\./, "");
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
import { tryGetHostname } from "@/lib/url";
|
||||
|
||||
interface UrlCitationProps {
|
||||
url: string;
|
||||
|
|
@ -261,7 +254,7 @@ interface UrlCitationProps {
|
|||
* page title and snippet (extracted deterministically from web_search tool results).
|
||||
*/
|
||||
export const UrlCitation: FC<UrlCitationProps> = ({ url }) => {
|
||||
const domain = extractDomain(url);
|
||||
const domain = tryGetHostname(url) ?? url;
|
||||
const meta = useCitationMetadata(url);
|
||||
|
||||
return (
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
"use client";
|
||||
|
||||
import { Folder as FolderIcon } from "lucide-react";
|
||||
import { Folder as FolderIcon, X as XIcon } from "lucide-react";
|
||||
import type { NodeEntry, TElement } from "platejs";
|
||||
import type { PlateElementProps } from "platejs/react";
|
||||
import {
|
||||
createPlatePlugin,
|
||||
|
|
@ -9,7 +10,16 @@ import {
|
|||
PlateContent,
|
||||
usePlateEditor,
|
||||
} from "platejs/react";
|
||||
import { type FC, forwardRef, useCallback, useImperativeHandle, useMemo, useRef } from "react";
|
||||
import {
|
||||
createContext,
|
||||
type FC,
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useContext,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
useRef,
|
||||
} from "react";
|
||||
import { FOLDER_MENTION_DOCUMENT_TYPE } from "@/atoms/chat/mentioned-documents.atom";
|
||||
import { getConnectorIcon } from "@/contracts/enums/connectorIcons";
|
||||
import type { Document } from "@/contracts/types/document.types";
|
||||
|
|
@ -26,13 +36,9 @@ export interface MentionedDocument {
|
|||
}
|
||||
|
||||
/**
|
||||
* Input shape for inserting a chip. ``kind`` defaults to ``"doc"``
|
||||
* when omitted so legacy callers don't have to thread the
|
||||
* discriminator. Folder callers pass ``kind: "folder"`` and the
|
||||
* folder ``id`` and ``title``; ``document_type`` defaults to
|
||||
* ``FOLDER_MENTION_DOCUMENT_TYPE`` inside ``insertMentionChip`` so the
|
||||
* dedup key (`kind:document_type:id`) never collides with a doc chip
|
||||
* that happens to share an id.
|
||||
* Input shape for inserting a chip. ``kind`` defaults to ``"doc"``.
|
||||
* Folder chips default ``document_type`` to ``FOLDER_MENTION_DOCUMENT_TYPE``
|
||||
* so the dedup key never collides with a doc chip sharing the same id.
|
||||
*/
|
||||
export type MentionChipInput = {
|
||||
id: number;
|
||||
|
|
@ -87,12 +93,7 @@ type MentionElementNode = {
|
|||
id: number;
|
||||
title: string;
|
||||
document_type?: string;
|
||||
/**
|
||||
* Discriminator added so a folder chip and a doc chip with the
|
||||
* same id round-trip cleanly through ``getMentionedDocuments``
|
||||
* and the persisted ``mentioned-documents`` content part.
|
||||
* Defaults to ``"doc"`` for nodes that predate this field.
|
||||
*/
|
||||
/** Discriminator; defaults to ``"doc"`` for legacy nodes. */
|
||||
kind?: MentionKind;
|
||||
statusLabel?: string | null;
|
||||
statusKind?: MentionStatusKind;
|
||||
|
|
@ -104,13 +105,22 @@ type ComposerValue = ComposerParagraph[];
|
|||
|
||||
const MENTION_TYPE = "mention";
|
||||
const MENTION_CHIP_CLASSNAME =
|
||||
"inline-flex h-5 items-center gap-1 mx-0.5 rounded bg-primary/10 px-1 text-xs font-bold text-primary/60 select-none align-middle leading-none";
|
||||
"group inline-flex h-5 items-center gap-1 mx-0.5 rounded bg-primary/10 px-1 text-xs font-bold text-primary/60 select-none align-middle leading-none";
|
||||
const MENTION_CHIP_ICON_CLASSNAME = "flex items-center text-muted-foreground leading-none";
|
||||
const MENTION_CHIP_TITLE_CLASSNAME = "max-w-[120px] truncate leading-none";
|
||||
const COMPOSER_TEXT_METRICS_CLASSNAME = "text-sm leading-6";
|
||||
|
||||
const EMPTY_VALUE: ComposerValue = [{ type: "p", children: [{ text: "" }] }];
|
||||
|
||||
/**
|
||||
* Lets ``MentionElement`` reach the editor's chip-removal helper so
|
||||
* the X button and Backspace go through the same call site.
|
||||
*/
|
||||
type MentionEditorContextValue = {
|
||||
removeChip: (docId: number, docType: string | undefined) => void;
|
||||
};
|
||||
const MentionEditorContext = createContext<MentionEditorContextValue | null>(null);
|
||||
|
||||
const MentionElement: FC<PlateElementProps<MentionElementNode>> = ({
|
||||
attributes,
|
||||
children,
|
||||
|
|
@ -124,16 +134,36 @@ const MentionElement: FC<PlateElementProps<MentionElementNode>> = ({
|
|||
: "text-amber-700";
|
||||
|
||||
const isFolder = element.kind === "folder";
|
||||
const ctx = useContext(MentionEditorContext);
|
||||
|
||||
return (
|
||||
<span {...attributes} className="inline-flex align-middle">
|
||||
<span contentEditable={false} className={`${MENTION_CHIP_CLASSNAME} cursor-default`}>
|
||||
<span className={MENTION_CHIP_ICON_CLASSNAME}>
|
||||
{isFolder ? (
|
||||
<FolderIcon className="h-3 w-3" />
|
||||
) : (
|
||||
getConnectorIcon(element.document_type ?? "UNKNOWN", "h-3 w-3")
|
||||
)}
|
||||
<span className="relative flex h-3 w-3 items-center justify-center">
|
||||
<span className="flex items-center justify-center transition-opacity group-hover:opacity-0">
|
||||
{isFolder ? (
|
||||
<FolderIcon className="h-3 w-3" />
|
||||
) : (
|
||||
getConnectorIcon(element.document_type ?? "UNKNOWN", "h-3 w-3")
|
||||
)}
|
||||
</span>
|
||||
{ctx ? (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Remove mention ${element.title}`}
|
||||
title={`Remove ${element.title}`}
|
||||
onMouseDown={(e) => e.preventDefault()}
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
ctx.removeChip(element.id, element.document_type);
|
||||
}}
|
||||
className="absolute inset-0 flex items-center justify-center rounded-sm opacity-0 transition-opacity hover:text-primary focus-visible:opacity-100 focus-visible:outline-none group-hover:opacity-100"
|
||||
>
|
||||
<XIcon className="h-3 w-3" />
|
||||
</button>
|
||||
) : null}
|
||||
</span>
|
||||
</span>
|
||||
<span className={MENTION_CHIP_TITLE_CLASSNAME} title={element.title}>
|
||||
{element.title}
|
||||
|
|
@ -294,17 +324,16 @@ export const InlineMentionEditor = forwardRef<InlineMentionEditorRef, InlineMent
|
|||
value: initialText ? toValueFromText(initialText) : EMPTY_VALUE,
|
||||
});
|
||||
|
||||
// Move the caret to end-of-doc and focus the editor. Falls back
|
||||
// to DOM focus if Plate's API throws (transient unmount race).
|
||||
const focusAtEnd = useCallback(() => {
|
||||
const el = editableRef.current;
|
||||
if (!el) return;
|
||||
el.focus();
|
||||
const selection = window.getSelection();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(el);
|
||||
range.collapse(false);
|
||||
selection?.removeAllRanges();
|
||||
selection?.addRange(range);
|
||||
}, []);
|
||||
try {
|
||||
editor.tf.select(editor.api.end([]));
|
||||
editor.tf.focus();
|
||||
} catch {
|
||||
editableRef.current?.focus();
|
||||
}
|
||||
}, [editor]);
|
||||
|
||||
const getCurrentValue = useCallback(
|
||||
() => (editor.children as ComposerValue) ?? EMPTY_VALUE,
|
||||
|
|
@ -352,13 +381,18 @@ export const InlineMentionEditor = forwardRef<InlineMentionEditorRef, InlineMent
|
|||
[editor, emitState]
|
||||
);
|
||||
|
||||
// Insert chip + trailing space as a single ``insertNodes`` call.
|
||||
// The chip is a void inline; ``select: true`` on it alone would
|
||||
// land the caret inside its empty children (an unrenderable
|
||||
// point). With the space as the last inserted node, the caret
|
||||
// resolves to that text node and stays visible. The
|
||||
// ``withoutNormalizing`` wrapper batches the optional trigger
|
||||
// delete + insert into a single undo step.
|
||||
const insertMentionChip = useCallback(
|
||||
(mention: MentionChipInput, options?: { removeTriggerText?: boolean }) => {
|
||||
if (typeof mention.id !== "number" || typeof mention.title !== "string") return;
|
||||
|
||||
const removeTriggerText = options?.removeTriggerText ?? true;
|
||||
const current = getCurrentValue();
|
||||
const selection = editor.selection;
|
||||
const kind: MentionKind = mention.kind ?? "doc";
|
||||
const document_type =
|
||||
mention.document_type ?? (kind === "folder" ? FOLDER_MENTION_DOCUMENT_TYPE : undefined);
|
||||
|
|
@ -371,65 +405,48 @@ export const InlineMentionEditor = forwardRef<InlineMentionEditorRef, InlineMent
|
|||
children: [{ text: "" }],
|
||||
};
|
||||
|
||||
const cursorCtx = getCursorTextContext(current, selection);
|
||||
if (!cursorCtx) {
|
||||
const lastBlock = current[current.length - 1] ?? { type: "p", children: [{ text: "" }] };
|
||||
const appended: ComposerValue = [
|
||||
...current.slice(0, -1),
|
||||
{
|
||||
...lastBlock,
|
||||
children: [...lastBlock.children, mentionNode, { text: " " }],
|
||||
},
|
||||
];
|
||||
setValue(appended);
|
||||
requestAnimationFrame(focusAtEnd);
|
||||
return;
|
||||
}
|
||||
editor.tf.withoutNormalizing(() => {
|
||||
const selection = editor.selection;
|
||||
|
||||
const block = current[cursorCtx.blockIndex];
|
||||
const currentChild = getTextNode(block.children[cursorCtx.childIndex]);
|
||||
if (!currentChild) {
|
||||
const children = [...block.children];
|
||||
children.splice(cursorCtx.childIndex + 1, 0, mentionNode, { text: " " });
|
||||
const next = [...current];
|
||||
next[cursorCtx.blockIndex] = { ...block, children };
|
||||
setValue(next as ComposerValue);
|
||||
requestAnimationFrame(focusAtEnd);
|
||||
return;
|
||||
}
|
||||
|
||||
const text = currentChild.text;
|
||||
let removeStart = cursorCtx.cursor;
|
||||
if (removeTriggerText) {
|
||||
for (let i = cursorCtx.cursor - 1; i >= 0; i--) {
|
||||
if (text[i] === "@") {
|
||||
removeStart = i;
|
||||
break;
|
||||
// No active selection (focus moved to a picker) — snap
|
||||
// to end-of-doc so the chip appends cleanly.
|
||||
if (!selection) {
|
||||
editor.tf.select(editor.api.end([]));
|
||||
} else if (removeTriggerText) {
|
||||
// Delete the in-progress "@query" so the chip stands in for it.
|
||||
const cursorCtx = getCursorTextContext(getCurrentValue(), selection);
|
||||
if (cursorCtx) {
|
||||
const text = cursorCtx.text;
|
||||
let triggerIndex = -1;
|
||||
for (let i = cursorCtx.cursor - 1; i >= 0; i--) {
|
||||
if (text[i] === "@") {
|
||||
triggerIndex = i;
|
||||
break;
|
||||
}
|
||||
if (text[i] === " " || text[i] === "\n") break;
|
||||
}
|
||||
if (triggerIndex >= 0 && triggerIndex < cursorCtx.cursor) {
|
||||
const path = [cursorCtx.blockIndex, cursorCtx.childIndex];
|
||||
editor.tf.delete({
|
||||
at: {
|
||||
anchor: { path, offset: triggerIndex },
|
||||
focus: { path, offset: cursorCtx.cursor },
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
if (text[i] === " " || text[i] === "\n") break;
|
||||
}
|
||||
}
|
||||
|
||||
const before = text.slice(0, removeStart);
|
||||
const after = text.slice(cursorCtx.cursor);
|
||||
const replacement: ComposerNode[] = [];
|
||||
if (before.length > 0) replacement.push({ text: before });
|
||||
replacement.push(mentionNode);
|
||||
replacement.push({ text: ` ${after}` });
|
||||
|
||||
const children = [...block.children];
|
||||
children.splice(cursorCtx.childIndex, 1, ...replacement);
|
||||
const next = [...current];
|
||||
next[cursorCtx.blockIndex] = { ...block, children };
|
||||
setValue(next as ComposerValue);
|
||||
requestAnimationFrame(focusAtEnd);
|
||||
editor.tf.insertNodes([mentionNode, { text: " " }] as unknown as TElement[], {
|
||||
select: true,
|
||||
});
|
||||
});
|
||||
editor.tf.focus();
|
||||
},
|
||||
[editor.selection, focusAtEnd, getCurrentValue, setValue]
|
||||
[editor, getCurrentValue]
|
||||
);
|
||||
|
||||
// Backwards-compatible shim — pre-folder callers pass a doc-only
|
||||
// payload; we route them through ``insertMentionChip`` with
|
||||
// ``kind: "doc"``.
|
||||
// Doc-only shim that routes through ``insertMentionChip``.
|
||||
const insertDocumentChip = useCallback(
|
||||
(
|
||||
doc: Pick<Document, "id" | "title" | "document_type">,
|
||||
|
|
@ -440,26 +457,43 @@ export const InlineMentionEditor = forwardRef<InlineMentionEditorRef, InlineMent
|
|||
[insertMentionChip]
|
||||
);
|
||||
|
||||
// Remove chip(s) matching (id, document_type). Iterates in
|
||||
// descending path order so removing one entry can't invalidate
|
||||
// later paths. Chips are deduped today, so this typically runs
|
||||
// at most once.
|
||||
const removeDocumentChip = useCallback(
|
||||
(docId: number, docType?: string) => {
|
||||
const current = getCurrentValue();
|
||||
let changed = false;
|
||||
const next = current.map((block) => {
|
||||
const children = block.children.filter((node) => {
|
||||
if (!isMentionNode(node)) return true;
|
||||
const match =
|
||||
node.id === docId && (node.document_type ?? "UNKNOWN") === (docType ?? "UNKNOWN");
|
||||
if (match) changed = true;
|
||||
return !match;
|
||||
});
|
||||
return { ...block, children: children.length ? children : [{ text: "" }] };
|
||||
const match = (n: unknown) => {
|
||||
if (!n || typeof n !== "object" || !("type" in n)) return false;
|
||||
const node = n as MentionElementNode;
|
||||
if (node.type !== MENTION_TYPE) return false;
|
||||
if (node.id !== docId) return false;
|
||||
return (node.document_type ?? "UNKNOWN") === (docType ?? "UNKNOWN");
|
||||
};
|
||||
|
||||
const entries = Array.from(editor.api.nodes({ at: [], match })) as NodeEntry[];
|
||||
if (entries.length === 0) return;
|
||||
editor.tf.withoutNormalizing(() => {
|
||||
for (const [, path] of entries.reverse()) {
|
||||
editor.tf.removeNodes({ at: path });
|
||||
}
|
||||
});
|
||||
if (!changed) return;
|
||||
setValue(next as ComposerValue);
|
||||
},
|
||||
[getCurrentValue, setValue]
|
||||
[editor]
|
||||
);
|
||||
|
||||
// Single removal call site for Backspace and the X button so the
|
||||
// two can never diverge (e.g. one forgetting to notify the parent).
|
||||
const removeChip = useCallback(
|
||||
(docId: number, docType: string | undefined) => {
|
||||
removeDocumentChip(docId, docType);
|
||||
onDocumentRemove?.(docId, docType);
|
||||
},
|
||||
[onDocumentRemove, removeDocumentChip]
|
||||
);
|
||||
|
||||
// Update chip status in place via ``tf.setNodes`` so the user's
|
||||
// selection survives backend status events arriving mid-typing.
|
||||
const setDocumentChipStatus = useCallback(
|
||||
(
|
||||
docId: number,
|
||||
|
|
@ -467,31 +501,31 @@ export const InlineMentionEditor = forwardRef<InlineMentionEditorRef, InlineMent
|
|||
statusLabel: string | null,
|
||||
statusKind: MentionStatusKind = "pending"
|
||||
) => {
|
||||
const current = getCurrentValue();
|
||||
let changed = false;
|
||||
const next = current.map((block) => ({
|
||||
...block,
|
||||
children: block.children.map((node) => {
|
||||
if (!isMentionNode(node)) return node;
|
||||
const sameType = (node.document_type ?? "UNKNOWN") === (docType ?? "UNKNOWN");
|
||||
if (node.id !== docId || !sameType) return node;
|
||||
changed = true;
|
||||
return {
|
||||
...node,
|
||||
statusLabel,
|
||||
statusKind: statusLabel ? statusKind : undefined,
|
||||
};
|
||||
}),
|
||||
}));
|
||||
if (!changed) return;
|
||||
setValue(next as ComposerValue);
|
||||
const match = (n: unknown) => {
|
||||
if (!n || typeof n !== "object" || !("type" in n)) return false;
|
||||
const node = n as MentionElementNode;
|
||||
if (node.type !== MENTION_TYPE) return false;
|
||||
if (node.id !== docId) return false;
|
||||
return (node.document_type ?? "UNKNOWN") === (docType ?? "UNKNOWN");
|
||||
};
|
||||
|
||||
editor.tf.setNodes(
|
||||
{
|
||||
statusLabel,
|
||||
statusKind: statusLabel ? statusKind : undefined,
|
||||
} as Partial<TElement>,
|
||||
{ at: [], match }
|
||||
);
|
||||
},
|
||||
[getCurrentValue, setValue]
|
||||
[editor]
|
||||
);
|
||||
|
||||
const clear = useCallback(() => {
|
||||
setValue(EMPTY_VALUE);
|
||||
}, [setValue]);
|
||||
// ``tf.setValue`` wipes the selection — refocus so the caret
|
||||
// returns after Enter-to-submit.
|
||||
requestAnimationFrame(focusAtEnd);
|
||||
}, [focusAtEnd, setValue]);
|
||||
|
||||
const setText = useCallback(
|
||||
(text: string) => {
|
||||
|
|
@ -510,7 +544,18 @@ export const InlineMentionEditor = forwardRef<InlineMentionEditorRef, InlineMent
|
|||
useImperativeHandle(
|
||||
ref,
|
||||
() => ({
|
||||
focus: () => editableRef.current?.focus(),
|
||||
// Preserve existing selection if any; otherwise seed one
|
||||
// at end-of-doc so the contentEditable shows a caret.
|
||||
focus: () => {
|
||||
try {
|
||||
if (!editor.selection) {
|
||||
editor.tf.select(editor.api.end([]));
|
||||
}
|
||||
editor.tf.focus();
|
||||
} catch {
|
||||
editableRef.current?.focus();
|
||||
}
|
||||
},
|
||||
clear,
|
||||
setText,
|
||||
getText,
|
||||
|
|
@ -522,6 +567,7 @@ export const InlineMentionEditor = forwardRef<InlineMentionEditorRef, InlineMent
|
|||
}),
|
||||
[
|
||||
clear,
|
||||
editor,
|
||||
getMentionedDocs,
|
||||
getText,
|
||||
insertMentionChip,
|
||||
|
|
@ -564,10 +610,9 @@ export const InlineMentionEditor = forwardRef<InlineMentionEditorRef, InlineMent
|
|||
if (!isMentionNode(prev)) return;
|
||||
|
||||
e.preventDefault();
|
||||
removeDocumentChip(prev.id, prev.document_type);
|
||||
onDocumentRemove?.(prev.id, prev.document_type);
|
||||
removeChip(prev.id, prev.document_type);
|
||||
},
|
||||
[editor.selection, getCurrentValue, onDocumentRemove, onKeyDown, onSubmit, removeDocumentChip]
|
||||
[editor.selection, getCurrentValue, onKeyDown, onSubmit, removeChip]
|
||||
);
|
||||
|
||||
const editableProps = useMemo(
|
||||
|
|
@ -584,26 +629,33 @@ export const InlineMentionEditor = forwardRef<InlineMentionEditorRef, InlineMent
|
|||
[editor, handleKeyDown, placeholder]
|
||||
);
|
||||
|
||||
const mentionEditorContextValue = useMemo<MentionEditorContextValue>(
|
||||
() => ({ removeChip }),
|
||||
[removeChip]
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="relative w-full">
|
||||
<Plate
|
||||
editor={editor}
|
||||
onChange={({ value }) => {
|
||||
emitState(value as ComposerValue);
|
||||
}}
|
||||
>
|
||||
<PlateContent
|
||||
ref={editableRef}
|
||||
readOnly={disabled}
|
||||
{...editableProps}
|
||||
className={cn(
|
||||
"min-h-[24px] max-h-32 overflow-y-auto outline-none whitespace-pre-wrap wrap-break-word",
|
||||
COMPOSER_TEXT_METRICS_CLASSNAME,
|
||||
disabled && "opacity-50 cursor-not-allowed",
|
||||
className
|
||||
)}
|
||||
/>
|
||||
</Plate>
|
||||
<MentionEditorContext.Provider value={mentionEditorContextValue}>
|
||||
<Plate
|
||||
editor={editor}
|
||||
onChange={({ value }) => {
|
||||
emitState(value as ComposerValue);
|
||||
}}
|
||||
>
|
||||
<PlateContent
|
||||
ref={editableRef}
|
||||
readOnly={disabled}
|
||||
{...editableProps}
|
||||
className={cn(
|
||||
"min-h-[24px] max-h-32 overflow-y-auto outline-none whitespace-pre-wrap wrap-break-word",
|
||||
COMPOSER_TEXT_METRICS_CLASSNAME,
|
||||
disabled && "opacity-50 cursor-not-allowed",
|
||||
className
|
||||
)}
|
||||
/>
|
||||
</Plate>
|
||||
</MentionEditorContext.Provider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -23,6 +23,8 @@ import "katex/dist/katex.min.css";
|
|||
import { toast } from "sonner";
|
||||
import { processChildrenWithCitations } from "@/components/citations/citation-renderer";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { tryGetHostname } from "@/lib/url";
|
||||
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
|
|
@ -139,15 +141,6 @@ const MarkdownTextImpl = () => {
|
|||
|
||||
export const MarkdownText = memo(MarkdownTextImpl);
|
||||
|
||||
function extractDomain(url: string): string {
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
return parsed.hostname.replace(/^www\./, "");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// Canonical local-file virtual paths are mount-prefixed: /<mount>/<relative/path>
|
||||
const LOCAL_FILE_PATH_REGEX = /^\/[a-z0-9_-]+\/[^\s`]+(?:\/[^\s`]+)*$/;
|
||||
|
||||
|
|
@ -288,7 +281,7 @@ function FilePathLink({ path, className }: { path: string; className?: string })
|
|||
function MarkdownImage({ src, alt }: { src?: string; alt?: string }) {
|
||||
if (!src) return null;
|
||||
|
||||
const domain = extractDomain(src);
|
||||
const domain = tryGetHostname(src) ?? "";
|
||||
|
||||
return (
|
||||
<div className="my-4 w-fit max-w-lg overflow-hidden rounded-2xl border bg-muted/30 select-none">
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
"use client";
|
||||
|
||||
import type { MouseEventHandler, ReactNode } from "react";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
|
|
@ -61,30 +60,27 @@ export function MentionChip({
|
|||
const isInteractive = Boolean(onClick) && !disabled;
|
||||
|
||||
const chip = (
|
||||
<Button
|
||||
variant="ghost"
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
disabled={disabled}
|
||||
aria-label={ariaLabel ?? label}
|
||||
className={cn(
|
||||
"h-auto max-w-[220px] justify-start gap-1.5 rounded-md border bg-background px-2 py-0.5 align-middle text-xs leading-5 text-foreground shadow-none transition-colors focus-visible:ring-1 focus-visible:ring-ring",
|
||||
isInteractive
|
||||
? "cursor-pointer hover:bg-accent hover:text-accent-foreground"
|
||||
: "cursor-default",
|
||||
"inline-flex h-5 items-center gap-1 rounded bg-primary/10 px-1 align-middle text-xs font-bold text-primary/60 leading-none focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring",
|
||||
isInteractive ? "cursor-pointer" : "cursor-default",
|
||||
disabled && "opacity-60",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<span className="inline-flex shrink-0 text-muted-foreground">{icon}</span>
|
||||
<span className="truncate">{label}</span>
|
||||
</Button>
|
||||
<span className="max-w-[120px] truncate leading-none">{label}</span>
|
||||
</button>
|
||||
);
|
||||
|
||||
if (!tooltip) return chip;
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<Tooltip delayDuration={600}>
|
||||
<TooltipTrigger asChild>{chip}</TooltipTrigger>
|
||||
<TooltipContent side="top" className="max-w-xs break-all">
|
||||
{tooltip}
|
||||
|
|
|
|||
|
|
@ -61,6 +61,7 @@ import { useDocumentUploadDialog } from "@/components/assistant-ui/document-uplo
|
|||
import {
|
||||
InlineMentionEditor,
|
||||
type InlineMentionEditorRef,
|
||||
type MentionedDocument,
|
||||
} from "@/components/assistant-ui/inline-mention-editor";
|
||||
import { TooltipIconButton } from "@/components/assistant-ui/tooltip-icon-button";
|
||||
import { UserMessage } from "@/components/assistant-ui/user-message";
|
||||
|
|
@ -180,36 +181,24 @@ const PremiumQuotaPinnedAlert: FC = () => {
|
|||
const getTimeBasedGreeting = (user?: { display_name?: string | null; email?: string }): string => {
|
||||
const hour = new Date().getHours();
|
||||
|
||||
// Extract first name: prefer display_name, fall back to email extraction
|
||||
let firstName: string | null = null;
|
||||
|
||||
if (user?.display_name?.trim()) {
|
||||
// Use display_name if available and not empty
|
||||
// Extract first name from display_name (take first word)
|
||||
const nameParts = user.display_name.trim().split(/\s+/);
|
||||
firstName = nameParts[0].charAt(0).toUpperCase() + nameParts[0].slice(1).toLowerCase();
|
||||
} else if (user?.email) {
|
||||
// Fall back to email extraction if display_name is not available
|
||||
firstName =
|
||||
user.email.split("@")[0].split(".")[0].charAt(0).toUpperCase() +
|
||||
user.email.split("@")[0].split(".")[0].slice(1);
|
||||
}
|
||||
|
||||
// Array of greeting variations for each time period
|
||||
const morningGreetings = ["Good morning", "Fresh start today", "Morning", "Hey there"];
|
||||
|
||||
const afternoonGreetings = ["Good afternoon", "Afternoon", "Hey there", "Hi there"];
|
||||
|
||||
const eveningGreetings = ["Good evening", "Evening", "Hey there", "Hi there"];
|
||||
|
||||
const nightGreetings = ["Good night", "Evening", "Hey there", "Winding down"];
|
||||
|
||||
const lateNightGreetings = ["Still up", "Night owl mode", "Up past bedtime", "Hi there"];
|
||||
|
||||
// Select a random greeting based on time
|
||||
let greeting: string;
|
||||
if (hour < 5) {
|
||||
// Late night: midnight to 5 AM
|
||||
greeting = lateNightGreetings[Math.floor(Math.random() * lateNightGreetings.length)];
|
||||
} else if (hour < 12) {
|
||||
greeting = morningGreetings[Math.floor(Math.random() * morningGreetings.length)];
|
||||
|
|
@ -218,33 +207,23 @@ const getTimeBasedGreeting = (user?: { display_name?: string | null; email?: str
|
|||
} else if (hour < 22) {
|
||||
greeting = eveningGreetings[Math.floor(Math.random() * eveningGreetings.length)];
|
||||
} else {
|
||||
// Night: 10 PM to midnight
|
||||
greeting = nightGreetings[Math.floor(Math.random() * nightGreetings.length)];
|
||||
}
|
||||
|
||||
// Add personalization with first name if available
|
||||
if (firstName) {
|
||||
return `${greeting}, ${firstName}!`;
|
||||
}
|
||||
|
||||
return `${greeting}!`;
|
||||
return firstName ? `${greeting}, ${firstName}!` : `${greeting}!`;
|
||||
};
|
||||
|
||||
const ThreadWelcome: FC = () => {
|
||||
const { data: user } = useAtomValue(currentUserAtom);
|
||||
|
||||
// Memoize greeting so it doesn't change on re-renders (only on user change)
|
||||
const greeting = useMemo(() => getTimeBasedGreeting(user), [user]);
|
||||
|
||||
return (
|
||||
<div className="aui-thread-welcome-root mx-auto flex w-full max-w-(--thread-max-width) grow flex-col items-center px-4 relative">
|
||||
{/* Greeting positioned above the composer */}
|
||||
<div className="aui-thread-welcome-message absolute bottom-[calc(50%+5rem)] left-0 right-0 flex flex-col items-center text-center">
|
||||
<h1 className="aui-thread-welcome-message-inner text-3xl md:text-[2.625rem] select-none">
|
||||
{greeting}
|
||||
</h1>
|
||||
</div>
|
||||
{/* Composer - top edge fixed, expands downward only */}
|
||||
<div className="w-full flex items-start justify-center absolute top-[calc(50%-3.5rem)] left-0 right-0">
|
||||
<Composer />
|
||||
</div>
|
||||
|
|
@ -422,7 +401,6 @@ const ClipboardChip: FC<{ text: string; onDismiss: () => void }> = ({ text, onDi
|
|||
};
|
||||
|
||||
const Composer: FC = () => {
|
||||
// Document mention state (atoms persist across component remounts)
|
||||
const [mentionedDocuments, setMentionedDocuments] = useAtom(mentionedDocumentsAtom);
|
||||
const [showDocumentPopover, setShowDocumentPopover] = useState(false);
|
||||
const [showPromptPicker, setShowPromptPicker] = useState(false);
|
||||
|
|
@ -434,7 +412,9 @@ const Composer: FC = () => {
|
|||
const promptPickerRef = useRef<PromptPickerRef>(null);
|
||||
const { search_space_id, chat_id } = useParams();
|
||||
const aui = useAui();
|
||||
const hasAutoFocusedRef = useRef(false);
|
||||
// Desktop-only auto-focus; on mobile, programmatic focus would
|
||||
// summon the soft keyboard on every picker close / thread switch.
|
||||
const isDesktop = useMediaQuery("(min-width: 640px)");
|
||||
|
||||
const electronAPI = useElectronAPI();
|
||||
const [clipboardInitialText, setClipboardInitialText] = useState<string | undefined>();
|
||||
|
|
@ -455,7 +435,6 @@ const Composer: FC = () => {
|
|||
|
||||
const currentPlaceholder = COMPOSER_PLACEHOLDER;
|
||||
|
||||
// Live collaboration state
|
||||
const { data: currentUser } = useAtomValue(currentUserAtom);
|
||||
const { data: members } = useAtomValue(membersAtom);
|
||||
const threadId = useMemo(() => {
|
||||
|
|
@ -469,13 +448,11 @@ const Composer: FC = () => {
|
|||
const respondingToUserId = sessionState?.respondingToUserId ?? null;
|
||||
const isBlockedByOtherUser = isAiResponding && respondingToUserId !== currentUser?.id;
|
||||
|
||||
// Sync comments for the entire thread via Zero (one subscription per thread)
|
||||
// One Zero subscription per thread for comment sync.
|
||||
useCommentsSync(threadId);
|
||||
|
||||
// Batch-prefetch comments for all assistant messages so individual useComments
|
||||
// hooks never fire their own network requests (eliminates N+1 API calls).
|
||||
// Return a primitive string from the selector so useSyncExternalStore can
|
||||
// compare snapshots by value and avoid infinite re-render loops.
|
||||
// Batch-prefetch assistant message comments to avoid N+1 fetches.
|
||||
// Returns a primitive string so useSyncExternalStore can compare by value.
|
||||
const assistantIdsKey = useAuiState(({ thread }) =>
|
||||
thread.messages
|
||||
.filter((m) => m.role === "assistant" && m.id?.startsWith("msg-"))
|
||||
|
|
@ -488,18 +465,17 @@ const Composer: FC = () => {
|
|||
);
|
||||
useBatchCommentsPreload(assistantDbMessageIds);
|
||||
|
||||
// Auto-focus editor on new chat page after mount
|
||||
// Always-focused composer: refocus whenever no picker has taken
|
||||
// over input. ``threadId`` is in the deps so the effect re-fires
|
||||
// on thread switch (Composer instance is reused).
|
||||
useEffect(() => {
|
||||
if (isThreadEmpty && !hasAutoFocusedRef.current && editorRef.current) {
|
||||
const timeoutId = setTimeout(() => {
|
||||
editorRef.current?.focus();
|
||||
hasAutoFocusedRef.current = true;
|
||||
}, 100);
|
||||
return () => clearTimeout(timeoutId);
|
||||
}
|
||||
}, [isThreadEmpty]);
|
||||
if (!isDesktop) return;
|
||||
if (showDocumentPopover || showPromptPicker) return;
|
||||
void threadId;
|
||||
editorRef.current?.focus();
|
||||
}, [isDesktop, showDocumentPopover, showPromptPicker, threadId]);
|
||||
|
||||
// Close document picker when a slide-out panel (inbox, shared/private chats) opens
|
||||
// Close document picker when a slide-out panel (inbox, etc.) opens.
|
||||
useEffect(() => {
|
||||
const handler = () => {
|
||||
setShowDocumentPopover(false);
|
||||
|
|
@ -509,21 +485,41 @@ const Composer: FC = () => {
|
|||
return () => window.removeEventListener(SLIDEOUT_PANEL_OPENED_EVENT, handler);
|
||||
}, []);
|
||||
|
||||
// Sync editor text with assistant-ui composer runtime
|
||||
// Sync editor text into assistant-ui's composer and mirror the chip
|
||||
// atom from the editor's reported ``docs``. The editor is the
|
||||
// single source of truth, so this catches every Plate deletion path
|
||||
// (Backspace, X button, Cmd+Backspace, range-delete, cut,
|
||||
// paste-over) without per-keybinding plumbing. The ``prev``
|
||||
// short-circuit keeps pure-text keystrokes from churning the atom.
|
||||
const handleEditorChange = useCallback(
|
||||
(text: string) => {
|
||||
(text: string, docs: MentionedDocument[]) => {
|
||||
aui.composer().setText(text);
|
||||
setMentionedDocuments((prev) => {
|
||||
if (prev.length === docs.length) {
|
||||
const editorKeys = new Set(docs.map((d) => getMentionDocKey(d)));
|
||||
if (prev.every((d) => editorKeys.has(getMentionDocKey(d)))) {
|
||||
return prev;
|
||||
}
|
||||
}
|
||||
return docs.map<MentionedDocumentInfo>((d) => ({
|
||||
id: d.id,
|
||||
title: d.title,
|
||||
// Atom requires a string; ``"UNKNOWN"`` matches the
|
||||
// sentinel ``getMentionDocKey`` and the editor's
|
||||
// match predicates use.
|
||||
document_type: d.document_type ?? "UNKNOWN",
|
||||
kind: d.kind,
|
||||
}));
|
||||
});
|
||||
},
|
||||
[aui]
|
||||
[aui, setMentionedDocuments]
|
||||
);
|
||||
|
||||
// Open document picker when @ mention is triggered
|
||||
const handleMentionTrigger = useCallback((query: string) => {
|
||||
setShowDocumentPopover(true);
|
||||
setMentionQuery(query);
|
||||
}, []);
|
||||
|
||||
// Close document picker and reset query
|
||||
const handleMentionClose = useCallback(() => {
|
||||
if (showDocumentPopover) {
|
||||
setShowDocumentPopover(false);
|
||||
|
|
@ -531,13 +527,11 @@ const Composer: FC = () => {
|
|||
}
|
||||
}, [showDocumentPopover]);
|
||||
|
||||
// Open action picker when / is triggered
|
||||
const handleActionTrigger = useCallback((query: string) => {
|
||||
setShowPromptPicker(true);
|
||||
setActionQuery(query);
|
||||
}, []);
|
||||
|
||||
// Close action picker and reset query
|
||||
const handleActionClose = useCallback(() => {
|
||||
if (showPromptPicker) {
|
||||
setShowPromptPicker(false);
|
||||
|
|
@ -581,7 +575,7 @@ const Composer: FC = () => {
|
|||
[clipboardInitialText, electronAPI, aui]
|
||||
);
|
||||
|
||||
// Keyboard navigation for document/action picker (arrow keys, Enter, Escape)
|
||||
// Arrow / Enter / Escape navigation for the active picker.
|
||||
const handleKeyDown = useCallback(
|
||||
(e: React.KeyboardEvent) => {
|
||||
if (showPromptPicker) {
|
||||
|
|
@ -662,7 +656,7 @@ const Composer: FC = () => {
|
|||
(docId: number, docType?: string) => {
|
||||
setMentionedDocuments((prev) => {
|
||||
if (!docType) {
|
||||
// Defensive fallback: keep UI in sync even when chip type is unavailable.
|
||||
// Fallback when chip type is unavailable.
|
||||
return prev.filter((doc) => doc.id !== docId);
|
||||
}
|
||||
const removedKey = getMentionDocKey({ id: docId, document_type: docType });
|
||||
|
|
@ -672,27 +666,22 @@ const Composer: FC = () => {
|
|||
[setMentionedDocuments]
|
||||
);
|
||||
|
||||
const handleDocumentsMention = useCallback(
|
||||
(mentions: MentionedDocumentInfo[]) => {
|
||||
const editorMentionedDocs = editorRef.current?.getMentionedDocuments() ?? [];
|
||||
const editorDocKeys = new Set(editorMentionedDocs.map((doc) => getMentionDocKey(doc)));
|
||||
const handleDocumentsMention = useCallback((mentions: MentionedDocumentInfo[]) => {
|
||||
const editorMentionedDocs = editorRef.current?.getMentionedDocuments() ?? [];
|
||||
const editorDocKeys = new Set(editorMentionedDocs.map((doc) => getMentionDocKey(doc)));
|
||||
|
||||
for (const mention of mentions) {
|
||||
const key = getMentionDocKey(mention);
|
||||
if (editorDocKeys.has(key)) continue;
|
||||
editorRef.current?.insertMentionChip(mention);
|
||||
}
|
||||
for (const mention of mentions) {
|
||||
const key = getMentionDocKey(mention);
|
||||
if (editorDocKeys.has(key)) continue;
|
||||
editorRef.current?.insertMentionChip(mention);
|
||||
// Track within the loop so a duplicate-in-batch can't double-insert.
|
||||
editorDocKeys.add(key);
|
||||
}
|
||||
|
||||
setMentionedDocuments((prev) => {
|
||||
const existingKeySet = new Set(prev.map((d) => getMentionDocKey(d)));
|
||||
const uniqueNew = mentions.filter((m) => !existingKeySet.has(getMentionDocKey(m)));
|
||||
return [...prev, ...uniqueNew];
|
||||
});
|
||||
|
||||
setMentionQuery("");
|
||||
},
|
||||
[setMentionedDocuments]
|
||||
);
|
||||
// Atom is reconciled by ``handleEditorChange`` via the editor's
|
||||
// onChange — no second write path here.
|
||||
setMentionQuery("");
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
const editor = editorRef.current;
|
||||
|
|
@ -1292,12 +1281,7 @@ const ComposerAction: FC<ComposerActionProps> = ({ isBlockedByOtherUser = false
|
|||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Friendly tool name for display in the chat UI. Delegates to the
|
||||
* shared map in ``contracts/enums/toolIcons`` so unix-style identifiers
|
||||
* (``rm``, ``ls``, ``grep`` …) and snake_cased function names render as
|
||||
* plain English (e.g. "Delete file", "List files", "Search in files").
|
||||
*/
|
||||
/** Friendly tool name (delegates to ``getToolDisplayName``). */
|
||||
function formatToolName(name: string): string {
|
||||
return getToolDisplayName(name);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue