Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Reveal menu: give focus back on close; Show in Finder on inline links to delivered files

AdityaUmale167ba1f46b6f
diff --git a/src/components/ChatMarkdown.tsx b/src/components/ChatMarkdown.tsx
index aa7f5610c7..a9a861cf85 100644
--- a/src/components/ChatMarkdown.tsx
+++ b/src/components/ChatMarkdown.tsx
@@ -28,6 +28,7 @@ import { MarkdownTable } from "./MarkdownTable";
import { CodeBlock, CodePlate, codeHash } from "./CodeBlock";
export { CodeBlock, HIGHLIGHT_CACHE_MAX, HIGHLIGHT_CACHE_MAX_CHARS, HIGHLIGHT_MAX_CHARS, type CodeBlockProps } from "./CodeBlock";
import { FilePreviewButton } from "./FilePreviewButton";
+import { useRevealOriginalMenu } from "./RevealOriginalMenu";
const mermaidCache = new Map<string, string>();
const MERMAID_CACHE_MAX = 50;
@@ -319,8 +320,10 @@ export function MermaidDiagram({ code }: MermaidDiagramProps) {
// Security: no href at all, since an <a href="file://…"> reaches setWindowOpenHandler on a middle or modifier click,
// which calls shell.openExternal without main's containment check.
-function LocalFileLink({ filePath, name, children, message }: { filePath: string; name?: string; children?: ReactNode; message?: MessageAttachmentContext }) {
+// source: the original a delivered copy came from, offered on right-click (Show in Finder) like in the gallery.
+function LocalFileLink({ filePath, name, source, children, message }: { filePath: string; name?: string; source?: string; children?: ReactNode; message?: MessageAttachmentContext }) {
const save = useLocalFileSave(filePath, name, message);
+ const revealMenu = useRevealOriginalMenu();
if (!message) {
return <span title="Unavailable legacy file reference" className="break-words text-ink-secondary">{children}</span>;
}
@@ -333,7 +336,8 @@ function LocalFileLink({ filePath, name, children, message }: { filePath: string
: null;
return (
- <span dir="ltr" className="inline-flex flex-wrap items-center gap-x-1.5 [unicode-bidi:isolate]">
+ <span dir="ltr" className="inline-flex flex-wrap items-center gap-x-1.5 [unicode-bidi:isolate]" {...revealMenu.targetProps(source)}>
+ {revealMenu.menu}
<FilePreviewButton path={filePath} name={name ?? fileName(filePath)} message={message} />
<button
type="button"
@@ -566,6 +570,7 @@ interface MessageScope {
threads: ThreadRefsValue["threads"];
currentBotId?: string;
delivered?: DeliveredFiles;
+ originals?: DeliveredFiles;
}
export type DeliveredFiles = Readonly<Record<string, string>>;
@@ -610,7 +615,7 @@ function MarkdownImage(props: ComponentProps<"img"> & ExtraProps) {
function MarkdownLink({ href, children, ...rest }: { href?: string; children?: ReactNode }) {
// SAFETY: react-markdown hands hast data-* attributes through as string props
const props = rest as Record<string, unknown>;
- const { threads, currentBotId, message, delivered } = useContext(MessageScopeContext);
+ const { threads, currentBotId, message, delivered, originals } = useContext(MessageScopeContext);
const linkMenu = useThreadLinkMenu(href), openPage = usePageOpener();
if (!href) return <span className="break-words">{children}</span>;
if (isUseMyComputerUrl(href)) return <UseMyComputerLink>{children}</UseMyComputerLink>;
@@ -621,7 +626,8 @@ function MarkdownLink({ href, children, ...rest }: { href?: string; children?: R
const localPath = localFilePath(href);
if (localPath) {
const copy = delivered && Object.hasOwn(delivered, fileName(localPath)) ? delivered[fileName(localPath)] : undefined;
- return <LocalFileLink filePath={copy ?? localPath} name={copy ? fileName(localPath) : undefined} message={message}>{children}</LocalFileLink>;
+ const source = copy && originals && Object.hasOwn(originals, copy) ? originals[copy] : undefined;
+ return <LocalFileLink filePath={copy ?? localPath} name={copy ? fileName(localPath) : undefined} source={source} message={message}>{children}</LocalFileLink>;
}
if (!/^https?:\/\//i.test(href)) {
return (
@@ -754,10 +760,11 @@ export function clearChatMarkdownCache(): void {
markdownCache.clear();
}
-function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS, everyone = false, mentionPerson, delivered }: {
+function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS, everyone = false, mentionPerson, delivered, originals }: {
text: string; message?: MessageAttachmentContext;
mentionPeers?: readonly MentionPeer[]; everyone?: boolean; mentionPerson?: MentionPerson;
- delivered?: DeliveredFiles;
+ /** Delivered copies by file name, and the originals those copies came from (copy path -> original). */
+ delivered?: DeliveredFiles; originals?: DeliveredFiles;
}) {
// use() may be called conditionally: only a message that can hold a thread link subscribes to the thread list.
const { threads, currentBotId } = MAY_LINK_THREAD.test(text) ? use(ThreadRefsContext) : NO_THREAD_REFS;
@@ -790,7 +797,7 @@ function ChatMarkdownComponent({ text, message, mentionPeers = NO_MENTION_PEERS,
return Markdown({ children: source, remarkPlugins, rehypePlugins: rehypePluginsFor(mathPlugin), urlTransform: chatUrlTransform, components: MARKDOWN_COMPONENTS });
});
return (
- <MessageScopeContext.Provider value={{ message, imageOffsets, threads, currentBotId, delivered }}>
+ <MessageScopeContext.Provider value={{ message, imageOffsets, threads, currentBotId, delivered, originals }}>
<div className="chat-md min-w-0 [&>*+*]:mt-2">{markdown}</div>
</MessageScopeContext.Provider>
);
@@ -811,7 +818,7 @@ export const ChatMarkdown = memo(ChatMarkdownComponent, (previous, next) => (
&& previous.everyone === next.everyone && sameMentionPerson(previous.mentionPerson, next.mentionPerson)
&& previous.message?.threadId === next.message?.threadId
&& previous.message?.messageId === next.message?.messageId
- && sameDelivered(previous.delivered, next.delivered)
+ && sameDelivered(previous.delivered, next.delivered) && sameDelivered(previous.originals, next.originals)
));
function sameDelivered(previous: DeliveredFiles | undefined, next: DeliveredFiles | undefined): boolean {
diff --git a/src/components/ChatView.tsx b/src/components/ChatView.tsx
index 1a2de51710..d98efcd3c8 100644
--- a/src/components/ChatView.tsx
+++ b/src/components/ChatView.tsx
@@ -552,14 +552,14 @@ const Bubble = memo(function Bubble({
{!group && <AttachmentGallery images={generatedPaths} files={linkedFiles} originals={attached.originals} message={{ threadId, messageId: message.id }} className={text ? undefined : "mb-0"} eager={eagerAttachments} />}
{split ? (
<ConversationalReply simple={simple} join={join} segments={reply.segments} firstNew={reply.firstNew} citation={{ messageId: message.id, botId, threadId }}
- renderSegment={(segment) => <ChatMarkdown text={segment} mentionPeers={mentionPeers} mentionPerson={mentionPerson} message={{ threadId, messageId: message.id }} delivered={group?.delivered} />} />
+ renderSegment={(segment) => <ChatMarkdown text={segment} mentionPeers={mentionPeers} mentionPerson={mentionPerson} message={{ threadId, messageId: message.id }} delivered={group?.delivered} originals={group?.originals} />} />
) : tabled && blocks ? (
<ReplyBlocks blocks={blocks} join={join} tray={botActions} citation={{ messageId: message.id, ownerType: "bot", ownerId: botId, threadId }}
- render={(block) => <ChatMarkdown text={block} mentionPeers={mentionPeers} mentionPerson={mentionPerson} message={{ threadId, messageId: message.id }} delivered={group?.delivered} />} />
+ render={(block) => <ChatMarkdown text={block} mentionPeers={mentionPeers} mentionPerson={mentionPerson} message={{ threadId, messageId: message.id }} delivered={group?.delivered} originals={group?.originals} />} />
) : viewRaw && text ? (
<div data-citation-source={message.id} data-citation-owner-type="bot" data-citation-owner={botId} data-citation-thread={threadId}><RawMarkdownView text={text} /></div>
) : text ? (
- <div data-citation-source={message.id} data-citation-owner-type="bot" data-citation-owner={botId} data-citation-thread={threadId}><ChatMarkdown text={text} mentionPeers={mentionPeers} mentionPerson={mentionPerson} message={{ threadId, messageId: message.id }} delivered={group?.delivered} /></div>
+ <div data-citation-source={message.id} data-citation-owner-type="bot" data-citation-owner={botId} data-citation-thread={threadId}><ChatMarkdown text={text} mentionPeers={mentionPeers} mentionPerson={mentionPerson} message={{ threadId, messageId: message.id }} delivered={group?.delivered} originals={group?.originals} /></div>
) : null}
{group && <AttachmentGallery images={group.images} files={group.files} originals={group.originals} message={{ threadId, messageId: message.id }} eager={eagerAttachments} beneath />}
</MessageBoundary>
diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsx
index 8acda164bb..6d436f31e0 100644
--- a/src/components/GroupView.tsx
+++ b/src/components/GroupView.tsx
@@ -289,9 +289,9 @@ function RoomTextMessage({
<div data-citation-source={m.id} data-citation-owner-type="group" data-citation-owner={group.id} data-citation-thread={group.threadId}><RawMarkdownView text={botText} /></div>
) : tabled && blocks ? (
<ReplyBlocks blocks={blocks} tray={botActions} citation={{ messageId: m.id, ownerType: "group", ownerId: group.id, threadId: group.threadId }}
- render={(block) => <ChatMarkdown text={block} mentionPeers={peers} everyone={!group.dm} mentionPerson={{ profileName: state.config?.profile?.name }} message={{ threadId: group.threadId, messageId: m.id }} delivered={replyGroup?.delivered} />} />
+ render={(block) => <ChatMarkdown text={block} mentionPeers={peers} everyone={!group.dm} mentionPerson={{ profileName: state.config?.profile?.name }} message={{ threadId: group.threadId, messageId: m.id }} delivered={replyGroup?.delivered} originals={replyGroup?.originals} />} />
) : botText ? (
- <div data-citation-source={m.id} data-citation-owner-type="group" data-citation-owner={group.id} data-citation-thread={group.threadId}><ChatMarkdown text={botText} mentionPeers={peers} everyone={!group.dm} mentionPerson={{ profileName: state.config?.profile?.name }} message={{ threadId: group.threadId, messageId: m.id }} delivered={replyGroup?.delivered} /></div>
+ <div data-citation-source={m.id} data-citation-owner-type="group" data-citation-owner={group.id} data-citation-thread={group.threadId}><ChatMarkdown text={botText} mentionPeers={peers} everyone={!group.dm} mentionPerson={{ profileName: state.config?.profile?.name }} message={{ threadId: group.threadId, messageId: m.id }} delivered={replyGroup?.delivered} originals={replyGroup?.originals} /></div>
) : null}
{replyGroup && <AttachmentGallery images={replyGroup.images} files={replyGroup.files} originals={replyGroup.originals} message={{ threadId: group.threadId, messageId: m.id }} eager={eager} beneath />}
</MessageBoundary>
diff --git a/src/components/RevealOriginalMenu.dom.test.ts b/src/components/RevealOriginalMenu.dom.test.ts
new file mode 100644
index 0000000000..791d6bb654
--- /dev/null
+++ b/src/components/RevealOriginalMenu.dom.test.ts
@@ -0,0 +1,75 @@
+// @vitest-environment happy-dom
+import { act, createElement } from "react";
+import { createRoot } from "react-dom/client";
+import { afterEach, expect, it, vi } from "vitest";
+import { useRevealOriginalMenu } from "./RevealOriginalMenu";
+import { ChatMarkdown } from "./ChatMarkdown";
+
+(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+afterEach(() => {
+ document.body.innerHTML = "";
+ delete (window as { ogb?: unknown }).ogb;
+});
+
+const ORIGINAL = "/home/me/Reports/q3.pdf";
+
+function Attachment() {
+ const reveal = useRevealOriginalMenu();
+ return createElement("div", null, createElement("button", { type: "button", id: "attachment", ...reveal.targetProps(ORIGINAL) }, "q3.pdf"), reveal.menu);
+}
+
+async function mount(element: ReturnType<typeof createElement>) {
+ const root = createRoot(document.body.appendChild(document.createElement("div")));
+ await act(async () => root.render(element));
+ return root;
+}
+
+const openMenu = (target: Element) => act(async () => {
+ target.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true, cancelable: true, clientX: 20, clientY: 20 }));
+});
+const menuButton = () => document.querySelector<HTMLButtonElement>("[role=group] button");
+
+it("gives focus back to the attachment when Escape closes the menu", async () => {
+ (window as { ogb?: unknown }).ogb = { platform: "linux", revealInFolder: vi.fn(async () => "shown") };
+ const root = await mount(createElement(Attachment));
+ const attachment = document.getElementById("attachment")!;
+ attachment.focus();
+ await openMenu(attachment);
+ expect(document.activeElement).toBe(menuButton());
+ await act(async () => { menuButton()!.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); });
+ expect(menuButton()).toBeNull();
+ expect(document.activeElement).toBe(attachment);
+ act(() => root.unmount());
+});
+
+it("gives focus back to the attachment after the original was shown", async () => {
+ const revealInFolder = vi.fn(async () => "shown");
+ (window as { ogb?: unknown }).ogb = { platform: "linux", revealInFolder };
+ const root = await mount(createElement(Attachment));
+ const attachment = document.getElementById("attachment")!;
+ attachment.focus();
+ await openMenu(attachment);
+ await act(async () => { menuButton()!.click(); });
+ expect(revealInFolder).toHaveBeenCalledWith(ORIGINAL);
+ expect(menuButton()).toBeNull();
+ expect(document.activeElement).toBe(attachment);
+ act(() => root.unmount());
+});
+
+it("offers the original on a file the reply links inline instead of showing it in the gallery", async () => {
+ const revealInFolder = vi.fn(async () => "shown");
+ (window as { ogb?: unknown }).ogb = { platform: "linux", revealInFolder };
+ const copy = "/data/bot/files/q3.pdf";
+ const root = await mount(createElement(ChatMarkdown, {
+ text: "Here it is: [q3.pdf](/home/me/Reports/q3.pdf)",
+ message: { threadId: "t1", messageId: "m1" },
+ delivered: { "q3.pdf": copy },
+ originals: { [copy]: ORIGINAL },
+ }));
+ const link = [...document.querySelectorAll("span[dir=ltr]")].at(-1)!;
+ await openMenu(link);
+ expect(menuButton()?.textContent).toBe("Show in folder");
+ await act(async () => { menuButton()!.click(); });
+ expect(revealInFolder).toHaveBeenCalledWith(ORIGINAL);
+ act(() => root.unmount());
+});
diff --git a/src/components/RevealOriginalMenu.tsx b/src/components/RevealOriginalMenu.tsx
index 312808a26e..4266a8f83a 100644
--- a/src/components/RevealOriginalMenu.tsx
+++ b/src/components/RevealOriginalMenu.tsx
@@ -39,6 +39,14 @@ export async function revealOriginal(source: string, reveal: Reveal): Promise<st
export function useRevealOriginalMenu() {
const [at, setAt] = useState<{ left: number; top: number; source: string; problem?: string } | null>(null);
const menuRef = useRef<HTMLDivElement>(null);
+ // Escape or a successful reveal removes the menu while its button has focus: give focus back to where it was.
+ const returnFocus = useRef<HTMLElement | null>(null);
+ const closeAndRestoreFocus = () => {
+ setAt(null);
+ const target = returnFocus.current;
+ returnFocus.current = null;
+ if (target?.isConnected) target.focus();
+ };
useEffect(() => {
if (!at) return;
menuRef.current?.querySelector<HTMLButtonElement>("button")?.focus();
@@ -51,6 +59,7 @@ export function useRevealOriginalMenu() {
const label = revealOriginalLabel(typeof window === "undefined" ? undefined : window.ogb?.platform);
const show = async (source: string) => {
const problem = reveal ? await revealOriginal(source, reveal) : t("attach.revealFailed");
+ if (!problem && menuRef.current?.contains(document.activeElement)) return closeAndRestoreFocus();
setAt((current) => current?.source !== source ? current : problem ? { ...current, problem } : null);
};
return {
@@ -59,13 +68,15 @@ export function useRevealOriginalMenu() {
onContextMenu: (event: MouseEvent<HTMLElement>) => {
event.preventDefault();
event.stopPropagation();
+ const active = document.activeElement;
+ returnFocus.current = active instanceof HTMLElement && active !== document.body ? active : event.currentTarget;
setAt({ left: Math.max(8, Math.min(event.clientX, window.innerWidth - 268)), top: Math.max(8, Math.min(event.clientY, window.innerHeight - 110)), source });
},
},
menu: at && createPortal(
<div ref={menuRef} role="group" aria-label={label} style={{ left: at.left, top: at.top }}
className={cn("fixed z-50 w-[260px]", MENU_SHEET)}
- onKeyDown={(event) => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); setAt(null); } }}>
+ onKeyDown={(event) => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); closeAndRestoreFocus(); } }}>
<button type="button" onClick={() => void show(at.source)} title={at.source} className={ITEM_CLASS}>
<FolderOpen size={16} />{label}
</button>