Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

feat: add re-run button to research history items (#1779)

LearningCircuitd425693669bf
diff --git a/src/local_deep_research/web/static/css/components/history-icons.css b/src/local_deep_research/web/static/css/components/history-icons.css
index efb2d8c5ad..9b5e09bc54 100644
--- a/src/local_deep_research/web/static/css/components/history-icons.css
+++ b/src/local_deep_research/web/static/css/components/history-icons.css
@@ -63,6 +63,17 @@
color: var(--success-color);
}
+/* Re-run button specific styling */
+.ldr-history-item-actions .ldr-rerun-btn {
+ color: var(--accent-tertiary);
+ border-color: var(--accent-tertiary);
+}
+
+.ldr-history-item-actions .ldr-rerun-btn:hover {
+ background-color: rgba(var(--accent-tertiary-rgb), 0.1);
+ color: var(--accent-secondary);
+}
+
/* Delete button specific styling */
.ldr-history-item-actions .ldr-delete-item-btn {
color: var(--error-color);
diff --git a/src/local_deep_research/web/static/js/components/history.js b/src/local_deep_research/web/static/js/components/history.js
index 2132abc874..17b39840b3 100644
--- a/src/local_deep_research/web/static/js/components/history.js
+++ b/src/local_deep_research/web/static/js/components/history.js
@@ -358,6 +358,10 @@
`<button class="btn btn-sm ldr-btn-outline ldr-subscribe-btn" data-research-id="${esc(item.id)}" data-query="${esc(encodeURIComponent(item.query))}">
<i class="fas fa-bell"></i> Subscribe
</button>` : ''}
+ ${item.status === 'completed' ?
+ `<button class="btn btn-sm ldr-btn-outline ldr-rerun-btn" title="Re-run this research">
+ <i class="fas fa-redo"></i> Re-run
+ </button>` : ''}
<button class="btn btn-sm ldr-btn-outline ldr-delete-item-btn">
<i class="fas fa-trash-alt"></i>
</button>
@@ -389,6 +393,14 @@
});
}
+ const rerunBtn = itemEl.querySelector('.ldr-rerun-btn');
+ if (rerunBtn) {
+ rerunBtn.addEventListener('click', (e) => {
+ e.stopPropagation(); // Prevent item click
+ handleRerun(item);
+ });
+ }
+
const deleteBtn = itemEl.querySelector('.ldr-delete-item-btn');
if (deleteBtn) {
deleteBtn.addEventListener('click', (e) => {
@@ -423,6 +435,21 @@
URLValidator.safeAssign(window.location, 'href', `/news/subscriptions/new?${params.toString()}`);
}
+ /**
+ * Handle re-run button click
+ * Stores research config in sessionStorage and navigates to research page
+ * @param {Object} item - The research item to re-run
+ */
+ function handleRerun(item) {
+ const rerunConfig = {
+ query: item.query,
+ mode: item.mode
+ };
+
+ sessionStorage.setItem('rerunConfig', JSON.stringify(rerunConfig));
+ URLValidator.safeAssign(window.location, 'href', '/');
+ }
+
// Modal-based subscription removed - now redirects to dedicated form page
// Folder loading removed - handled by dedicated form page
diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.js
index 34c8d2771f..19e594da09 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -67,6 +67,9 @@
// Track initialization to prevent unwanted saves during initial setup
let isInitializing = true;
+ // Store pending rerun config to apply after initialization completes
+ let pendingRerunConfig = null;
+
/**
* Select a research mode (both visual and radio button)
* @param {HTMLElement} modeElement - The mode option element that was selected
@@ -112,6 +115,81 @@
return provider ? provider.is_cloud === false : false;
}
+ /**
+ * Check for rerun configuration from sessionStorage.
+ * Stores it for later application after initialization completes.
+ */
+ function checkAndApplyRerunConfig() {
+ const rerunConfigStr = sessionStorage.getItem('rerunConfig');
+ if (!rerunConfigStr) return;
+
+ try {
+ pendingRerunConfig = JSON.parse(rerunConfigStr);
+ sessionStorage.removeItem('rerunConfig'); // Clear immediately
+ SafeLogger.log('Stored pending rerun config:', pendingRerunConfig);
+ } catch (e) {
+ SafeLogger.error('Error parsing rerun config:', e);
+ sessionStorage.removeItem('rerunConfig');
+ pendingRerunConfig = null;
+ }
+ }
+
+ /**
+ * Apply pending rerun configuration after initialization is complete.
+ * Only pre-fills query and mode; all other settings come from the
+ * settings manager / database (the current user defaults).
+ */
+ function applyPendingRerunConfig() {
+ if (!pendingRerunConfig) return;
+
+ const config = pendingRerunConfig;
+ pendingRerunConfig = null; // Clear to prevent re-application
+ SafeLogger.log('Applying rerun config:', config);
+
+ // Set query
+ const queryEl = document.getElementById('query');
+ if (queryEl && config.query) {
+ queryEl.value = config.query;
+ }
+
+ // Set mode via the visible label element so both the radio and
+ // the visual highlight update correctly
+ if (config.mode) {
+ const modeOption = document.querySelector(`.ldr-mode-option[data-mode="${config.mode}"]`);
+ if (modeOption) {
+ selectMode(modeOption);
+ }
+ }
+
+ // Show notification
+ showRerunNotification();
+ }
+
+ /**
+ * Called when initialization completes. Applies any pending rerun config.
+ */
+ function onInitializationComplete() {
+ SafeLogger.log('Initialization complete, checking for pending rerun config');
+ applyPendingRerunConfig();
+ }
+
+ /**
+ * Show notification that form has been pre-filled for re-run
+ */
+ function showRerunNotification() {
+ const alertContainer = document.getElementById('research-alert');
+ if (alertContainer) {
+ alertContainer.style.display = 'block';
+ alertContainer.innerHTML = `
+ <div class="alert alert-info alert-dismissible fade show" role="alert">
+ <i class="fas fa-redo me-2"></i>
+ Re-running previous research. Review settings and click "Start Research" when ready.
+ <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
+ </div>
+ `;
+ }
+ }
+
/**
* Initialize the research component
*/
@@ -120,6 +198,9 @@
isInitializing = true;
SafeLogger.log('=== Starting research page initialization. isInitializing:', isInitializing);
+ // Check for rerun config from history page
+ checkAndApplyRerunConfig();
+
// Get DOM elements
form = document.getElementById('research-form');
queryInput = document.getElementById('query');
@@ -1545,6 +1626,7 @@
numApiCallsPending--;
isInitializing = (numApiCallsPending === 0);
SafeLogger.log('Settings loaded. isInitializing now:', isInitializing, 'pending calls:', numApiCallsPending);
+ if (!isInitializing) onInitializationComplete();
})
.catch(error => {
SafeLogger.error('Error loading settings:', error);
@@ -1556,6 +1638,7 @@
numApiCallsPending--;
isInitializing = (numApiCallsPending === 0);
SafeLogger.log('Settings load error. isInitializing now:', isInitializing, 'pending calls:', numApiCallsPending);
+ if (!isInitializing) onInitializationComplete();
});
// Load search strategy setting
@@ -1589,6 +1672,7 @@
numApiCallsPending--;
isInitializing = (numApiCallsPending === 0);
SafeLogger.log('Strategy loaded. isInitializing now:', isInitializing, 'pending calls:', numApiCallsPending);
+ if (!isInitializing) onInitializationComplete();
})
.catch(error => {
SafeLogger.error('Error loading strategy:', error);
@@ -1603,6 +1687,7 @@
numApiCallsPending--;
isInitializing = (numApiCallsPending === 0);
SafeLogger.log('Strategy load error. isInitializing now:', isInitializing, 'pending calls:', numApiCallsPending);
+ if (!isInitializing) onInitializationComplete();
});
}
diff --git a/tests/infrastructure_tests/test_rerun_config.test.js b/tests/infrastructure_tests/test_rerun_config.test.js
new file mode 100644
index 0000000000..d9293f1182
--- /dev/null
+++ b/tests/infrastructure_tests/test_rerun_config.test.js
@@ -0,0 +1,224 @@
+/**
+ * Jest unit tests for Re-run Research configuration handling.
+ *
+ * Tests the logic for:
+ * 1. Building rerun config from research items (history.js handleRerun)
+ * 2. Parsing and applying rerun config (research.js checkAndApplyRerunConfig)
+ *
+ * Note: Re-run only stores query and mode. All other settings (model, provider,
+ * search engine, etc.) come from the user's current defaults via the settings manager.
+ *
+ * Run with: npx jest tests/infrastructure_tests/test_rerun_config.test.js
+ */
+
+// Mock sessionStorage
+const mockSessionStorage = {
+ store: {},
+ getItem: jest.fn((key) => mockSessionStorage.store[key] || null),
+ setItem: jest.fn((key, value) => { mockSessionStorage.store[key] = value; }),
+ removeItem: jest.fn((key) => { delete mockSessionStorage.store[key]; }),
+ clear: jest.fn(() => { mockSessionStorage.store = {}; })
+};
+
+// Mock URLValidator
+const mockURLValidator = {
+ safeAssign: jest.fn()
+};
+
+// Setup globals
+global.sessionStorage = mockSessionStorage;
+global.URLValidator = mockURLValidator;
+global.window = {
+ location: { href: '' }
+};
+
+// ============================================================================
+// handleRerun Logic Tests (from history.js)
+// ============================================================================
+
+describe('handleRerun Configuration Building', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockSessionStorage.clear();
+ });
+
+ /**
+ * Simulates the handleRerun function logic.
+ * Only stores query and mode - no advanced settings.
+ */
+ function buildRerunConfig(item) {
+ return {
+ query: item.query,
+ mode: item.mode
+ };
+ }
+
+ describe('Basic Config Building', () => {
+ test('should include query and mode from item', () => {
+ const item = {
+ query: 'What is quantum computing?',
+ mode: 'detailed'
+ };
+
+ const config = buildRerunConfig(item);
+
+ expect(config.query).toBe('What is quantum computing?');
+ expect(config.mode).toBe('detailed');
+ });
+
+ test('should handle missing mode gracefully', () => {
+ const item = {
+ query: 'Test query'
+ // mode is undefined
+ };
+
+ const config = buildRerunConfig(item);
+
+ expect(config.query).toBe('Test query');
+ expect(config.mode).toBeUndefined();
+ });
+
+ test('should handle empty query', () => {
+ const item = {
+ query: '',
+ mode: 'quick'
+ };
+
+ const config = buildRerunConfig(item);
+
+ expect(config.query).toBe('');
+ expect(config.mode).toBe('quick');
+ });
+ });
+
+ describe('Advanced settings are NOT included', () => {
+ test('should not include submission params even when present', () => {
+ const item = {
+ query: 'Test query',
+ mode: 'detailed',
+ metadata: {
+ submission: {
+ model_provider: 'OLLAMA',
+ model: 'llama3',
+ search_engine: 'duckduckgo',
+ iterations: 5,
+ questions_per_iteration: 3,
+ strategy: 'focused-iteration'
+ }
+ }
+ };
+
+ const config = buildRerunConfig(item);
+
+ expect(config.query).toBe('Test query');
+ expect(config.mode).toBe('detailed');
+ expect(config.model_provider).toBeUndefined();
+ expect(config.model).toBeUndefined();
+ expect(config.search_engine).toBeUndefined();
+ expect(config.iterations).toBeUndefined();
+ expect(config.questions_per_iteration).toBeUndefined();
+ expect(config.strategy).toBeUndefined();
+ });
+
+ test('should only have query and mode keys', () => {
+ const item = {
+ query: 'Test query',
+ mode: 'quick',
+ metadata: { submission: { model_provider: 'OPENAI' } }
+ };
+
+ const config = buildRerunConfig(item);
+ const keys = Object.keys(config);
+
+ expect(keys).toEqual(['query', 'mode']);
+ });
+ });
+
+});
+
+// ============================================================================
+// checkAndApplyRerunConfig Logic Tests (from research.js)
+// ============================================================================
+
+describe('checkAndApplyRerunConfig Parsing', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockSessionStorage.clear();
+ });
+
+ /**
+ * Simulates the config parsing logic from checkAndApplyRerunConfig
+ */
+ function parseRerunConfig() {
+ const rerunConfigStr = sessionStorage.getItem('rerunConfig');
+ if (!rerunConfigStr) return null;
+
+ try {
+ const config = JSON.parse(rerunConfigStr);
+ sessionStorage.removeItem('rerunConfig');
+ return config;
+ } catch (e) {
+ sessionStorage.removeItem('rerunConfig');
+ return null;
+ }
+ }
+
+ describe('Valid Config Parsing', () => {
+ test('should parse valid JSON config', () => {
+ const config = { query: 'Test', mode: 'quick' };
+ sessionStorage.setItem('rerunConfig', JSON.stringify(config));
+
+ const parsed = parseRerunConfig();
+
+ expect(parsed).toEqual(config);
+ expect(sessionStorage.getItem('rerunConfig')).toBeNull();
+ });
+
+ test('should parse config with query and mode', () => {
+ const config = {
+ query: 'Full config test',
+ mode: 'detailed'
+ };
+ sessionStorage.setItem('rerunConfig', JSON.stringify(config));
+
+ const parsed = parseRerunConfig();
+
+ expect(parsed).toEqual(config);
+ });
+ });
+
+ describe('Invalid Config Handling', () => {
+ test('should return null for invalid JSON', () => {
+ sessionStorage.setItem('rerunConfig', 'not valid json {{{');
+
+ const parsed = parseRerunConfig();
+
+ expect(parsed).toBeNull();
+ expect(sessionStorage.getItem('rerunConfig')).toBeNull();
+ });
+
+ test('should return null for empty string', () => {
+ sessionStorage.setItem('rerunConfig', '');
+
+ const parsed = parseRerunConfig();
+
+ expect(parsed).toBeNull();
+ });
+
+ test('should return null when no config exists', () => {
+ const parsed = parseRerunConfig();
+
+ expect(parsed).toBeNull();
+ });
+
+ test('should handle truncated JSON', () => {
+ sessionStorage.setItem('rerunConfig', '{"query": "test"');
+
+ const parsed = parseRerunConfig();
+
+ expect(parsed).toBeNull();
+ expect(sessionStorage.getItem('rerunConfig')).toBeNull();
+ });
+ });
+
+});
diff --git a/tests/ui_tests/test_history_page.js b/tests/ui_tests/test_history_page.js
index 4931910437..cebcbc9941 100644
--- a/tests/ui_tests/test_history_page.js
+++ b/tests/ui_tests/test_history_page.js
@@ -221,6 +221,123 @@ async function testHistoryPage() {
log(` - Has back/home button: ${navigationElements.hasBackButton}`, 'info');
log(` - Has new research button: ${navigationElements.hasNewResearchButton}`, 'info');
+ // Test re-run button on history items
+ log('\n=== TESTING RE-RUN BUTTON ===', 'section');
+ const rerunButtonInfo = await page.evaluate(() => {
+ const historyItems = document.querySelectorAll('.ldr-history-item, [data-research-id]');
+ const rerunButtons = document.querySelectorAll('.ldr-rerun-btn');
+
+ // Helper to check true visibility
+ function isVisible(el) {
+ if (!el) return false;
+ const style = getComputedStyle(el);
+ const rect = el.getBoundingClientRect();
+ return style.display !== 'none' &&
+ style.visibility !== 'hidden' &&
+ parseFloat(style.opacity) > 0 &&
+ rect.width > 0 && rect.height > 0;
+ }
+
+ // Check each item for re-run button
+ const itemDetails = [];
+ historyItems.forEach(item => {
+ const status = item.querySelector('.ldr-status-badge, .status-badge');
+ const rerunBtn = item.querySelector('.ldr-rerun-btn');
+ const statusText = status?.textContent?.trim().toLowerCase() || 'unknown';
+
+ itemDetails.push({
+ status: statusText,
+ hasRerunBtn: !!rerunBtn,
+ isVisible: isVisible(rerunBtn),
+ // Re-run should only show on completed items
+ isCorrect: statusText === 'completed' ? (!!rerunBtn && isVisible(rerunBtn)) : !rerunBtn
+ });
+ });
+
+ // Check button styling if any exist
+ let buttonStyle = null;
+ if (rerunButtons.length > 0) {
+ const btn = rerunButtons[0];
+ const style = getComputedStyle(btn);
+ buttonStyle = {
+ hasIcon: !!btn.querySelector('i, .fa-redo, [class*="fa-"]'),
+ cursor: style.cursor,
+ hasTitle: !!btn.title
+ };
+ }
+
+ return {
+ totalItems: historyItems.length,
+ totalRerunButtons: rerunButtons.length,
+ items: itemDetails,
+ allCorrect: itemDetails.every(i => i.isCorrect),
+ buttonStyle
+ };
+ });
+
+ log(` - Total history items: ${rerunButtonInfo.totalItems}`, 'info');
+ log(` - Re-run buttons found: ${rerunButtonInfo.totalRerunButtons}`, 'info');
+
+ if (rerunButtonInfo.totalItems > 0) {
+ rerunButtonInfo.items.forEach((item, idx) => {
+ const mark = item.isCorrect ? '✓' : '✗';
+ log(` - Item ${idx + 1}: status=${item.status}, hasBtn=${item.hasRerunBtn}, visible=${item.isVisible} ${mark}`, 'info');
+ });
+
+ if (rerunButtonInfo.allCorrect) {
+ log('✅ Re-run buttons correctly shown only on completed items', 'success');
+ } else {
+ log('⚠️ Re-run button visibility issue detected', 'warning');
+ }
+
+ if (rerunButtonInfo.buttonStyle) {
+ log(` - Button has icon: ${rerunButtonInfo.buttonStyle.hasIcon}`, 'info');
+ log(` - Button cursor: ${rerunButtonInfo.buttonStyle.cursor}`, 'info');
+ if (rerunButtonInfo.buttonStyle.cursor === 'pointer') {
+ log('✅ Re-run button has pointer cursor', 'success');
+ }
+ }
+ } else {
+ log('ℹ️ No history items to test re-run button on', 'info');
+ }
+
+ // Test re-run button click if available
+ if (rerunButtonInfo.totalRerunButtons > 0) {
+ log('\n=== TESTING RE-RUN BUTTON CLICK ===', 'section');
+
+ // Get query before clicking
+ const queryBefore = await page.evaluate(() => {
+ const item = document.querySelector('.ldr-history-item, [data-research-id]');
+ const queryEl = item?.querySelector('.ldr-history-item-query, .query-text, h5, h6');
+ return queryEl?.textContent?.trim() || '';
+ });
+
+ log(` - Query to re-run: "${queryBefore.substring(0, 50)}..."`, 'info');
+
+ // Click the re-run button
+ await page.click('.ldr-rerun-btn');
+ await delay(2000);
+
+ // Check if we navigated and form is populated
+ const afterClick = await page.evaluate(() => {
+ const queryEl = document.getElementById('query');
+ return {
+ url: window.location.pathname,
+ queryValue: queryEl?.value || '',
+ hasNotification: !!document.querySelector('.alert-info')
+ };
+ });
+
+ log(` - Navigated to: ${afterClick.url}`, 'info');
+ log(` - Form query: "${afterClick.queryValue.substring(0, 50)}..."`, 'info');
+ log(` - Re-run notification: ${afterClick.hasNotification}`, 'info');
+
+ if (afterClick.url === '/' && afterClick.queryValue.length > 0) {
+ log('✅ Re-run button works correctly', 'success');
+ } else {
+ log('⚠️ Re-run navigation or form population issue', 'warning');
+ }
+ }
log('\n✅ History page test completed successfully!', 'success');
diff --git a/tests/ui_tests/test_research_form.js b/tests/ui_tests/test_research_form.js
index 0d5fb734f9..889351706b 100644
--- a/tests/ui_tests/test_research_form.js
+++ b/tests/ui_tests/test_research_form.js
@@ -113,6 +113,68 @@ async function testResearchForm() {
console.log(` - "${btn.text}" (form: ${btn.form})`);
});
+ // Test re-run form pre-population via sessionStorage
+ console.log('\n🔄 Testing re-run form pre-population...\n');
+
+ const rerunTestConfig = {
+ query: 'Test re-run query from sessionStorage',
+ mode: 'quick'
+ };
+
+ // Set sessionStorage and reload
+ await page.evaluate((config) => {
+ sessionStorage.setItem('rerunConfig', JSON.stringify(config));
+ }, rerunTestConfig);
+
+ await page.goto(baseUrl, { waitUntil: 'domcontentloaded', timeout: 30000 });
+ await new Promise(resolve => setTimeout(resolve, 3000)); // Wait for initialization
+
+ // Check if form was pre-populated
+ const rerunResult = await page.evaluate((expectedQuery) => {
+ const queryEl = document.getElementById('query');
+ const notification = document.querySelector('.alert-info');
+ const sessionCleared = !sessionStorage.getItem('rerunConfig');
+
+ return {
+ queryValue: queryEl?.value || '',
+ queryMatches: queryEl?.value === expectedQuery,
+ hasNotification: !!notification,
+ sessionCleared
+ };
+ }, rerunTestConfig.query);
+
+ console.log(` - Query pre-filled: ${rerunResult.queryMatches ? '✅' : '❌'} (got: "${rerunResult.queryValue.substring(0, 40)}...")`);
+ console.log(` - Re-run notification: ${rerunResult.hasNotification ? '✅' : '⚠️'}`);
+ console.log(` - SessionStorage cleared: ${rerunResult.sessionCleared ? '✅' : '❌'}`);
+
+ if (rerunResult.queryMatches && rerunResult.sessionCleared) {
+ console.log('✅ Re-run form pre-population works correctly');
+ } else {
+ console.log('⚠️ Re-run form pre-population may have issues');
+ }
+
+ // Test edge case: invalid JSON in sessionStorage
+ console.log('\n🧪 Testing invalid sessionStorage handling...');
+ await page.evaluate(() => {
+ sessionStorage.setItem('rerunConfig', 'invalid json {{{');
+ });
+
+ await page.goto(baseUrl, { waitUntil: 'domcontentloaded', timeout: 30000 });
+ await new Promise(resolve => setTimeout(resolve, 2000));
+
+ const invalidJsonResult = await page.evaluate(() => {
+ const pageLoaded = !!document.getElementById('query');
+ const sessionCleared = !sessionStorage.getItem('rerunConfig');
+ return { pageLoaded, sessionCleared };
+ });
+
+ console.log(` - Page loaded after invalid JSON: ${invalidJsonResult.pageLoaded ? '✅' : '❌'}`);
+ console.log(` - Invalid config cleared: ${invalidJsonResult.sessionCleared ? '✅' : '❌'}`);
+
+ if (invalidJsonResult.pageLoaded && invalidJsonResult.sessionCleared) {
+ console.log('✅ Invalid sessionStorage handled gracefully');
+ }
+
// Try to find the correct form and submit a search
console.log('\n🔎 Attempting to submit a search...\n');