import { AutocompletePlugin } from '@algolia/autocomplete-js'; import { getI18n } from 'react-i18next'; import { useTabStore } from '../../../store/tabStore'; import { TabType } from '../../../types/tab'; import { getTabTypeIcon, highlightHits } from '../styles'; type TabSource = { id: string; title: string; type: TabType; favicon?: string; }; export const createClosedTabsPlugin = (): AutocompletePlugin => { const { t } = getI18n(); const plugin = { getSources({ query }) { return [ { sourceId: 'closedTabsSource', getItems() { const { closedTabs } = useTabStore.getState(); if (!query) { return closedTabs.map((tab) => ({ id: tab.id, title: tab.title, type: tab.type, favicon: (tab as { favicon?: string }).favicon, })); } const lowerCaseQuery = query.toLowerCase(); return closedTabs .filter((tab) => tab.title.toLowerCase().includes(lowerCaseQuery)) .map((tab) => ({ id: tab.id, title: tab.title, type: tab.type, favicon: (tab as { favicon?: string }).favicon, })); }, templates: { header() { return (
{t('Search.RecentlyClosedTabs', { ns: 'agent' })}
); }, item({ item, state }) { return (
{item.favicon ? (
{item.favicon}
) : (
{getTabTypeIcon(item.type)}
)}
); }, noResults() { return (
{t('Search.NoClosedTabsFound', { ns: 'agent' })}
); }, }, onSelect: async ({ item: _item }) => { try { const tabStore = useTabStore.getState(); const { activeTabId, tabs } = tabStore; // Handle current active tab if (activeTabId) { const activeTab = tabs.find(tab => tab.id === activeTabId); // Always close NEW_TAB type tabs when selecting from search if (activeTab && activeTab.type === TabType.NEW_TAB) { // await is needed because closeTab returns a Promise await window.service.agentBrowser.closeTab(activeTabId); } } // Restore recently closed tab using the service directly const restoredTab = await window.service.agentBrowser.restoreClosedTab(); // For tabs restored via the API, the tab is already added to the store // Just activate the tab if it was successfully restored if (restoredTab && restoredTab.id) { // Let the tabStore handle this instead of directly calling the service void tabStore.initialize(); } } catch (error) { console.error('Failed to restore closed tab from search:', error); } }, }, ]; }, } satisfies AutocompletePlugin; return plugin; };