YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context
Rust agentsagiaiai-memoryaudio-recordingcomputer-visionhermeshermes-agentllmlocal-ailocal-firstmachine-learningmcpmultimodalopenclawprivacyrewindscreen-recordingspeech-to-textycombinator
feat(chat): archive the current tab with Cmd+E (#6752)
Louis Beaumont7fdb4aa6b2e2
diff --git a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx b/apps/screenpipe-app-tauri/components/chat-sidebar.tsxindex b2afd68c3..c24e1137b 100644--- a/apps/screenpipe-app-tauri/components/chat-sidebar.tsx+++ b/apps/screenpipe-app-tauri/components/chat-sidebar.tsx@@ -62,6 +62,7 @@ import {isEmptyChatShell,selectDisplayedChatId,sessionRecordFromMeta,+ fallbackOpenChatId,type SessionRecord,} from "@/lib/stores/chat-store";import {@@ -1374,24 +1375,32 @@ export function ChatSidebar({ className, onViewAll }: ChatSidebarProps) {// Archiving should tuck chats away immediately; users can reopen// the bucket manually when they want to review archived items.setArchivedCollapsed(true);- // Move the panel off a chat that just left the visible list.+ const fallbackId = fallbackOpenChatId(useChatStore.getState(), id);+ actions.closeChat(id);+ // Move the panel off a chat that just left the visible list. Prefer+ // the next open tab; mint untitled only when this was the last one.if (id === currentId) {- const fresh = crypto.randomUUID();- actions.upsert({- id: fresh,- title: "untitled",- preview: "",- status: "idle",- messageCount: 0,- createdAt: Date.now(),- updatedAt: Date.now(),- pinned: false,- unread: false,- draft: true,- messages: [],- });- actions.setCurrent(fresh);- emit("chat-load-conversation", { conversationId: fresh });+ if (fallbackId) {+ actions.setCurrent(fallbackId);+ emit("chat-load-conversation", { conversationId: fallbackId });+ } else {+ const fresh = crypto.randomUUID();+ actions.upsert({+ id: fresh,+ title: "untitled",+ preview: "",+ status: "idle",+ messageCount: 0,+ createdAt: Date.now(),+ updatedAt: Date.now(),+ pinned: false,+ unread: false,+ draft: true,+ messages: [],+ });+ actions.setCurrent(fresh);+ emit("chat-load-conversation", { conversationId: fresh });+ }}// Best-effort persistence for restart durability.try {diff --git a/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.test.tsx b/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.test.tsxindex 98fae024b..deebd2592 100644--- a/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.test.tsx+++ b/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.test.tsx@@ -281,6 +281,114 @@ describe("ChatTabStrip", () => {);});+ it("archives the active tab on Ctrl+E and keeps the sibling open", async () => {+ const actions = useChatStore.getState().actions;+ for (const [id, title] of [+ ["chat-a", "first"],+ ["chat-b", "second"],+ ] as const) {+ actions.upsert(record({ id, title }));+ actions.openChat(id);+ }+ const onActivate = vi.fn();+ const archiveConversation = vi.fn(async () => {});+ render(+ <ChatTabStrip+ activeId="chat-b"+ onActivate={onActivate}+ onNewChat={vi.fn()}+ archiveConversation={archiveConversation}+ />,+ );++ fireEvent.keyDown(window, { key: "e", code: "KeyE", ctrlKey: true });++ await waitFor(() =>+ expect(archiveConversation).toHaveBeenCalledWith("chat-b"),+ );+ expect(useChatStore.getState().openChatIds).toEqual(["chat-a"]);+ expect(onActivate).toHaveBeenCalledWith("chat-a");+ });++ it("closes an empty untitled draft on Ctrl+E instead of archiving it", async () => {+ const actions = useChatStore.getState().actions;+ actions.upsert(+ record({+ id: "chat-a",+ title: "keep",+ messageCount: 2,+ }),+ );+ actions.upsert(+ record({+ id: "draft",+ title: "untitled",+ messageCount: 0,+ draft: true,+ }),+ );+ actions.openChat("chat-a");+ actions.openChat("draft");+ const archiveConversation = vi.fn(async () => {});+ const onActivate = vi.fn();+ render(+ <ChatTabStrip+ activeId="draft"+ onActivate={onActivate}+ onNewChat={vi.fn()}+ archiveConversation={archiveConversation}+ />,+ );++ fireEvent.keyDown(window, { key: "e", code: "KeyE", ctrlKey: true });++ expect(archiveConversation).not.toHaveBeenCalled();+ expect(useChatStore.getState().openChatIds).toEqual(["chat-a"]);+ expect(onActivate).toHaveBeenCalledWith("chat-a");+ });++ it("prints the archive shortcut on the tab menu", async () => {+ const actions = useChatStore.getState().actions;+ actions.upsert(record({ id: "chat-a", title: "crm" }));+ actions.openChat("chat-a");++ render(+ <ChatTabStrip+ activeId="chat-a"+ onActivate={vi.fn()}+ onNewChat={vi.fn()}+ archiveConversation={vi.fn(async () => {})}+ />,+ );++ fireEvent.contextMenu(screen.getByRole("tab", { name: "crm" }));+ expect(await screen.findByText("Archive")).toBeVisible();+ expect(screen.getByText("Ctrl+E")).toBeVisible();+ });++ it("starts a new chat on Ctrl+E when the last real tab is archived", async () => {+ const actions = useChatStore.getState().actions;+ actions.upsert(record({ id: "chat-a", title: "only" }));+ actions.openChat("chat-a");+ const onNewChat = vi.fn();+ const archiveConversation = vi.fn(async () => {});+ render(+ <ChatTabStrip+ activeId="chat-a"+ onActivate={vi.fn()}+ onNewChat={onNewChat}+ archiveConversation={archiveConversation}+ />,+ );++ fireEvent.keyDown(window, { key: "e", code: "KeyE", ctrlKey: true });++ await waitFor(() =>+ expect(archiveConversation).toHaveBeenCalledWith("chat-a"),+ );+ expect(onNewChat).toHaveBeenCalledTimes(1);+ });+it("starts a new chat on Ctrl+W when the last tab is closed", () => {const actions = useChatStore.getState().actions;actions.upsert(record({ id: "chat-a", title: "only" }));diff --git a/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.tsx b/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.tsxindex aee81b7c0..313d7c22e 100644--- a/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.tsx+++ b/apps/screenpipe-app-tauri/components/chat/chat-tab-strip.tsx@@ -26,7 +26,10 @@ import type { Message } from "@/lib/chat/types";import { isInjectedTitle } from "@/lib/chat-utils";import { registerChatTabCloser } from "@/lib/close-tab-shortcut";import { usePlatform } from "@/lib/hooks/use-platform";-import { inAppShortcutLabel } from "@/lib/shortcuts";+import {+ inAppShortcutLabel,+ matchesInAppShortcut,+} from "@/lib/shortcuts";import {isEphemeralSideConversation,useChatActions,@@ -156,6 +159,7 @@ export function ChatTabStrip({const actions = useChatActions();const { isMac } = usePlatform();const closeShortcut = inAppShortcutLabel("close_tab", isMac);+ const archiveShortcut = inAppShortcutLabel("archive_chat", isMac);const scrollerRef = useRef<HTMLDivElement | null>(null);const closingActiveIdRef = useRef<string | null>(null);const [contextMenuRevision, setContextMenuRevision] = useState(0);@@ -180,9 +184,11 @@ export function ChatTabStrip({useEffect(() => {if (!activeId || closingActiveIdRef.current === activeId) return;+ const session = sessions[activeId];+ if (!session || session.hidden) return;closingActiveIdRef.current = null;actions.openChat(activeId);- }, [actions, activeId]);+ }, [actions, activeId, sessions]);useEffect(() => {if (!renamingId) return;@@ -257,6 +263,43 @@ export function ChatTabStrip({}}, [actions, activeId, onActivate, onNewChat, splitChatId, tabs]);+ const archiveTab = useCallback(+ (id: string) => {+ const session = sessions[id];+ if (!session || isEphemeralSideConversation(session)) return;+ const emptyDraft =+ session.draft === true &&+ session.messageCount === 0 &&+ session.kind !== "pipe-watch" &&+ session.kind !== "pipe-run";+ if (emptyDraft || !archiveConversation) {+ if (emptyDraft) closeTab(id);+ return;+ }+ void Promise.resolve(archiveConversation(id)).finally(() => {+ closeTab(id);+ });+ },+ [archiveConversation, closeTab, sessions],+ );++ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (!matchesInAppShortcut(event, "archive_chat", isMac)) return;+ if (document.querySelector('[role="dialog"][data-state="open"]')) return;+ if (renamingId) return;+ const id =+ (activeId && tabs.some((tab) => tab.id === activeId) && activeId) ||+ tabs[0]?.id;+ if (!id) return;+ event.preventDefault();+ event.stopPropagation();+ archiveTab(id);+ };+ window.addEventListener("keydown", onKey, true);+ return () => window.removeEventListener("keydown", onKey, true);+ }, [activeId, archiveTab, isMac, renamingId, tabs]);+useEffect(() => {return registerChatTabCloser(() => {const id =@@ -490,10 +533,13 @@ export function ChatTabStrip({<ContextMenuItemonSelect={() => {closeContextMenu();- void archiveConversation?.(session.id);+ archiveTab(session.id);}}>Archive+ <ContextMenuShortcut className="text-[10px] tracking-normal text-muted-foreground/55">+ {archiveShortcut}+ </ContextMenuShortcut></ContextMenuItem><ContextMenuSeparator /></>diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/chat-title-menu.test.tsx b/apps/screenpipe-app-tauri/components/chat/standalone/chat-title-menu.test.tsxindex 35ec3b907..0dbdbdd4b 100644--- a/apps/screenpipe-app-tauri/components/chat/standalone/chat-title-menu.test.tsx+++ b/apps/screenpipe-app-tauri/components/chat/standalone/chat-title-menu.test.tsx@@ -91,6 +91,25 @@ describe("ChatTitleMenu", () => {);});+ it("prints the archive shortcut on the title menu", async () => {+ render(+ <ChatTitleMenu+ conversationId={SESSION.id}+ messages={[+ { id: "u", role: "user", content: "day recap", timestamp: 1 },+ ]}+ renameConversation={vi.fn()}+ archiveConversation={vi.fn()}+ />,+ );++ fireEvent.click(+ screen.getByRole("button", { name: "chat options for day recap" }),+ );+ expect(await screen.findByRole("button", { name: "Archive" })).toBeVisible();+ expect(screen.getByText(/⌘E|Ctrl\+E/)).toBeVisible();+ });+it("renames the same conversation from the title-owned menu", async () => {const renameConversation = vi.fn(async () => {});render(diff --git a/apps/screenpipe-app-tauri/components/chat/standalone/chat-title-menu.tsx b/apps/screenpipe-app-tauri/components/chat/standalone/chat-title-menu.tsxindex f95b3a3b0..42f936f21 100644--- a/apps/screenpipe-app-tauri/components/chat/standalone/chat-title-menu.tsx+++ b/apps/screenpipe-app-tauri/components/chat/standalone/chat-title-menu.tsx@@ -4,10 +4,12 @@"use client";import * as React from "react";-import { useRef, useState } from "react";+import { useEffect, useRef, useState } from "react";import { Archive, MoreHorizontal, Pencil, Pin } from "lucide-react";import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";import type { Message } from "@/lib/chat/types";+import { usePlatform } from "@/lib/hooks/use-platform";+import { inAppShortcutLabel, matchesInAppShortcut } from "@/lib/shortcuts";import {isEphemeralSideConversation,useChatStore,@@ -41,6 +43,8 @@ export function ChatTitleMenu({const [renaming, setRenaming] = useState(false);const [draft, setDraft] = useState("");const inputRef = useRef<HTMLInputElement | null>(null);+ const { isMac } = usePlatform();+ const archiveShortcut = inAppShortcutLabel("archive_chat", isMac);// Title source order:// 1. The session's title from the chat-store (in-memory, freshest;@@ -66,6 +70,30 @@ export function ChatTitleMenu({messages,pendingUserText,});+ const canArchive =+ Boolean(conversationId && title) &&+ !isEphemeralSideConversation(session);++ useEffect(() => {+ if (!canArchive || !conversationId) return;+ const onKey = (event: KeyboardEvent) => {+ if (!matchesInAppShortcut(event, "archive_chat", isMac)) return;+ if (document.querySelector('[role="dialog"][data-state="open"]')) return;+ if (renaming) return;+ event.preventDefault();+ event.stopPropagation();+ setOpen(false);+ void archiveConversation(conversationId);+ };+ window.addEventListener("keydown", onKey, true);+ return () => window.removeEventListener("keydown", onKey, true);+ }, [+ archiveConversation,+ canArchive,+ conversationId,+ isMac,+ renaming,+ ]);// No conversation id OR no real content → don't render. The "+ New"// button on the right is enough; no point showing actions for a@@ -183,9 +211,13 @@ export function ChatTitleMenu({<buttonclassName="flex h-8 w-full items-center gap-2 px-2 text-left text-sm hover:bg-muted focus-visible:outline-none focus-visible:bg-muted"onClick={() => void handleArchive()}+ aria-label="Archive"><Archive className="h-3.5 w-3.5 shrink-0" aria-hidden />Archive+ <span className="ml-auto text-[10px] tracking-normal text-muted-foreground/55">+ {archiveShortcut}+ </span></button></PopoverContent></Popover>diff --git a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.tsindex cc55bd777..ec40a07a6 100644--- a/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts+++ b/apps/screenpipe-app-tauri/components/hooks/use-chat-conversations.ts@@ -1849,17 +1849,29 @@ export function useChatConversations(opts: UseChatConversationsOpts) {// The chat-title menu uses Archive as its safe primary history action.// Permanent deletion remains available from the sidebar row menu, where// the conversation being acted on is explicit and a confirmation follows.+ // Close the tab as part of archive. Sibling tabs stay the resume path;+ // mint a new chat only when this was the last open tab and the tab strip+ // is not already going to recover via ⌘W's closer.const archiveConversation = async (convId: string) => {+ const { fallbackOpenChatId, useChatStore } = await import(+ "@/lib/stores/chat-store"+ );+ const { hasRegisteredChatTabCloser } = await import(+ "@/lib/close-tab-shortcut"+ );+ const store = useChatStore.getState();+ const wasCurrent =+ conversationId === convId || piSessionIdRef.current === convId;+ const fallbackId = fallbackOpenChatId(store, convId);+await updateConversationFlags(convId, { hidden: true, pinned: false });commands.piAbort(convId).catch(() => {});-- const { useChatStore } = await import("@/lib/stores/chat-store");- const store = useChatStore.getState();store.actions.patch(convId, {hidden: true,pinned: false,unread: false,});+ store.actions.closeChat(convId);await refreshFileConversations();try {@@ -1869,7 +1881,19 @@ export function useChatConversations(opts: UseChatConversationsOpts) {// repair itself on its next disk hydration.}- if (conversationId === convId || piSessionIdRef.current === convId) {+ if (!wasCurrent) return;++ if (fallbackId) {+ store.actions.setCurrent(fallbackId);+ try {+ await emit("chat-load-conversation", { conversationId: fallbackId });+ } catch {+ // Local currentId already moved; the panel can recover on next click.+ }+ return;+ }++ if (!hasRegisteredChatTabCloser()) {await startNewConversation();}};diff --git a/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.tsindex eab375d09..4f04e9072 100644--- a/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts+++ b/apps/screenpipe-app-tauri/lib/__tests__/chat-store.test.ts@@ -15,6 +15,7 @@ import {selectRecentSwitcherSessions,selectVisibleOpenChatTabs,nextOpenChatTabId,+ fallbackOpenChatId,getOrCreateEmptyChatId,isReusableBlankChatSession,isEmptyChatShell,@@ -101,6 +102,24 @@ describe("chat-store: tab and split working set", () => {expect(nextOpenChatTabId(["A", "worktree"], "worktree", 1)).toBe("A");expect(nextOpenChatTabId(["A"], "A", 1)).toBeNull();});++ it("picks the next open tab after archive, then the previous", () => {+ const actions = useChatStore.getState().actions;+ actions.upsert(baseRecord({ id: "A" }));+ actions.upsert(baseRecord({ id: "B" }));+ actions.upsert(baseRecord({ id: "hidden", hidden: true }));+ actions.upsert(baseRecord({ id: "C" }));+ actions.openChat("A");+ actions.openChat("B");+ actions.openChat("hidden");+ actions.openChat("C");++ const state = useChatStore.getState();+ expect(fallbackOpenChatId(state, "B")).toBe("C");+ expect(fallbackOpenChatId(state, "C")).toBe("B");+ expect(fallbackOpenChatId(state, "A")).toBe("B");+ expect(fallbackOpenChatId({ sessions: state.sessions, openChatIds: ["A"] }, "A")).toBeNull();+ });});describe("chat-store: temporary side conversations", () => {diff --git a/apps/screenpipe-app-tauri/lib/__tests__/close-tab-shortcut.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/close-tab-shortcut.test.tsindex e0c19a814..2340cba34 100644--- a/apps/screenpipe-app-tauri/lib/__tests__/close-tab-shortcut.test.ts+++ b/apps/screenpipe-app-tauri/lib/__tests__/close-tab-shortcut.test.ts@@ -5,6 +5,7 @@import { afterEach, describe, expect, it, vi } from "vitest";import {consumeCloseShortcut,+ hasRegisteredChatTabCloser,registerChatTabCloser,resetCloseShortcutForTests,} from "@/lib/close-tab-shortcut";@@ -62,3 +63,13 @@ describe("consumeCloseShortcut", () => {expect(closeWindow).not.toHaveBeenCalled();});});++describe("hasRegisteredChatTabCloser", () => {+ it("is true only while a tab closer is registered", () => {+ expect(hasRegisteredChatTabCloser()).toBe(false);+ const unregister = registerChatTabCloser(() => true);+ expect(hasRegisteredChatTabCloser()).toBe(true);+ unregister();+ expect(hasRegisteredChatTabCloser()).toBe(false);+ });+});diff --git a/apps/screenpipe-app-tauri/lib/__tests__/shortcuts.test.ts b/apps/screenpipe-app-tauri/lib/__tests__/shortcuts.test.tsindex 62345f905..b6d1c3319 100644--- a/apps/screenpipe-app-tauri/lib/__tests__/shortcuts.test.ts+++ b/apps/screenpipe-app-tauri/lib/__tests__/shortcuts.test.ts@@ -18,6 +18,8 @@ describe("in-app shortcut registry", () => {expect(inAppShortcutLabel("new_chat", true)).toBe("⌘N");expect(inAppShortcutLabel("close_tab", true)).toBe("⌘W");expect(inAppShortcutLabel("close_tab", false)).toBe("Ctrl+W");+ expect(inAppShortcutLabel("archive_chat", true)).toBe("⌘E");+ expect(inAppShortcutLabel("archive_chat", false)).toBe("Ctrl+E");expect(inAppShortcutLabel("next_recent_chat", false)).toBe("Ctrl+Tab");});@@ -45,6 +47,30 @@ describe("in-app shortcut registry", () => {).toBe(false);});+ it("matches Cmd+E on macOS and Ctrl+E elsewhere", () => {+ expect(+ matchesInAppShortcut(+ keyEvent({ key: "e", code: "KeyE", metaKey: true }),+ "archive_chat",+ true,+ ),+ ).toBe(true);+ expect(+ matchesInAppShortcut(+ keyEvent({ key: "e", code: "KeyE", ctrlKey: true }),+ "archive_chat",+ false,+ ),+ ).toBe(true);+ expect(+ matchesInAppShortcut(+ keyEvent({ key: "e", code: "KeyE", metaKey: true }),+ "close_tab",+ true,+ ),+ ).toBe(false);+ });+it("requires exact modifiers so OS and app chords do not overlap", () => {expect(matchesInAppShortcut(diff --git a/apps/screenpipe-app-tauri/lib/close-tab-shortcut.ts b/apps/screenpipe-app-tauri/lib/close-tab-shortcut.tsindex 935954435..b81d3fc3b 100644--- a/apps/screenpipe-app-tauri/lib/close-tab-shortcut.ts+++ b/apps/screenpipe-app-tauri/lib/close-tab-shortcut.ts@@ -18,6 +18,10 @@ export function registerChatTabCloser(handler: () => boolean): () => void {};}+export function hasRegisteredChatTabCloser(): boolean {+ return closeTabHandler !== null;+}+export function resetCloseShortcutForTests(): void {closeTabHandler = null;lastConsumedAt = 0;diff --git a/apps/screenpipe-app-tauri/lib/shortcuts.ts b/apps/screenpipe-app-tauri/lib/shortcuts.tsindex dc68be766..1a1a8297d 100644--- a/apps/screenpipe-app-tauri/lib/shortcuts.ts+++ b/apps/screenpipe-app-tauri/lib/shortcuts.ts@@ -8,6 +8,7 @@ import { useShortcutGuideStore } from "@/lib/stores/shortcut-guide-store";export type InAppShortcutId =| "new_chat"| "close_tab"+ | "archive_chat"| "command_menu"| "shortcut_guide"| "toggle_sidebar"@@ -36,6 +37,12 @@ export const IN_APP_SHORTCUTS: readonly InAppShortcutDefinition[] = [label: "close tab",description: "close the current chat tab, not the app",},+ {+ id: "archive_chat",+ section: "chat",+ label: "archive chat",+ description: "hide this conversation, stop the agent, and close the tab",+ },{id: "next_recent_chat",section: "chat",@@ -115,6 +122,8 @@ export function inAppShortcutLabel(return `${primary}N`;case "close_tab":return `${primary}W`;+ case "archive_chat":+ return `${primary}E`;case "command_menu":return `${primary}K`;case "shortcut_guide":@@ -149,6 +158,8 @@ function specFor(id: InAppShortcutId, isMac: boolean): ShortcutSpec {return { ...primary, key: "n", code: "KeyN" };case "close_tab":return { ...primary, key: "w", code: "KeyW" };+ case "archive_chat":+ return { ...primary, key: "e", code: "KeyE" };case "command_menu":return { ...primary, key: "k", code: "KeyK" };case "shortcut_guide":diff --git a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts b/apps/screenpipe-app-tauri/lib/stores/chat-store.tsindex d44702fea..97f787547 100644--- a/apps/screenpipe-app-tauri/lib/stores/chat-store.ts+++ b/apps/screenpipe-app-tauri/lib/stores/chat-store.ts@@ -1300,6 +1300,31 @@ export function selectVisibleOpenChatTabs(state: {);}+/** Next tab after close/archive: the neighbor to the right, else left. */+export function fallbackOpenChatId(+ state: {+ sessions: Record<string, SessionRecord>;+ openChatIds: string[];+ },+ closingId: string,+): string | null {+ const isKeep = (id: string) => {+ if (id === closingId) return false;+ const session = state.sessions[id];+ return Boolean(session && !session.hidden);+ };+ const index = state.openChatIds.indexOf(closingId);+ if (index >= 0) {+ for (let i = index + 1; i < state.openChatIds.length; i++) {+ if (isKeep(state.openChatIds[i])) return state.openChatIds[i];+ }+ for (let i = index - 1; i >= 0; i--) {+ if (isKeep(state.openChatIds[i])) return state.openChatIds[i];+ }+ }+ return state.openChatIds.find(isKeep) ?? null;+}+export function nextOpenChatTabId(tabIds: string[],currentId: string | null,