diff --git a/.github/workflows/mac-release.yml b/.github/workflows/mac-release.yml
index dc060f73..c771889b 100644
--- a/.github/workflows/mac-release.yml
+++ b/.github/workflows/mac-release.yml
@@ -44,9 +44,11 @@ env:
jobs:
resolve-release-target:
runs-on: ubuntu-latest
+ # The only output is the validated tag (v.., confirmed
+ # to exist). Every checkout below pins refs/tags/, so no job checks
+ # out a branch or any other caller-chosen ref.
outputs:
tag: ${{ steps.resolve.outputs.tag }}
- ref: ${{ steps.resolve.outputs.ref }}
steps:
- name: Resolve and validate release target
id: resolve
@@ -63,7 +65,6 @@ jobs:
return;
}
core.setOutput("tag", tag);
- core.setOutput("ref", `refs/tags/${tag}`);
return;
}
@@ -87,7 +88,6 @@ jobs:
}
core.setOutput("tag", requestedTag);
- core.setOutput("ref", `refs/tags/${requestedTag}`);
build-macos:
needs: resolve-release-target
@@ -111,7 +111,7 @@ jobs:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- ref: ${{ needs.resolve-release-target.outputs.ref }}
+ ref: refs/tags/${{ needs.resolve-release-target.outputs.tag }}
fetch-depth: 0
- name: Verify package version matches release tag
env:
@@ -123,7 +123,26 @@ jobs:
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version-file: '.nvmrc'
- cache: npm
+ # Restore-only npm cache (next two steps): a release build reads the
+ # cache that ordinary CI writes on main but never saves one, so a
+ # release run cannot seed the default-branch cache scope. setup-node
+ # would save in its post step, so its own caching stays off.
+ package-manager-cache: false
+
+ - name: Locate npm cache directory
+ id: npm-cache-dir
+ run: echo "dir=$(npm config get cache)" >> "$GITHUB_OUTPUT"
+
+ - name: Restore npm cache (read-only)
+ # Same path and key format as setup-node's `cache: npm` (used by CI on
+ # main), so its entries match here. matrix.arch equals the runner's
+ # os.arch() on every leg of this job.
+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: ${{ steps.npm-cache-dir.outputs.dir }}
+ key: node-cache-${{ runner.os }}-${{ matrix.arch }}-npm-${{ hashFiles('package-lock.json') }}
+ restore-keys: |
+ node-cache-${{ runner.os }}-${{ matrix.arch }}-npm-
- name: Verify macOS build assets
run: node scripts/verify-build-assets.js --platform=mac
@@ -383,7 +402,7 @@ jobs:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- ref: ${{ needs.resolve-release-target.outputs.ref }}
+ ref: refs/tags/${{ needs.resolve-release-target.outputs.tag }}
fetch-depth: 0
- name: Free disk space on runner
@@ -423,7 +442,26 @@ jobs:
uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
with:
node-version-file: '.nvmrc'
- cache: npm
+ # Restore-only npm cache (next two steps): a release build reads the
+ # cache that ordinary CI writes on main but never saves one, so a
+ # release run cannot seed the default-branch cache scope. setup-node
+ # would save in its post step, so its own caching stays off.
+ package-manager-cache: false
+
+ - name: Locate npm cache directory
+ id: npm-cache-dir
+ run: echo "dir=$(npm config get cache)" >> "$GITHUB_OUTPUT"
+
+ - name: Restore npm cache (read-only)
+ # Same path and key format as setup-node's `cache: npm` (used by CI on
+ # main), so its entries match here. matrix.arch equals the runner's
+ # os.arch() on every leg of this job.
+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ with:
+ path: ${{ steps.npm-cache-dir.outputs.dir }}
+ key: node-cache-${{ runner.os }}-${{ matrix.arch }}-npm-${{ hashFiles('package-lock.json') }}
+ restore-keys: |
+ node-cache-${{ runner.os }}-${{ matrix.arch }}-npm-
- name: Install dependencies (with optional deps)
run: npm ci --include=optional
@@ -549,7 +587,7 @@ jobs:
- name: Checkout
uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
- ref: ${{ needs.resolve-release-target.outputs.ref }}
+ ref: refs/tags/${{ needs.resolve-release-target.outputs.tag }}
fetch-depth: 0
- name: Download macOS artifacts
diff --git a/docs/MCP_SERVER.md b/docs/MCP_SERVER.md
index f6f782db..f862945f 100644
--- a/docs/MCP_SERVER.md
+++ b/docs/MCP_SERVER.md
@@ -129,7 +129,7 @@ Search the indexed corpus by meaning, keyword, or both.
```json
{
- "query": "string (1..1000)",
+ "query": "string (2..1000)",
"top_k": 10,
"mode": "hybrid",
"smart_folder_id": "optional-uuid"
diff --git a/scripts/compose-walkthrough-media.js b/scripts/compose-walkthrough-media.js
index ca42ea7e..cca1377f 100644
--- a/scripts/compose-walkthrough-media.js
+++ b/scripts/compose-walkthrough-media.js
@@ -29,8 +29,6 @@ const ROOT = path.resolve(__dirname, '..');
const OUT_DIR = path.join(ROOT, 'docs', 'walkthrough-assets');
const RAW_DIR = path.join(OUT_DIR, 'tour-raw');
const SHORT_DIR = path.join(OUT_DIR, 'shorts');
-const VIDEO = path.join(RAW_DIR, 'app.webm');
-const ACTIONS = path.join(RAW_DIR, 'actions.json');
const LOGO = path.join(ROOT, 'assets', 'stratosort-logo.png');
const FPS = 25;
@@ -470,9 +468,13 @@ function probeVideo(file) {
};
}
-/** Paths inside a filter graph: forward slashes, and the drive colon escaped. */
+/**
+ * Paths inside a filter graph: forward slashes, and the drive colon escaped.
+ * One pass handles both characters, so every backslash in the input becomes
+ * '/' and the only backslashes in the result are the ones escaping ':'.
+ */
function ffPath(file) {
- return file.replace(/\\/g, '/').replace(/:/g, '\\:');
+ return file.replace(/[\\:]/g, (ch) => (ch === ':' ? '\\:' : '/'));
}
const even = (n) => Math.max(2, Math.floor(n / 2) * 2);
diff --git a/scripts/verify-splash-csp-hash.js b/scripts/verify-splash-csp-hash.js
index 28df0821..7c81d8fc 100644
--- a/scripts/verify-splash-csp-hash.js
+++ b/scripts/verify-splash-csp-hash.js
@@ -24,7 +24,9 @@ function main() {
}
const html = fs.readFileSync(indexPath, 'utf8');
const inlineBodies = [];
- const re = /"); the
+ // browser still ends the script there, so the hashed body must end there too.
+ const re = /", ""); browsers still close the element there.
+ scriptTags: /",
+ // ""); browsers still close the element there, so match it too.
+ scriptTags: /`), as browsers accept.
+ // Repeat until nothing changes: removing one element can join the text
+ // around it into another (`ipt>`).
+ let previous;
+ do {
+ previous = cleaned;
+ cleaned = cleaned.replace(/<(script|style|iframe)\b[\s\S]*?<\/\1\b[^>]*>/gi, '');
+ } while (cleaned !== previous);
+ // Then an unclosed script or style, to the end of the text.
+ cleaned = cleaned.replace(/<(script|style)\b[^>]*>[\s\S]*$/gi, '');
// IPC data is rendered through React JSX which auto-escapes, so entity encoding
// is unnecessary. The previous code corrupted user text like "size < 10MB",
@@ -160,8 +163,29 @@ function createIpcSanitizer({ log }) {
// Prose that mentions a Windows path ("What is in D:\Docs?") matches the
// path heuristic and used to be blanked before it left the renderer. Exact
// names only; every other key keeps the heuristic, and a key containing
- // "path" or "file" always wins.
- const FREE_TEXT_KEYS = new Set(['query', 'description', 'text', 'message', 'note']);
+ // "path" or "file" always wins. Matched on key.toLowerCase(), so entries
+ // are lowercase.
+ //
+ // The settings prose fields (organization and persona guidance, persona
+ // label) were blanked when they named a path and also held `?`, `*` or
+ // `..`; an empty persona guidance then dropped the whole persona in main.
+ // Exclusion glob lists (settings `downloadsTriageExclusions`, triage
+ // `exclusionGlobs`) hold `\` and `*` by design; a blanked entry failed the
+ // settings schema (min length 1), so every later save failed. Main
+ // re-validates all of these (sanitizeCustomPersonas, sanitizeExclusionGlobs).
+ const FREE_TEXT_KEYS = new Set([
+ 'query',
+ 'description',
+ 'text',
+ 'message',
+ 'note',
+ 'organizationcustomguidance',
+ 'chatpersonacustomguidance',
+ 'guidance',
+ 'label',
+ 'downloadstriageexclusions',
+ 'exclusionglobs'
+ ]);
/**
* @param {any} obj
diff --git a/src/preload/ipcValidator.js b/src/preload/ipcValidator.js
index d422c2ee..bd7ada45 100644
--- a/src/preload/ipcValidator.js
+++ b/src/preload/ipcValidator.js
@@ -16,6 +16,7 @@ function createIpcValidator({ log: _log } = {}) {
const MAX_ARRAY_LENGTH = 50000;
const MAX_OBJECT_KEYS = 5000;
const MAX_STRING_LENGTH = 500000; // ~500KB per string payload
+ const PAYLOAD_TOO_LARGE = 'payload-too-large';
/**
* Validate event source to prevent spoofing.
@@ -136,7 +137,15 @@ function createIpcValidator({ log: _log } = {}) {
case 'smart-folders:get-custom':
return [];
case 'analysis-history:get':
- return [];
+ // Not []: pagination reads an empty page as the end of the
+ // history, so a page of long transcripts made the whole list look
+ // empty. The reason lets fetchAnalysisHistoryPages retry the same
+ // offset with a smaller page.
+ return {
+ success: false,
+ error: 'IPC response rejected: payload exceeded safety limits',
+ reason: PAYLOAD_TOO_LARGE
+ };
case 'undo-redo:get-history':
return [];
case 'undo-redo:get-state':
diff --git a/src/renderer/components/AnalysisDetails.jsx b/src/renderer/components/AnalysisDetails.jsx
index 543854aa..b4c0006c 100644
--- a/src/renderer/components/AnalysisDetails.jsx
+++ b/src/renderer/components/AnalysisDetails.jsx
@@ -148,7 +148,7 @@ const AnalysisDetails = memo(function AnalysisDetails({
if (result?.success) {
setExportStatus(
result?.truncated
- ? `Saved ${format.toUpperCase()} — long recording: transcript was truncated at 1,000 segments`
+ ? `Saved ${format.toUpperCase()}. Long recording, so the transcript was cut off at 1,000 segments.`
: `Saved ${format.toUpperCase()}`
);
} else if (!result?.canceled) {
diff --git a/src/renderer/components/AnalysisHistoryModal.jsx b/src/renderer/components/AnalysisHistoryModal.jsx
index 134450e8..206b3cea 100644
--- a/src/renderer/components/AnalysisHistoryModal.jsx
+++ b/src/renderer/components/AnalysisHistoryModal.jsx
@@ -150,10 +150,10 @@ function AnalysisHistoryModal({ onClose, analysisStats, setAnalysisStats }) {
if (actual && typeof actual === 'string') {
const normalized = actual.replace(/\\+/g, '/');
const segments = normalized.split('/').filter(Boolean);
+ // organization.actual is the moved file's path, so the folder is its
+ // parent. Guessing by extension named LICENSE or Makefile as the folder.
if (segments.length > 1) {
- const last = segments[segments.length - 1];
- const isFile = /\.[A-Za-z0-9]+$/.test(last);
- const folder = isFile ? segments[segments.length - 2] : last;
+ const folder = segments[segments.length - 2];
if (folder) return folder;
}
}
diff --git a/src/renderer/components/ErrorBoundary.jsx b/src/renderer/components/ErrorBoundary.jsx
index 33b50f39..d6b8eab9 100644
--- a/src/renderer/components/ErrorBoundary.jsx
+++ b/src/renderer/components/ErrorBoundary.jsx
@@ -27,6 +27,9 @@ class ErrorBoundaryCore extends React.Component {
chunkReloadExhausted: false
};
this.resetTimeoutId = null;
+ // Runs after an automatic reset; if the children stay up this long, the
+ // earlier failures are forgotten and errorCount starts over.
+ this.stableTimeoutId = null;
this.handleReset = this.handleReset.bind(this);
this.handleNavigateHome = this.handleNavigateHome.bind(this);
this.handleReload = this.handleReload.bind(this);
@@ -48,6 +51,8 @@ class ErrorBoundaryCore extends React.Component {
timestamp: new Date().toISOString()
});
+ this.clearStableTimer();
+
this.setState(
(prevState) => ({
errorInfo,
@@ -76,6 +81,14 @@ class ErrorBoundaryCore extends React.Component {
clearTimeout(this.resetTimeoutId);
this.resetTimeoutId = null;
}
+ this.clearStableTimer();
+ }
+
+ clearStableTimer() {
+ if (this.stableTimeoutId) {
+ clearTimeout(this.stableTimeoutId);
+ this.stableTimeoutId = null;
+ }
}
handleChunkLoadError(error, context) {
@@ -158,15 +171,42 @@ class ErrorBoundaryCore extends React.Component {
clearTimeout(this.resetTimeoutId);
}
this.resetTimeoutId = setTimeout(() => {
- this.handleReset();
+ this.handleAutoReset(delay);
}, delay);
}
+ // Unlike a manual reset, keeps errorCount: an error that recurs right after
+ // the remount must count toward the retry cap and the "Multiple errors"
+ // hint, or a child that always throws is remounted forever.
+ handleAutoReset(delay) {
+ this.resetTimeoutId = null;
+ this.clearStableTimer();
+ this.stableTimeoutId = setTimeout(() => {
+ this.stableTimeoutId = null;
+ if (!this.state.hasError) {
+ this.setState({ errorCount: 0 });
+ }
+ }, delay);
+
+ this.setState((prevState) => ({
+ hasError: false,
+ error: null,
+ errorInfo: null,
+ resetKey: prevState.resetKey + 1,
+ chunkReloadExhausted: false
+ }));
+
+ if (this.props.onReset) {
+ this.props.onReset();
+ }
+ }
+
handleReset() {
if (this.resetTimeoutId) {
clearTimeout(this.resetTimeoutId);
this.resetTimeoutId = null;
}
+ this.clearStableTimer();
this.setState((prevState) => ({
hasError: false,
@@ -183,6 +223,11 @@ class ErrorBoundaryCore extends React.Component {
}
handleNavigateHome() {
+ if (this.resetTimeoutId) {
+ clearTimeout(this.resetTimeoutId);
+ this.resetTimeoutId = null;
+ }
+ this.clearStableTimer();
this.setState((prevState) => ({
hasError: false,
error: null,
@@ -261,7 +306,7 @@ class ErrorBoundaryCore extends React.Component {
{needsRestart
- ? 'StratoSort was updated while it was running. Please quit and reopen the app to finish updating — reloading won’t resolve this.'
+ ? 'StratoSort was updated while it was running. Quit and reopen the app to finish updating. Reloading won’t fix this.'
: isChunk
? 'App assets failed to load. This usually happens after an update.'
: 'The application encountered an unexpected error.'}
@@ -271,7 +316,7 @@ class ErrorBoundaryCore extends React.Component {
{errorCount > 2 && !needsRestart && (
- Multiple errors detected. Consider reloading the application.
+ Multiple errors detected. Try reloading the app.
)}
@@ -310,7 +355,7 @@ class ErrorBoundaryCore extends React.Component {
- If this problem persists, please check your settings or contact support.
+ If this keeps happening, check your settings or contact support.
@@ -344,7 +389,7 @@ class ErrorBoundaryCore extends React.Component {
{isChunk && (
{needsRestart
- ? 'StratoSort was updated while running. Please quit and reopen the app to finish updating — reloading won’t help.'
+ ? 'StratoSort was updated while running. Quit and reopen the app to finish updating. Reloading won’t help.'
: 'This looks like an app asset mismatch. Reloading usually fixes it after an update.'}
)}
diff --git a/src/renderer/components/ModelSetupWizard.jsx b/src/renderer/components/ModelSetupWizard.jsx
index fc047b5d..6a5400b0 100644
--- a/src/renderer/components/ModelSetupWizard.jsx
+++ b/src/renderer/components/ModelSetupWizard.jsx
@@ -38,13 +38,17 @@ const STEP_TITLES = {
downloading: 'Download',
complete: 'Finish'
};
-const DOWNLOADS_STOPPED_MESSAGE = 'Required model downloads stopped. Please retry downloads.';
+const DOWNLOADS_STOPPED_MESSAGE = 'Required model downloads stopped. Retry the downloads.';
// Main says "started" before the download is in its status list (it checks
// disk space and any partial file first), so for this long after a request an
// empty list does not mean the download stopped.
const DOWNLOAD_START_GRACE_MS = 3000;
const PROJECTOR_MISSING_MESSAGE =
'The model downloaded, but its image projector file did not download. Images cannot be analyzed until it does. Retry to fetch it.';
+// The vision model is optional: when it does not install, setup can still
+// finish on the required models, and this warning says what is missing.
+const VISION_NOT_INSTALLED_MESSAGE =
+ 'The image analysis model is not installed, so images cannot be analyzed yet. Documents are analyzed as usual, and you can download it later from Settings.';
const CHECKING_STATUS_MESSAGES = [
'Detecting available local models...',
'Checking active background downloads...',
@@ -471,7 +475,7 @@ function ModelSetupWizardBody({ onComplete, onSkip, onDismiss, onStepChange }) {
if (!hasLlamaApi) {
if (!isMountedRef.current) return;
applyFallbackSelection();
- setInitError('AI engine is still starting. Please try again in a moment.');
+ setInitError('AI engine is still starting. Try again in a moment.');
setStep('select');
setIsRefreshing(false);
return;
@@ -653,7 +657,7 @@ function ModelSetupWizardBody({ onComplete, onSkip, onDismiss, onStepChange }) {
if (step === 'checking' && !pendingEmbeddingSwitch) {
const timer = setTimeout(() => {
if (isMountedRef.current) {
- setInitError('AI system check timed out. Please select models manually.');
+ setInitError('AI system check timed out. Select models manually.');
setStep('select');
setIsRefreshing(false);
}
@@ -917,6 +921,38 @@ function ModelSetupWizardBody({ onComplete, onSkip, onDismiss, onStepChange }) {
return;
}
+ // Only the optional vision model is missing and nothing runs any more:
+ // its download stopped. A row still showing "downloading" would keep
+ // the step waiting forever with "Continue with limited AI" as the only
+ // exit (which skips the chosen profile), so mark it failed. The step
+ // then offers Continue (required models are in) next to Retry.
+ if (
+ requiredMissing.length === 0 &&
+ selectedMissing.length > 0 &&
+ hasReliableDownloadStatus &&
+ activeDownloads.length === 0 &&
+ !downloadWasJustRequested()
+ ) {
+ setDownloadState((prev) => {
+ let changed = false;
+ const next = { ...prev };
+ selectedMissing.forEach((name) => {
+ const status = prev[name]?.status;
+ if (status === 'failed' || status === 'cancelled') return;
+ changed = true;
+ next[name] = {
+ ...(prev[name] || {}),
+ status: 'failed',
+ speedBps: 0,
+ etaSeconds: 0,
+ error: prev[name]?.error || 'The download stopped before it finished.'
+ };
+ });
+ return changed ? next : prev;
+ });
+ return;
+ }
+
if (
requiredMissing.length > 0 &&
hasReliableDownloadStatus &&
@@ -1072,6 +1108,9 @@ function ModelSetupWizardBody({ onComplete, onSkip, onDismiss, onStepChange }) {
const selectedMissing = Object.values(selectedModels)
.filter(Boolean)
.filter((name) => !nextAvailable.has(name));
+ const requiredMissing = [selectedModels.embedding, selectedModels.text]
+ .filter(Boolean)
+ .filter((name) => !nextAvailable.has(name));
let configApplied = true;
if (selectedMissing.length === 0) {
@@ -1084,11 +1123,15 @@ function ModelSetupWizardBody({ onComplete, onSkip, onDismiss, onStepChange }) {
// An empty status list right after main acknowledged a request only
// means the download is not registered yet; with a failed engine the
// model list cannot say what is missing either. The poll takes over.
+ // With embedding + text installed, only the optional vision request
+ // failed: stay on the download step, where its row reads Failed and
+ // Continue / Retry are offered, instead of dropping back to Choose.
const statusSaysNothingRuns =
hasReliableDownloadStatus &&
activeDownloads.length === 0 &&
acknowledged === 0 &&
- !modelListError;
+ !modelListError &&
+ requiredMissing.length > 0;
setStep(statusSaysNothingRuns ? 'select' : 'downloading');
}
}
@@ -1429,8 +1472,20 @@ function ModelSetupWizardBody({ onComplete, onSkip, onDismiss, onStepChange }) {
const status = downloadState[filename]?.status || 'downloading';
return !['ready', 'complete', 'failed', 'cancelled'].includes(status);
});
+ // The vision model is optional. With embedding + text ready and nothing
+ // still downloading, a failed or cancelled vision download is a warning,
+ // and "Continue" still saves the chosen profile and finishes setup.
+ const isReadyStatus = (filename) =>
+ ['ready', 'complete'].includes(downloadState[filename]?.status);
+ const requiredComplete = [selectedModels.embedding, selectedModels.text]
+ .filter(Boolean)
+ .every(isReadyStatus);
+ const canContinue = allComplete || (requiredComplete && !hasActiveDownload);
+ const optionalVisionStopped =
+ Boolean(selectedModels.vision) &&
+ ['failed', 'cancelled'].includes(downloadState[selectedModels.vision]?.status);
const leaveKeepsDownloading =
- !allComplete && hasActiveDownload && typeof onDismiss === 'function';
+ !canContinue && hasActiveDownload && typeof onDismiss === 'function';
return (
@@ -1454,6 +1509,12 @@ function ModelSetupWizardBody({ onComplete, onSkip, onDismiss, onStepChange }) {
)}
+ {requiredComplete && optionalVisionStopped && !hasActiveDownload && (
+
+ {VISION_NOT_INSTALLED_MESSAGE}
+
+ )}
+
)}
diff --git a/src/renderer/components/PhaseErrorBoundary.jsx b/src/renderer/components/PhaseErrorBoundary.jsx
index 13a7e9d4..de7b2a5a 100644
--- a/src/renderer/components/PhaseErrorBoundary.jsx
+++ b/src/renderer/components/PhaseErrorBoundary.jsx
@@ -6,6 +6,7 @@ import { resetUi } from '../store/slices/uiSlice';
import { resetFilesState } from '../store/slices/filesSlice';
import { resetAnalysisState, resetToSafeState } from '../store/slices/analysisSlice';
import { ErrorBoundaryCore } from './ErrorBoundary';
+import { useOptionalAnalysisRun } from '../phases/discover/AnalysisRunProvider';
const logger = createLogger('PhaseErrorBoundary');
/**
@@ -18,8 +19,18 @@ const logger = createLogger('PhaseErrorBoundary');
*/
function PhaseErrorBoundary({ children, phaseName }) {
const dispatch = useAppDispatch();
+ const analysisRun = useOptionalAnalysisRun();
const handleNavigateHome = () => {
+ // Clearing Redux alone leaves a running analysis alive with no progress
+ // card or Stop button, and the next files queue behind it.
+ try {
+ analysisRun?.resetRun?.('Go to Home', { discard: true });
+ } catch (error) {
+ logger.warn('Could not stop the analysis run on Go to Home', {
+ error: error?.message
+ });
+ }
dispatch(resetUi());
dispatch(resetFilesState());
dispatch(resetAnalysisState());
diff --git a/src/renderer/components/SettingsPanel.jsx b/src/renderer/components/SettingsPanel.jsx
index 7ec12437..4d77a366 100644
--- a/src/renderer/components/SettingsPanel.jsx
+++ b/src/renderer/components/SettingsPanel.jsx
@@ -1388,7 +1388,7 @@ const SettingsPanel = React.memo(function SettingsPanel() {
title={`Save failed: ${lastSaveError}. Click to retry.`}
>
- Save failed — retry
+ Save failed. Retry
);
} else if (isSaving) {
@@ -1440,7 +1440,7 @@ const SettingsPanel = React.memo(function SettingsPanel() {
- Electron API not available. Please restart the application.
+ Electron API not available. Restart the application.
- Electron API not available. Please restart the application.
+ Electron API not available. Restart the application.
@@ -50,13 +56,19 @@ const VirtualizedFileRow = React.memo(function VirtualizedFileRow({ index, style
aria-pressed={isSelected}
className="flex min-w-0 flex-1 items-center gap-cozy text-left"
>
-
+ {/* Raw name so the icon still matches the extension; it is never shown as text. */}
+
@@ -95,7 +107,8 @@ VirtualizedFileRow.propTypes = {
selectedFiles: PropTypes.instanceOf(Set).isRequired,
handleToggleFile: PropTypes.func.isRequired,
openFile: PropTypes.func.isRequired,
- revealFile: PropTypes.func.isRequired
+ revealFile: PropTypes.func.isRequired,
+ redactPaths: PropTypes.bool.isRequired
}).isRequired
};
@@ -119,19 +132,25 @@ export default function TriageModal({
const [moveError, setMoveError] = useState('');
const { openFile, revealFile } = useFileActions(setMoveError);
const prevIsOpenRef = useRef(false);
- const containerRef = useRef(null);
+ const redactPaths = useSelector(selectRedactPaths);
+ // The container node lives in state (callback ref) rather than a ref read on
+ // [isOpen]: Modal mounts its children a render after isOpen flips and keeps
+ // them through the exit animation, so an isOpen-keyed effect saw a null node
+ // on open and observed the dying node on close, which then reported 0 height.
+ const [containerEl, setContainerEl] = useState(null);
const [listHeight, setListHeight] = useState(400);
useEffect(() => {
- if (!containerRef.current) return;
+ if (!containerEl || typeof ResizeObserver === 'undefined') return undefined;
const observer = new ResizeObserver((entries) => {
for (const entry of entries) {
- setListHeight(entry.contentRect.height);
+ // A detached node reports 0x0; keep the last real height instead.
+ if (entry.contentRect.height > 0) setListHeight(entry.contentRect.height);
}
});
- observer.observe(containerRef.current);
+ observer.observe(containerEl);
return () => observer.disconnect();
- }, [isOpen]);
+ }, [containerEl]);
useEffect(() => {
const wasOpen = prevIsOpenRef.current;
@@ -193,7 +212,7 @@ export default function TriageModal({
error: error?.message,
stack: error?.stack
});
- setMoveError(error?.message || 'Failed to move files. Please try again.');
+ setMoveError(error?.message || 'Failed to move files. Try again.');
} finally {
setIsMoving(false);
}
@@ -208,10 +227,11 @@ export default function TriageModal({
selectedFiles,
handleToggleFile,
openFile,
- revealFile
+ revealFile,
+ redactPaths
}
}),
- [files, selectedFiles, handleToggleFile, openFile, revealFile]
+ [files, selectedFiles, handleToggleFile, openFile, revealFile, redactPaths]
);
return (
@@ -284,7 +304,7 @@ export default function TriageModal({
{/* File List */}
-
+
{files.length > 0 ? (
{suggestion.displayName}
{suggestion.earlierCount > 0
? ` (${suggestion.earlierCount} analyzed earlier)`
- : ''}{' '}
- — want a Smart Folder for them?
+ : ''}
+ . Want a Smart Folder for them?
) : (
diff --git a/src/renderer/components/search/AtlasTabContent.jsx b/src/renderer/components/search/AtlasTabContent.jsx
index 3126cc63..8680b11a 100644
--- a/src/renderer/components/search/AtlasTabContent.jsx
+++ b/src/renderer/components/search/AtlasTabContent.jsx
@@ -179,7 +179,7 @@ function AtlasTabContent({ isActive, openFile, revealFile, setError, simpleMode
const api = /** @type {any} */ (window).electronAPI?.atlas;
if (!api?.getProjection) {
setStatus('error');
- setBothErrors('Atlas is unavailable — the projection service did not load.');
+ setBothErrors('Atlas is unavailable. The projection service did not load.');
return;
}
// Generation token: a newer load (e.g. a forced rebuild racing the
@@ -240,7 +240,7 @@ function AtlasTabContent({ isActive, openFile, revealFile, setError, simpleMode
} else if (pageSignature !== fitSignature) {
restarts += 1;
if (restarts > 3) {
- throw new Error('Atlas projection kept changing while loading — try again');
+ throw new Error('Atlas projection kept changing while loading. Try again.');
}
offset = 0;
total = 0;
@@ -1261,7 +1261,7 @@ function AtlasTabContent({ isActive, openFile, revealFile, setError, simpleMode
{status === 'rebuilding'
- ? 'Embeddings are rebuilding — the map will refresh shortly.'
+ ? 'Embeddings are rebuilding. The map will refresh shortly.'
: 'Projecting your library…'}
diff --git a/src/renderer/components/search/BridgeAnalysisModal.jsx b/src/renderer/components/search/BridgeAnalysisModal.jsx
index c65ef49d..d48e65c5 100644
--- a/src/renderer/components/search/BridgeAnalysisModal.jsx
+++ b/src/renderer/components/search/BridgeAnalysisModal.jsx
@@ -220,7 +220,7 @@ export default function BridgeAnalysisModal({
}
title={
selectedBridge.centroidOnly
- ? 'No concrete files to move — this bridge is a topical overlap only.'
+ ? 'No concrete files to move. This bridge is a topical overlap only.'
: `Move ${selectedBridge.bridgeFiles.length} bridge file${selectedBridge.bridgeFiles.length === 1 ? '' : 's'} into a folder of your choice.`
}
onClick={() =>
diff --git a/src/renderer/components/search/ChatPanel.jsx b/src/renderer/components/search/ChatPanel.jsx
index bb003091..b0b7e003 100644
--- a/src/renderer/components/search/ChatPanel.jsx
+++ b/src/renderer/components/search/ChatPanel.jsx
@@ -1064,8 +1064,7 @@ function ChatPanel({
>
{messages.length === 0 ? (
- Ask me anything about your documents — search by meaning, summarize, or explore
- connections.
+ Ask about your documents. You can search by meaning, summarize, or explore connections.
) : null}
diff --git a/src/renderer/components/search/ClusterNode.jsx b/src/renderer/components/search/ClusterNode.jsx
index 4516bc31..25ca66aa 100644
--- a/src/renderer/components/search/ClusterNode.jsx
+++ b/src/renderer/components/search/ClusterNode.jsx
@@ -316,10 +316,10 @@ const ClusterNode = memo(({ data, selected }) => {
style={{ margin: '-6px' }}
title={
confidence === 'high'
- ? 'High confidence — AI generated a descriptive label from file content'
+ ? 'High confidence: AI generated a descriptive label from file content'
: confidence === 'medium'
- ? 'Medium confidence — label derived from shared tags or categories'
- : 'Low confidence — label auto-generated from file count only'
+ ? 'Medium confidence: label derived from shared tags or categories'
+ : 'Low confidence: label auto-generated from file count only'
}
aria-label={`Cluster confidence: ${confidence}`}
/>
diff --git a/src/renderer/components/search/ComparisonTable.jsx b/src/renderer/components/search/ComparisonTable.jsx
index d2316d45..2b115376 100644
--- a/src/renderer/components/search/ComparisonTable.jsx
+++ b/src/renderer/components/search/ComparisonTable.jsx
@@ -81,8 +81,8 @@ export default function ComparisonTable({ documentAnswer, sources, onOpenSource
{onlyDoc
- ? `Only one document matched (${onlyDoc.name}). Comparison needs at least two — broaden the scope or try a less specific query.`
- : 'No documents matched. Comparison needs at least two — broaden the scope or try a less specific query.'}
+ ? `Only one document matched (${onlyDoc.name}). Comparison needs at least two. Broaden the scope or try a less specific query.`
+ : 'No documents matched. Comparison needs at least two. Broaden the scope or try a less specific query.'}
diff --git a/src/renderer/components/search/EmptyEmbeddingsBanner.jsx b/src/renderer/components/search/EmptyEmbeddingsBanner.jsx
index 08d635f5..e316b7da 100644
--- a/src/renderer/components/search/EmptyEmbeddingsBanner.jsx
+++ b/src/renderer/components/search/EmptyEmbeddingsBanner.jsx
@@ -57,7 +57,7 @@ function EmptyEmbeddingsBanner({
? `${mismatchDetails} Rebuild the search index to restore reliable semantic search.`
: `${mismatchDetails} Rebuild embeddings to restore reliable semantic search.`
: needsFileEmbeddingRebuild
- ? 'You already have analyzed files, but the embedding index is empty or incomplete. Run a file embedding rebuild from analysis history to restore full Knowledge OS coverage.'
+ ? 'You already have analyzed files, but the embedding index is empty or incomplete. Rebuild file embeddings from analysis history to restore full Knowledge OS coverage.'
: isManual
? simpleMode
? 'Knowledge OS search needs a local search index, but your settings are set to Manual only. Turn automatic indexing back on (Settings -> Embedding behavior), then rebuild to populate the index.'
diff --git a/src/renderer/components/search/EmptySearchState.jsx b/src/renderer/components/search/EmptySearchState.jsx
index 6114cbf0..acd6670b 100644
--- a/src/renderer/components/search/EmptySearchState.jsx
+++ b/src/renderer/components/search/EmptySearchState.jsx
@@ -87,7 +87,7 @@ const EmptySearchState = memo(function EmptySearchState({
tone="error"
size="lg"
title="Search is offline"
- description="The local AI engine or vector database is currently unavailable. Please check your model downloads in Settings or restart the app."
+ description="The local AI engine or vector database is currently unavailable. Check your model downloads in Settings or restart the app."
action={
onOpenSettings && (
- Topics with only 1 source may benefit from additional documents. Click any topic to
- explore it further.
+ Topics with only 1 source could use more documents. Click any topic to explore it
+ further.
diff --git a/src/renderer/components/search/GraphTabContent.jsx b/src/renderer/components/search/GraphTabContent.jsx
index a2fb3acb..ec9cdb43 100644
--- a/src/renderer/components/search/GraphTabContent.jsx
+++ b/src/renderer/components/search/GraphTabContent.jsx
@@ -244,7 +244,7 @@ export default function GraphTabContent({
tone="error"
size="lg"
title="Graph is offline"
- description="The local AI engine or vector database is currently unavailable. Please check your model downloads in Settings or restart the app."
+ description="The local AI engine or vector database is currently unavailable. Check your model downloads in Settings or restart the app."
action={
Open Settings
@@ -400,7 +400,7 @@ export default function GraphTabContent({
{bridge.targetLabel}
>
}
- description={`${Math.round((bridge.similarity || 0) * 100)}% related — files sit in different folders`}
+ description={`${Math.round((bridge.similarity || 0) * 100)}% related, but the files sit in different folders`}
verb="Highlight on graph"
onClick={() => {
setBridgeOverlayEnabled(true);
@@ -1382,7 +1382,7 @@ export default function GraphTabContent({
className="text-system-gray-500 max-w-md mb-8 leading-relaxed"
>
Your files are scattered across folders. Clustering reveals how they
- naturally belong together-even files you forgot you had. For a
+ naturally belong together, even files you forgot you had. For a
bird's-eye map of everything at once, the Atlas tab is a great
companion view.
@@ -2575,9 +2575,10 @@ export default function GraphTabContent({
Clusters are groups of related files. Solid lines connect similar
- files; dashed lines between clusters mean topics overlap — a count
- shows files that belong to both groups. Hover or click a line's
- label for why it's there; click again to pin the details open.
+ files. Dashed lines between clusters mean topics overlap, and a
+ count shows how many files belong to both groups. Hover or click a
+ line's label for why it's there; click again to pin the
+ details open.
dispatch(setGraphLegendHintDismissed(true))}
diff --git a/src/renderer/components/search/GraphTour.jsx b/src/renderer/components/search/GraphTour.jsx
index 1987f6de..1f6249aa 100644
--- a/src/renderer/components/search/GraphTour.jsx
+++ b/src/renderer/components/search/GraphTour.jsx
@@ -44,7 +44,7 @@ const TOUR_STEPS = [
icon: GitBranch,
title: 'Topic bridges',
content:
- 'Dashed lines between clusters mean your topics overlap. When the label shows a number, that many files sit in both groups — useful for shared clients, projects, or duplicates across folders. Hover or click the label for details.',
+ 'Dashed lines between clusters mean your topics overlap. When the label shows a number, that many files sit in both groups (useful for shared clients, projects, or duplicates across folders). Hover or click the label for details.',
position: 'center'
},
{
@@ -60,7 +60,7 @@ const TOUR_STEPS = [
icon: Orbit,
title: 'The Atlas, a companion view',
content:
- 'Alongside Relate there is the Atlas — a zoomable map of every file where nearby dots are similar. Reach for the Atlas when you want the whole library at a glance or to lasso-select for bulk moves; come back to Relate to follow the links between specific files.',
+ 'Alongside Relate there’s the Atlas, a zoomable map of every file where nearby dots are similar. Use the Atlas when you want the whole library at a glance or to lasso-select for bulk moves. Come back to Relate to follow the links between specific files.',
position: 'center'
}
];
diff --git a/src/renderer/components/search/SearchAutocomplete.jsx b/src/renderer/components/search/SearchAutocomplete.jsx
index 2c21d91e..8ed24e4b 100644
--- a/src/renderer/components/search/SearchAutocomplete.jsx
+++ b/src/renderer/components/search/SearchAutocomplete.jsx
@@ -9,6 +9,18 @@ import { getScrollBehavior } from '../../utils/motionPreferences';
const RECENT_SEARCHES_KEY = 'stratosort-recent-searches';
const MAX_RECENT_SEARCHES = 10;
const MAX_SUGGESTIONS = 5;
+// Fired on window after the stored list changes, so a mounted autocomplete
+// picks up searches recorded elsewhere (useSearchTab) instead of keeping its
+// mount-time copy and later overwriting them.
+const RECENT_SEARCHES_CHANGED_EVENT = 'stratosort-recent-searches-changed';
+
+function notifyRecentSearchesChanged() {
+ try {
+ window.dispatchEvent(new Event(RECENT_SEARCHES_CHANGED_EVENT));
+ } catch {
+ // Ignore: no window outside the renderer
+ }
+}
const isMac =
navigator.userAgentData?.platform === 'macOS' || /Mac|iPod|iPhone|iPad/.test(navigator.userAgent);
@@ -31,6 +43,7 @@ function saveRecentSearches(searches) {
} catch {
// Ignore storage errors
}
+ notifyRecentSearchesChanged();
}
export function addToRecentSearches(query) {
@@ -51,6 +64,7 @@ export function clearRecentSearches() {
} catch {
// Ignore
}
+ notifyRecentSearchesChanged();
}
const SearchAutocomplete = memo(
@@ -83,7 +97,10 @@ const SearchAutocomplete = memo(
);
useEffect(() => {
- setRecentSearches(loadRecentSearches());
+ const reload = () => setRecentSearches(loadRecentSearches());
+ reload();
+ window.addEventListener(RECENT_SEARCHES_CHANGED_EVENT, reload);
+ return () => window.removeEventListener(RECENT_SEARCHES_CHANGED_EVENT, reload);
}, []);
useEffect(() => {
@@ -326,7 +343,9 @@ const SearchAutocomplete = memo(
const handleClearRecent = (e, searchToRemove) => {
e.stopPropagation();
- const updated = recentSearches.filter((s) => s !== searchToRemove);
+ // Filter what is stored now, not this component's copy, so searches
+ // recorded since the last reload are not erased.
+ const updated = loadRecentSearches().filter((s) => s !== searchToRemove);
setRecentSearches(updated);
saveRecentSearches(updated);
};
diff --git a/src/renderer/components/search/SearchTabContent.jsx b/src/renderer/components/search/SearchTabContent.jsx
index c301dd84..ee388361 100644
--- a/src/renderer/components/search/SearchTabContent.jsx
+++ b/src/renderer/components/search/SearchTabContent.jsx
@@ -30,9 +30,7 @@ import SearchAutocomplete from './SearchAutocomplete';
import SearchDiagnosticsBanner from './SearchDiagnosticsBanner';
import SearchModeBanner from './SearchModeBanner';
import VirtualizedSearchResults from './VirtualizedSearchResults';
-
-// Cap rows per category in grouped view (full counts still shown in header)
-const GROUPED_VIEW_MAX_PER_CATEGORY = 50;
+import { GROUPED_VIEW_MAX_PER_CATEGORY } from './hooks/useSearchTab';
export default function SearchTabContent({
search,
@@ -70,6 +68,9 @@ export default function SearchTabContent({
isSearching,
queryMeta,
searchMeta,
+ exactSearch,
+ searchExactly,
+ searchWithCorrection,
bulkSelectedIds,
focusedResultIndex,
viewMode,
@@ -82,6 +83,25 @@ export default function SearchTabContent({
resultIdToIndex
} = search;
+ // What the spelling notice shows: the corrected query with the typed one
+ // on offer, or (after "search for the typed query instead") the reverse.
+ let correctionNotice = null;
+ if (exactSearch?.corrected) {
+ correctionNotice = {
+ shown: exactSearch.query,
+ asTyped: true,
+ alternative: exactSearch.corrected,
+ onSwitch: searchWithCorrection
+ };
+ } else if (queryMeta?.corrections?.length > 0) {
+ correctionNotice = {
+ shown: queryMeta.corrected || queryMeta.corrections.map((c) => c.corrected).join(', '),
+ asTyped: false,
+ alternative: debouncedQuery,
+ onSwitch: searchExactly
+ };
+ }
+
return (
)}
- {/* Query correction feedback - "Did you mean?" */}
- {queryMeta?.corrections?.length > 0 && searchResults.length > 0 && (
+ {/* Spelling correction notice, with a way to search for exactly what
+ was typed (and back). Both states render the same elements so the
+ button keeps focus when it is pressed. */}
+ {correctionNotice && searchResults.length > 0 && (
)}
diff --git a/src/renderer/components/search/SimilarityEdge.jsx b/src/renderer/components/search/SimilarityEdge.jsx
index 9af169b9..152400c7 100644
--- a/src/renderer/components/search/SimilarityEdge.jsx
+++ b/src/renderer/components/search/SimilarityEdge.jsx
@@ -555,7 +555,7 @@ const SimilarityEdge = memo(
{data?.bridgeCount > 0
- ? 'These documents sit in both topic groups — handy for shared clients, projects, or cross-folder duplicates.'
+ ? 'These documents sit in both topic groups (handy for shared clients, projects, or cross-folder duplicates).'
: 'These topic groups overlap by meaning, even when no single file spans both.'}
- No analyzed files yet — analyze files to build your timeline.
+ No analyzed files yet. Analyze files to build your timeline.
)}
diff --git a/src/renderer/components/search/UnifiedSearchModal.jsx b/src/renderer/components/search/UnifiedSearchModal.jsx
index ef583e10..3981f6e7 100644
--- a/src/renderer/components/search/UnifiedSearchModal.jsx
+++ b/src/renderer/components/search/UnifiedSearchModal.jsx
@@ -184,6 +184,7 @@ export default function UnifiedSearchModal({
focusedResultIndex,
setFocusedResultIndex,
viewMode,
+ navigableResults,
selectedSearchResultPath,
triggerSearchRefresh,
resetSearchState
@@ -1021,10 +1022,11 @@ export default function UnifiedSearchModal({
// Keyboard Shortcuts
// ============================================================================
- // Reset focused index when search results change
+ // Reset focused index when search results change, or when the view mode
+ // changes, since the index points into the order on screen.
useEffect(() => {
setFocusedResultIndex(-1);
- }, [searchResults, setFocusedResultIndex]);
+ }, [searchResults, viewMode, setFocusedResultIndex]);
// Scroll focused result into view
useEffect(() => {
@@ -1135,13 +1137,15 @@ export default function UnifiedSearchModal({
const autocompleteOpen = document.querySelector('[role="listbox"]');
if (autocompleteOpen) return; // Let autocomplete handle arrow keys
+ // Step through the rows in on-screen order (grouped view reorders
+ // and caps them), not the flat result order.
if (e.key === 'ArrowDown') {
e.preventDefault();
setFocusedResultIndex((prev) => {
- const next = Math.min(prev + 1, searchResults.length - 1);
+ const next = Math.min(prev + 1, navigableResults.length - 1);
// Also select when navigating
- if (searchResults[next]) {
- setSelectedSearchId(searchResults[next].id);
+ if (navigableResults[next]) {
+ setSelectedSearchId(navigableResults[next].id);
}
return next;
});
@@ -1151,8 +1155,8 @@ export default function UnifiedSearchModal({
setFocusedResultIndex((prev) => {
const next = Math.max(prev - 1, -1);
// Select result or clear selection when at -1
- if (next >= 0 && searchResults[next]) {
- setSelectedSearchId(searchResults[next].id);
+ if (next >= 0 && navigableResults[next]) {
+ setSelectedSearchId(navigableResults[next].id);
} else if (next === -1) {
setSelectedSearchId(null); // Clear selection when defocusing
}
@@ -1161,7 +1165,7 @@ export default function UnifiedSearchModal({
}
// Enter to open focused result
if (e.key === 'Enter' && focusedResultIndex >= 0 && !e.ctrlKey && !e.metaKey) {
- const result = searchResults[focusedResultIndex];
+ const result = navigableResults[focusedResultIndex];
const resultPath = getMetadataPath(result, result?.id);
if (resultPath) {
e.preventDefault();
@@ -1221,6 +1225,7 @@ export default function UnifiedSearchModal({
selectedNodeId,
nodes.length,
searchResults,
+ navigableResults,
focusedResultIndex,
openFile,
graphViewEnabled,
@@ -1681,7 +1686,7 @@ export default function UnifiedSearchModal({
}}
icon={Orbit}
label="Atlas"
- tooltip="See your whole library as a map — nearby files are similar"
+ tooltip="See your whole library as a map where nearby files are similar"
/>
)}
diff --git a/src/renderer/components/search/hooks/useChatTab.js b/src/renderer/components/search/hooks/useChatTab.js
index f9e9a710..99c56b2e 100644
--- a/src/renderer/components/search/hooks/useChatTab.js
+++ b/src/renderer/components/search/hooks/useChatTab.js
@@ -160,7 +160,7 @@ export function useChatTab({ isOpen, searchResults, defaultTopK, openFile }) {
const trimmed = typeof text === 'string' ? text.trim() : '';
if (!trimmed) return false;
if (chatInFlightRef.current) {
- setChatWarning('Please wait for the current response to finish.');
+ setChatWarning('Wait for the current response to finish.');
return false;
}
@@ -279,7 +279,7 @@ export function useChatTab({ isOpen, searchResults, defaultTopK, openFile }) {
streamingFlushIntervalRef.current = null;
pendingStreamChunkRef.current = '';
logger.warn('[KnowledgeOS] Chat stream timed out — no activity from main process');
- setChatError('The response timed out. Please try again.');
+ setChatError('The response timed out. Try again.');
setChatStatus('');
setChatWarning('');
setChatMessages((prev) => {
@@ -514,7 +514,7 @@ export function useChatTab({ isOpen, searchResults, defaultTopK, openFile }) {
logger.debug('[UnifiedSearchModal] Failed to save chat response mode', {
error: err?.message || String(err)
});
- setChatWarning('Failed to save chat response mode. Please try again.');
+ setChatWarning('Failed to save chat response mode. Try again.');
});
}, []);
@@ -528,7 +528,7 @@ export function useChatTab({ isOpen, searchResults, defaultTopK, openFile }) {
logger.debug('[UnifiedSearchModal] Failed to save chat persona', {
error: err?.message || String(err)
});
- setChatWarning('Failed to save chat persona. Please try again.');
+ setChatWarning('Failed to save chat persona. Try again.');
});
},
[savedCustomPersonas]
@@ -663,7 +663,7 @@ export function useChatTab({ isOpen, searchResults, defaultTopK, openFile }) {
}
} catch (e) {
logger.error('Failed to resolve scope files', e);
- setChatWarning('Could not check those files against the index. Please try again.');
+ setChatWarning('Could not check those files against the index. Try again.');
}
}, []);
diff --git a/src/renderer/components/search/hooks/useGraphTab.js b/src/renderer/components/search/hooks/useGraphTab.js
index f11473e2..812bdd3b 100644
--- a/src/renderer/components/search/hooks/useGraphTab.js
+++ b/src/renderer/components/search/hooks/useGraphTab.js
@@ -1073,7 +1073,7 @@ export function useGraphTab(
const handleClearFocus = useCallback(() => {
setFocusNodeId(null);
setSearchWithinScope(null);
- setGraphStatus('Focus cleared - showing all nodes');
+ setGraphStatus('Focus cleared. Showing all nodes.');
}, []);
const handleExpandAllClusters = useCallback(async () => {
@@ -2049,7 +2049,8 @@ export function useGraphTab(
const end = cluster?.timeRange?.end;
const startLabel = formatDateLabel(start);
const endLabel = formatDateLabel(end);
- if (startLabel && endLabel && startLabel !== endLabel) return `${startLabel} – ${endLabel}`;
+ if (startLabel && endLabel && startLabel !== endLabel)
+ return `${startLabel} to ${endLabel}`;
if (endLabel) return endLabel;
return fallback;
}
@@ -4495,10 +4496,21 @@ export function useGraphTab(
logger.warn('Some duplicates could not be trashed', {
failed: result.failed
});
- setError(
- `Trashed ${trashedPaths.length} of ${filesToDelete.length}. ` +
- `${result.failed.length} failed — see logs for details.`
- );
+ const onShare = result.failed.filter(
+ (/** @type {any} */ f) => f?.code === 'NETWORK_NO_RECYCLE_BIN'
+ ).length;
+ const otherFailed = result.failed.length - onShare;
+ const parts = [`Trashed ${trashedPaths.length} of ${filesToDelete.length}.`];
+ if (onShare > 0) {
+ parts.push(
+ `Left ${onShare} on a network drive, where Windows has no Recycle Bin. ` +
+ 'Delete those yourself if you are sure.'
+ );
+ }
+ if (otherFailed > 0) {
+ parts.push(`${otherFailed} failed. See the logs for details.`);
+ }
+ setError(parts.join(' '));
}
// Remove successfully-trashed file nodes from the live graph.
diff --git a/src/renderer/components/search/hooks/useSearchTab.js b/src/renderer/components/search/hooks/useSearchTab.js
index 46d0899a..dd9c4fb6 100644
--- a/src/renderer/components/search/hooks/useSearchTab.js
+++ b/src/renderer/components/search/hooks/useSearchTab.js
@@ -29,6 +29,9 @@ import {
const logger = createLogger('useSearchTab');
+// Cap rows per category in grouped view (full counts still shown in header)
+export const GROUPED_VIEW_MAX_PER_CATEGORY = 50;
+
const ENABLE_SEARCH_TRACE_LOGS = process.env.NODE_ENV === 'development';
/** Per-renderer sequence for the abortKey tagging each search-tab invoke. */
@@ -84,6 +87,17 @@ export function useSearchTab({ isOpen, activeTab, defaultTopK, error, setError }
const [searchRefreshTrigger, setSearchRefreshTrigger] = useState(0);
const [focusedResultIndex, setFocusedResultIndex] = useState(-1);
const [viewMode, setViewMode] = useState('all'); // 'all' or 'grouped'
+ // Query the user chose to search exactly as typed (spelling correction
+ // off), with the corrected text it replaced so the notice can offer it back.
+ const [exactSearchState, setExactSearchState] = useState(
+ /** @type {{ query: string, corrected: string } | null} */ (null)
+ );
+
+ // Only the query it was chosen for is searched exactly; any other query
+ // gets spelling correction again.
+ const exactSearch =
+ exactSearchState && exactSearchState.query === debouncedQuery ? exactSearchState : null;
+ const exactQuery = exactSearch?.query ?? null;
const lastSearchRef = useRef(0);
const searchRequestCounterRef = useRef(0);
@@ -170,7 +184,7 @@ export function useSearchTab({ isOpen, activeTab, defaultTopK, error, setError }
const searchPromise = window.electronAPI?.embeddings?.search?.(q, {
topK: defaultTopK,
mode: 'hybrid',
- correctSpelling: true,
+ correctSpelling: q !== exactQuery,
expandSynonyms: true,
abortKey
});
@@ -199,9 +213,7 @@ export function useSearchTab({ isOpen, activeTab, defaultTopK, error, setError }
if (invokeInFlight && !cancelled && lastSearchRef.current === requestId) {
abortInFlightSearch(abortKey, 'search-timeout');
}
- reject(
- new Error('Search timed out. The index may still be loading — please try again.')
- );
+ reject(new Error('Search timed out. The index may still be loading. Try again.'));
}, TIMEOUTS.SEMANTIC_QUERY);
})
]);
@@ -276,7 +288,22 @@ export function useSearchTab({ isOpen, activeTab, defaultTopK, error, setError }
};
// searchRefreshTrigger triggers re-search when files are moved/deleted
// eslint-disable-next-line react-hooks/exhaustive-deps -- setError is a stable setState-backed callback
- }, [debouncedQuery, isOpen, defaultTopK, activeTab, searchRefreshTrigger]);
+ }, [debouncedQuery, isOpen, defaultTopK, activeTab, searchRefreshTrigger, exactQuery]);
+
+ // "Search for instead": re-run the current query without spelling
+ // correction.
+ const searchExactly = useCallback(() => {
+ if (!debouncedQuery || !queryMeta?.corrections?.length) return;
+ setExactSearchState({
+ query: debouncedQuery,
+ corrected: typeof queryMeta.corrected === 'string' ? queryMeta.corrected : ''
+ });
+ }, [debouncedQuery, queryMeta]);
+
+ // Undo searchExactly: search the current query with correction again.
+ const searchWithCorrection = useCallback(() => {
+ setExactSearchState(null);
+ }, []);
const searchStatusLabel = useMemo(() => {
if (isSearching) return 'Searching...';
@@ -310,12 +337,24 @@ export function useSearchTab({ isOpen, activeTab, defaultTopK, error, setError }
return sortedGroups;
}, [searchResults]);
- // Pre-compute ID-to-index map for O(1) lookup in grouped view
+ // Results in the order the list renders them. Grouped view shows them by
+ // category, each capped, so keyboard focus (focusedResultIndex) indexes this
+ // list: the highlight follows the rows on screen and never lands on a
+ // result the cap hides.
+ const navigableResults = useMemo(() => {
+ if (viewMode !== 'grouped') return searchResults;
+ return Object.values(groupedResults).flatMap((results) =>
+ results.slice(0, GROUPED_VIEW_MAX_PER_CATEGORY)
+ );
+ }, [viewMode, searchResults, groupedResults]);
+
+ // Pre-compute ID-to-position map (into navigableResults) for O(1) lookup in
+ // grouped view
const resultIdToIndex = useMemo(() => {
const map = new Map();
- searchResults.forEach((r, i) => map.set(r.id, i));
+ navigableResults.forEach((r, i) => map.set(r.id, i));
return map;
- }, [searchResults]);
+ }, [navigableResults]);
// Reset to a clean slate for a fresh open (called from the modal's
// open-reset effect so the reset ordering stays exactly as before).
@@ -328,6 +367,7 @@ export function useSearchTab({ isOpen, activeTab, defaultTopK, error, setError }
setQueryMeta(null);
setSearchMeta(null);
setBulkSelectedIds(new Set());
+ setExactSearchState(null);
}, []);
return {
@@ -342,6 +382,9 @@ export function useSearchTab({ isOpen, activeTab, defaultTopK, error, setError }
isSearching,
queryMeta,
searchMeta,
+ exactSearch,
+ searchExactly,
+ searchWithCorrection,
bulkSelectedIds,
setBulkSelectedIds,
focusedResultIndex,
@@ -354,6 +397,7 @@ export function useSearchTab({ isOpen, activeTab, defaultTopK, error, setError }
selectedSearchResultName,
searchStatusLabel,
groupedResults,
+ navigableResults,
resultIdToIndex,
triggerSearchRefresh,
resetSearchState
diff --git a/src/renderer/components/search/utils/searchResultUtils.js b/src/renderer/components/search/utils/searchResultUtils.js
index 1641f0d9..4b832463 100644
--- a/src/renderer/components/search/utils/searchResultUtils.js
+++ b/src/renderer/components/search/utils/searchResultUtils.js
@@ -35,11 +35,11 @@ export function getErrorMessage(/** @type {any} */ error, context = 'Operation')
msg.includes('Vector DB') ||
msg.includes('not available yet')
) {
- return `${context} failed: Knowledge Graph is initializing. Please wait a moment and try again.`;
+ return `${context} failed: Knowledge Graph is initializing. Wait a moment and try again.`;
}
if (msg.includes('Embedding model changed') || msg.includes('dimension mismatch')) {
- return 'Embedding model changed. Please rebuild your index in Settings > Embeddings maintenance to use the new model.';
+ return 'Embedding model changed. Rebuild your index in Settings → Embeddings maintenance to use the new model.';
}
return msg || `${context} failed`;
diff --git a/src/renderer/components/settings/AIProviderConfigModal.jsx b/src/renderer/components/settings/AIProviderConfigModal.jsx
index b7418195..380aef9a 100644
--- a/src/renderer/components/settings/AIProviderConfigModal.jsx
+++ b/src/renderer/components/settings/AIProviderConfigModal.jsx
@@ -24,9 +24,9 @@ const PROVIDER_LABELS = {
};
const ANTHROPIC_MODELS = [
- { value: 'claude-opus-5-5', label: 'Claude Opus 5.5 — best quality (~$4/M input)' },
- { value: 'claude-sonnet-5-5', label: 'Claude Sonnet 5.5 — balanced (~$2/M input)' },
- { value: 'claude-haiku-5-5', label: 'Claude Haiku 5.5 — fastest (~$0.10/M input)' }
+ { value: 'claude-opus-5-5', label: 'Claude Opus 5.5 (best quality, ~$4/M input)' },
+ { value: 'claude-sonnet-5-5', label: 'Claude Sonnet 5.5 (balanced, ~$2/M input)' },
+ { value: 'claude-haiku-5-5', label: 'Claude Haiku 5.5 (fastest, ~$0.10/M input)' }
];
/**
@@ -38,7 +38,7 @@ const ANTHROPIC_MODELS = [
function anthropicModelOptions(current) {
const saved = String(current ?? '').trim();
if (!saved || ANTHROPIC_MODELS.some((m) => m.value === saved)) return ANTHROPIC_MODELS;
- return [{ value: saved, label: `${saved} — older model, currently in use` }, ...ANTHROPIC_MODELS];
+ return [{ value: saved, label: `${saved} (older model, currently in use)` }, ...ANTHROPIC_MODELS];
}
// Mirrors the Zod ceiling on spendCapMonthlyUsd (ipc/validationSchemas.js).
@@ -218,7 +218,7 @@ function AIProviderConfigModal({ provider, onClose, addNotification }) {
await dispatch(setProviderKey({ provider, key, allowPlaintext })).unwrap();
setKeyInput('');
addNotification?.(
- allowPlaintext ? 'API key saved (unencrypted — see warning).' : 'API key saved.',
+ allowPlaintext ? 'API key saved (unencrypted, see warning).' : 'API key saved.',
allowPlaintext ? 'warning' : 'success'
);
};
@@ -386,7 +386,7 @@ function AIProviderConfigModal({ provider, onClose, addNotification }) {
// Save again is now a plain config save on an off provider, which
// offers the consent prompt and stores the whole form.
addNotification?.(
- 'Provider turned off. Your other changes need cloud AI to be acknowledged first — press Save again to store them.',
+ 'Provider turned off. Your other changes need cloud AI to be acknowledged first. Press Save again to store them.',
'warning'
);
} else {
diff --git a/src/renderer/components/settings/AIProviderSection.jsx b/src/renderer/components/settings/AIProviderSection.jsx
index 31db8ebe..8423d480 100644
--- a/src/renderer/components/settings/AIProviderSection.jsx
+++ b/src/renderer/components/settings/AIProviderSection.jsx
@@ -70,7 +70,7 @@ function AIProviderSection({ addNotification }) {
const formatError = (err) => {
if (err?.code === 'CONSENT_REQUIRED' || err?.message === 'CONSENT_REQUIRED') {
- return 'Cloud AI consent is required. Please accept the privacy notice to continue.';
+ return 'Cloud AI consent is required. Accept the privacy notice to continue.';
}
return err?.message || 'Something went wrong.';
};
diff --git a/src/renderer/components/settings/AutoOrganizeSection.jsx b/src/renderer/components/settings/AutoOrganizeSection.jsx
index e3b14caa..c48758d0 100644
--- a/src/renderer/components/settings/AutoOrganizeSection.jsx
+++ b/src/renderer/components/settings/AutoOrganizeSection.jsx
@@ -86,11 +86,11 @@ function AutoOrganizeSection({ settings, setSettings }) {
className="w-full"
>
-
-
-
+
+
+
{settings.smartFolderRoutingMode !== 'llm' &&
@@ -123,8 +123,8 @@ function AutoOrganizeSection({ settings, setSettings }) {
{confidenceOutOfSliderRange && (
The saved value ({confidencePercent}%) is outside the slider's{' '}
- {Math.round(CONFIDENCE_MIN * 100)}–{Math.round(CONFIDENCE_MAX * 100)}% range. It still
- applies as saved; moving the slider will replace it.
+ {Math.round(CONFIDENCE_MIN * 100)} to {Math.round(CONFIDENCE_MAX * 100)}% range. It
+ still applies as saved; moving the slider will replace it.
)}
{currentOverrideUnavailable && (
- Saved override is not ready — analysis will use the app default or local model until the
+ Saved override is not ready. Analysis will use the app default or local model until the
provider is configured.
)}
diff --git a/src/renderer/components/setup/WatcherStatusLine.jsx b/src/renderer/components/setup/WatcherStatusLine.jsx
index 90f2b763..fea38778 100644
--- a/src/renderer/components/setup/WatcherStatusLine.jsx
+++ b/src/renderer/components/setup/WatcherStatusLine.jsx
@@ -64,7 +64,7 @@ function WatcherStatusLine({ folderCount, intervalMs = DEFAULT_INTERVAL_MS }) {
if (!status.isRunning) {
message = status.isStarting
? 'Starting folder watching…'
- : 'These folders are not being watched — files added later are analyzed only on the next scan. Turn on "Watch smart folders" in Settings → Auto-organize.';
+ : 'These folders are not being watched, so files added later are analyzed only on the next scan. Turn on "Watch smart folders" in Settings → Auto-organize.';
tone = 'text-stratosort-warning';
} else {
const watched = Number(status.watchedCount) || 0;
diff --git a/src/renderer/components/triage/DownloadsTriageView.jsx b/src/renderer/components/triage/DownloadsTriageView.jsx
index 9e7e64ac..06f62f82 100644
--- a/src/renderer/components/triage/DownloadsTriageView.jsx
+++ b/src/renderer/components/triage/DownloadsTriageView.jsx
@@ -50,7 +50,7 @@ const TAB_DEFS = [
{
key: 'keep',
label: 'Keep',
- copy: 'High-confidence matches to your Smart Folders — ready to organize.'
+ copy: 'High-confidence matches to your Smart Folders, ready to organize.'
},
{
key: 'excluded',
@@ -70,7 +70,7 @@ const TAB_DEFS = [
{
key: 'unmatched',
label: 'Unmatched',
- copy: "Deep scan couldn't find a folder match. These are likely orphans — decide manually."
+ copy: "Deep scan couldn't find a folder match. These are likely orphans. Decide manually."
}
];
@@ -208,7 +208,7 @@ export default function DownloadsTriageView({ isOpen, onClose }) {
setActiveTab('trash');
setIsDeepScanning(false);
hasAutoSelectedTrashRef.current = null;
- setError('Triage session expired — rescan the folder.');
+ setError('Triage session expired. Rescan the folder.');
});
}, []);
@@ -393,7 +393,7 @@ export default function DownloadsTriageView({ isOpen, onClose }) {
triageId,
action,
files,
- summary: { label: `Downloads triage — ${action}` }
+ summary: { label: `Downloads triage: ${action}` }
});
if (result?.errorCode === 'NO_SESSION' || result?.errorCode === 'NOT_IN_SESSION') {
setTriageId(null);
@@ -412,8 +412,8 @@ export default function DownloadsTriageView({ isOpen, onClose }) {
hasAutoSelectedTrashRef.current = null;
setError(
result?.errorCode === 'NOT_IN_SESSION'
- ? 'Those files are not in this triage session — rescan.'
- : 'Session expired — rescan the folder.'
+ ? 'Those files are not in this triage session. Rescan.'
+ : 'Session expired. Rescan the folder.'
);
return;
}
@@ -421,7 +421,7 @@ export default function DownloadsTriageView({ isOpen, onClose }) {
const failed = Array.isArray(result?.failed) ? result.failed.length : 0;
const done = action === 'trash' ? result?.trashed?.length : result?.moved?.length;
setError(
- `${action === 'trash' ? 'Trashed' : 'Organized'} ${done || 0} of ${files.length}. ${failed} failed — see logs.`
+ `${action === 'trash' ? 'Trashed' : 'Organized'} ${done || 0} of ${files.length}. ${failed} failed. See logs.`
);
} else if (!result?.success) {
setError(toErrorMessage(result?.error, 'Action failed'));
@@ -434,8 +434,8 @@ export default function DownloadsTriageView({ isOpen, onClose }) {
if (result?.undoUnavailable) {
actWarnings.push(
action === 'trash'
- ? 'Undo could not record this trash — restore from the OS Trash manually if needed.'
- : 'Undo could not record this move — undo will not cover these files.'
+ ? 'Undo could not record this trash. Restore from the OS Trash manually if needed.'
+ : 'Undo could not record this move, so undo will not cover these files.'
);
}
const rejectedCount = Array.isArray(result?.rejected) ? result.rejected.length : 0;
@@ -578,7 +578,7 @@ export default function DownloadsTriageView({ isOpen, onClose }) {
/>
- {scanWarning.partial ? 'Partial scan — results may be incomplete' : 'Scan note'}
+ {scanWarning.partial ? 'Partial scan: results may be incomplete' : 'Scan note'}
{(typeof scanWarning.filesIncluded === 'number' &&
typeof scanWarning.maxFiles === 'number') ||
diff --git a/src/renderer/components/ui/Modal.jsx b/src/renderer/components/ui/Modal.jsx
index 1a23f041..c40fd1a2 100644
--- a/src/renderer/components/ui/Modal.jsx
+++ b/src/renderer/components/ui/Modal.jsx
@@ -466,7 +466,7 @@ export const ConfirmModal = memo(function ConfirmModal({
const message =
(error && typeof error.message === 'string' && error.message.trim()) ||
(typeof error === 'string' && error.trim()) ||
- 'Something went wrong. Please try again.';
+ 'Something went wrong. Try again.';
setConfirmError(message);
}
} finally {
diff --git a/src/renderer/contexts/NotificationContext.jsx b/src/renderer/contexts/NotificationContext.jsx
index 62ba88d2..98278993 100644
--- a/src/renderer/contexts/NotificationContext.jsx
+++ b/src/renderer/contexts/NotificationContext.jsx
@@ -128,7 +128,7 @@ export function NotificationProvider({ children }) {
if (!message) return;
const notificationId = explicitNotificationId || payloadId;
- // Grouped toasts keep the first message, so a type-only default key
+ // A grouped toast shows only one of its messages, so a type-only default key
// would swallow distinct errors arriving in the same burst. Without an
// explicit groupKey, only collapse identical repeats of the same message.
const resolvedGroupKey = groupKey || `ipc:${type || 'notification'}:${message}`;
diff --git a/src/renderer/hooks/useKeyboardShortcuts.js b/src/renderer/hooks/useKeyboardShortcuts.js
index a834ea21..1513a66c 100644
--- a/src/renderer/hooks/useKeyboardShortcuts.js
+++ b/src/renderer/hooks/useKeyboardShortcuts.js
@@ -88,7 +88,11 @@ export function useKeyboardShortcuts() {
canRedoRef.current = canRedo;
}, [canRedo]);
- const handleOpenSettings = useCallback(() => dispatch(openSettings()), [dispatch]);
+ const handleOpenSettings = useCallback(
+ (/** @type {{ scrollToId?: string } | undefined} */ payload = undefined) =>
+ dispatch(openSettings(payload)),
+ [dispatch]
+ );
const handleAdvancePhase = useCallback(
(/** @type {any} */ phase) => dispatch(setPhase(phase)),
[dispatch]
@@ -284,6 +288,13 @@ export function useKeyboardShortcuts() {
actions.openSettings();
}
break;
+ case 'show-about':
+ // About lives in Settings' Application section (collapsed by
+ // default); the deep link expands it and scrolls there.
+ if (canHotkeySwapSurface()) {
+ actions.openSettings({ scrollToId: 'settings-app' });
+ }
+ break;
case 'select-files':
dispatchDiscoverEvent('app:select-files');
break;
diff --git a/src/renderer/hooks/useSettingsSubscription.js b/src/renderer/hooks/useSettingsSubscription.js
index 2750fcbc..bba00360 100644
--- a/src/renderer/hooks/useSettingsSubscription.js
+++ b/src/renderer/hooks/useSettingsSubscription.js
@@ -31,6 +31,22 @@ function stableSerialize(/** @type {any} */ value) {
}
}
+/**
+ * Main sends either the settings object or `{ settings }`.
+ * @param {any} payload
+ * @returns {Record | null}
+ */
+function normalizeSettingsPayload(payload) {
+ const settings =
+ payload &&
+ typeof payload === 'object' &&
+ payload.settings &&
+ typeof payload.settings === 'object'
+ ? payload.settings
+ : payload;
+ return settings && typeof settings === 'object' ? settings : null;
+}
+
function areValuesEqual(/** @type {any} */ a, /** @type {any} */ b) {
if (Object.is(a, b)) return true;
const aIsObject = a && typeof a === 'object';
@@ -77,16 +93,12 @@ export function useSettingsSubscription(onSettingsChanged, options = {}) {
useEffect(() => {
if (!enabled) return () => {};
+ let disposed = false;
+
const handleSettingsChanged = (/** @type {any} */ payload) => {
try {
- const normalizedSettings =
- payload &&
- typeof payload === 'object' &&
- payload.settings &&
- typeof payload.settings === 'object'
- ? payload.settings
- : payload;
- if (!normalizedSettings || typeof normalizedSettings !== 'object') {
+ const normalizedSettings = normalizeSettingsPayload(payload);
+ if (!normalizedSettings) {
return;
}
// If watching specific keys, filter to only those changes
@@ -109,7 +121,11 @@ export function useSettingsSubscription(onSettingsChanged, options = {}) {
key
);
nextWatchedValues[key] = nextValue;
- if (!hasPreviousValue || !areValuesEqual(prevValue, nextValue)) {
+ // Main broadcasts the whole settings object on every save, import
+ // and at startup. A key with no baseline yet is recorded, not
+ // reported: otherwise the first broadcast after mount claims
+ // every watched setting changed.
+ if (hasPreviousValue && !areValuesEqual(prevValue, nextValue)) {
relevantChanges[key] = nextValue;
hasRelevantChange = true;
}
@@ -131,6 +147,41 @@ export function useSettingsSubscription(onSettingsChanged, options = {}) {
}
};
+ // Seed the watched baseline with the current settings, so a real change
+ // that arrives as the first broadcast after mount is still reported.
+ // Keys an event already recorded are newer than this read and are kept.
+ const seedKeys = watchKeysRef.current;
+ const getSettings = window.electronAPI?.settings?.get;
+ if (Array.isArray(seedKeys) && typeof getSettings === 'function') {
+ Promise.resolve()
+ .then(() => getSettings())
+ .then(
+ /**
+ * @param {any} result
+ * @returns {null}
+ */
+ (result) => {
+ const current = normalizeSettingsPayload(result);
+ if (disposed || !current) return null;
+ /** @type {Record} */
+ const seeded = { ...(lastWatchedValuesRef.current || {}) };
+ seedKeys.forEach((/** @type {string} */ key) => {
+ if (key in current && !Object.prototype.hasOwnProperty.call(seeded, key)) {
+ seeded[key] = current[key];
+ }
+ });
+ lastWatchedValuesRef.current = seeded;
+ return null;
+ }
+ )
+ .catch((/** @type {any} */ error) => {
+ // Without a seed the first broadcast becomes the baseline.
+ logger.debug('Could not read settings to seed the watched baseline', {
+ error: error?.message
+ });
+ });
+ }
+
// Subscribe to settings changes
let unsubscribe = null;
if (window.electronAPI?.events?.onSettingsChanged) {
@@ -142,6 +193,7 @@ export function useSettingsSubscription(onSettingsChanged, options = {}) {
// Cleanup
return () => {
+ disposed = true;
if (typeof unsubscribe === 'function') {
try {
unsubscribe();
diff --git a/src/renderer/index.js b/src/renderer/index.js
index e4d6bddf..62d4e7dd 100644
--- a/src/renderer/index.js
+++ b/src/renderer/index.js
@@ -631,8 +631,7 @@ function initializeApp() {
const description = document.createElement('p');
description.className = 'splash-error-message';
- description.textContent =
- 'The application encountered an error during startup. Please try reloading.';
+ description.textContent = 'StratoSort hit an error during startup. Try reloading.';
const details = document.createElement('details');
details.className = 'splash-error-details';
diff --git a/src/renderer/phases/CompletePhase.jsx b/src/renderer/phases/CompletePhase.jsx
index d97b32db..db780fd9 100644
--- a/src/renderer/phases/CompletePhase.jsx
+++ b/src/renderer/phases/CompletePhase.jsx
@@ -21,6 +21,7 @@ import { useFileActions } from '../hooks/useFileActions';
import { isRemovedDuplicate } from '../utils/duplicateRemoval';
import { organizedEntryToRow } from '../utils/organizeRunResults';
import RunResultsList, { useRunResultsExport } from '../components/organize/RunResultsList';
+import { useAnalysisRun } from './discover/AnalysisRunProvider';
/**
* Pick a folder path safe to hand to shell.openPath — prefers `newLocation`
@@ -49,6 +50,7 @@ function baseName(p) {
function CompletePhase() {
const dispatch = useAppDispatch();
const { showError } = useNotification();
+ const { resetRun } = useAnalysisRun();
const organizedFiles = useAppSelector((state) => state.files.organizedFiles);
const organizedPathIndex = useAppSelector((state) => state.files.organizedPathIndex);
const organizedCount = useAppSelector(selectOrganizedCount);
@@ -145,6 +147,10 @@ function CompletePhase() {
// Clear this finished batch and go straight to Discover for the next
// one. Landing on Welcome made the user find Discover in the phase bar.
analyzeMoreFiles: () => {
+ // The run outlives the phases, so files can still be analyzing here.
+ // Clearing only Redux left it running unseen: no progress card or
+ // Stop button, and its lock queued the next files behind it.
+ resetRun('Analyze more files', { discard: true });
// React 18+ batches state updates automatically
dispatch(resetUi());
dispatch(resetFilesState());
@@ -162,7 +168,7 @@ function CompletePhase() {
}
}
}),
- [dispatch]
+ [dispatch, resetRun]
);
// Opens one destination folder: the footer button's, or a folder in the
@@ -210,7 +216,7 @@ function CompletePhase() {
const openFolderLabel = primaryFolderName ? `Open ${primaryFolderName}` : 'Open folder';
const openFolderHint =
destinationCount > 1
- ? `Opens ${redactPaths ? 'the folder' : primaryDestination} — it received the most files. Use the folder button on a row to see any other file.`
+ ? `Opens ${redactPaths ? 'the folder' : primaryDestination}, which received the most files. Use the folder button on a row to see any other file.`
: `Opens ${redactPaths ? 'the folder these files were moved to' : primaryDestination}`;
const showCelebration = totalFiles > 0 && !shouldReduceMotion;
@@ -298,7 +304,7 @@ function CompletePhase() {
A clean finish for this batch
- Review what changed, confirm the outcome, and start the next batch when you are ready.
+ Review what changed, then start the next batch when you're ready.
diff --git a/src/renderer/phases/DiscoverPhase.jsx b/src/renderer/phases/DiscoverPhase.jsx
index df87c1bc..e29a10af 100644
--- a/src/renderer/phases/DiscoverPhase.jsx
+++ b/src/renderer/phases/DiscoverPhase.jsx
@@ -57,7 +57,6 @@ function DiscoverPhase() {
setSeparator,
setFileStates,
updateFileState,
- resetAnalysisState,
actions,
organizedFiles,
organizedPathIndex,
@@ -285,6 +284,7 @@ function DiscoverPhase() {
retryFailedFiles,
reanalyzeFiles,
pruneBatchResultsForPath,
+ resetRun,
totalAnalysisFailure,
setTotalAnalysisFailure
} = useAnalysisRun();
@@ -448,12 +448,12 @@ function DiscoverPhase() {
collapsedSummary={
{isAnalyzing
- ? 'Analysis running now - expand for review tips'
+ ? 'Analysis running now. Expand for review tips.'
: visibleReadyCount > 0
- ? `${visibleReadyCount} file${visibleReadyCount !== 1 ? 's' : ''} ready to review - expand for review tips`
+ ? `${visibleReadyCount} file${visibleReadyCount !== 1 ? 's' : ''} ready to review. Expand for review tips.`
: pendingAnalysisCount > 0
- ? `${pendingAnalysisCount} file${pendingAnalysisCount !== 1 ? 's' : ''} waiting for analysis - expand for review tips`
- : 'Add files to begin - expand for review tips'}
+ ? `${pendingAnalysisCount} file${pendingAnalysisCount !== 1 ? 's' : ''} waiting for analysis. Expand for review tips.`
+ : 'Add files to begin. Expand for review tips.'}
}
>
@@ -483,8 +483,8 @@ function DiscoverPhase() {
Build a clean review queue
- This step is designed to stay simple: add files, let local AI prepare suggestions, and
- move forward only when the review list feels ready.
+ Add files, let local AI prepare suggestions, and move on when the review list looks
+ ready.
@@ -615,7 +615,9 @@ function DiscoverPhase() {
Date.now() - analysisProgress.lastActivity >
TIMEOUTS.STUCK_ANALYSIS_CHECK && (
resetAnalysisState('User forced reset')}
+ // The run's reset: it releases the lock and keeps
+ // finished results, unlike the Redux-only one.
+ onClick={() => resetRun('User forced reset')}
variant="warning"
size="sm"
>
@@ -871,7 +873,7 @@ function DiscoverPhase() {
addNotification(
visibleFailedCount > 0
? 'All files failed analysis. Retry them, or clear the queue and try again.'
- : 'Please analyze files first',
+ : 'Analyze files first',
'warning',
4000
);
diff --git a/src/renderer/phases/OrganizePhase.jsx b/src/renderer/phases/OrganizePhase.jsx
index 0f3f08c8..15e344eb 100644
--- a/src/renderer/phases/OrganizePhase.jsx
+++ b/src/renderer/phases/OrganizePhase.jsx
@@ -233,7 +233,14 @@ function OrganizePhase() {
);
}
if (field === 'suggestedName') {
- dispatch(updateAnalysisResult({ path: filePath, changes: { suggestedName: value } }));
+ // userSuggestedName marks the name as typed, so Discover's naming
+ // re-apply leaves it alone when the analysis provider remounts.
+ dispatch(
+ updateAnalysisResult({
+ path: filePath,
+ changes: { suggestedName: value, userSuggestedName: value }
+ })
+ );
}
},
[dispatch]
@@ -595,8 +602,7 @@ function OrganizePhase() {
Review & Organize
- Review the move plan, refine anything that needs attention, and stay in control before
- files are relocated.
+ Review the move plan and fix anything that needs attention before files move.
{isAnalysisRunning && (
@@ -623,8 +629,8 @@ function OrganizePhase() {
collapsedSummary={
{readyFilesCount > 0
- ? `${readyFilesCount} file${readyFilesCount !== 1 ? 's' : ''} ready for review - expand for organize tips`
- : 'Waiting for review items - expand for organize tips'}
+ ? `${readyFilesCount} file${readyFilesCount !== 1 ? 's' : ''} ready for review. Expand for organize tips.`
+ : 'Waiting for review items. Expand for organize tips.'}
}
>
@@ -639,7 +645,7 @@ function OrganizePhase() {
- Approve the move plan with confidence
+ Approve the move plan
This is the last review step before files move. Focus on anything uncertain, confirm
@@ -921,8 +927,8 @@ function OrganizePhase() {
{isOrganizing
- ? 'Please wait — destinations update as each file lands. You can cancel or pause below.'
- : `${readyFilesCount} file${readyFilesCount !== 1 ? 's' : ''} prepared for movement. Undo remains available after the batch completes.`}
+ ? 'Destinations update as each file lands. You can cancel or pause below.'
+ : `${readyFilesCount} file${readyFilesCount !== 1 ? 's' : ''} ready to move. You can still undo after the batch finishes.`}
{!isOrganizing && !isPaused ? (
diff --git a/src/renderer/phases/SetupPhase.jsx b/src/renderer/phases/SetupPhase.jsx
index 2e6c4e87..8095ed56 100644
--- a/src/renderer/phases/SetupPhase.jsx
+++ b/src/renderer/phases/SetupPhase.jsx
@@ -191,7 +191,7 @@ function SetupPhase() {
if (!Array.isArray(folders)) {
logger.warn('Received non-array response', { folders });
- notifyRef.current.showError?.('Failed to load smart folders. Please try again.');
+ notifyRef.current.showError?.('Failed to load smart folders. Try again.');
return;
}
@@ -587,10 +587,10 @@ function SetupPhase() {
collapsedSummary={
{hasConfiguredFolders
- ? `${destinationCount} destination${destinationCount !== 1 ? 's' : ''} ready — expand for setup tips`
+ ? `${destinationCount} destination${destinationCount !== 1 ? 's' : ''} ready. Expand for setup tips.`
: onlyFallbackFolder
- ? 'No destination yet, so files can only go to Uncategorized — expand for setup tips'
- : 'Add a destination to continue — expand for setup tips'}
+ ? 'No destination yet, so files can only go to Uncategorized. Expand for setup tips.'
+ : 'Add a destination to continue. Expand for setup tips.'}
}
>
@@ -854,7 +854,7 @@ function SetupPhase() {
}
if (currentFolders.length === 0) {
- showWarning('Please add at least one smart folder before continuing.');
+ showWarning('Add at least one smart folder before continuing.');
} else {
actions.setPhaseData('smartFolders', currentFolders);
setSmartFolders(currentFolders);
diff --git a/src/renderer/phases/WelcomePhase.jsx b/src/renderer/phases/WelcomePhase.jsx
index b97a6896..562af32d 100644
--- a/src/renderer/phases/WelcomePhase.jsx
+++ b/src/renderer/phases/WelcomePhase.jsx
@@ -380,7 +380,7 @@ function WelcomePhase() {
{
icon: CheckCircle2,
title: 'Complete',
- copy: 'See what changed and start the next batch with confidence.'
+ copy: 'See what changed, then start the next batch.'
}
];
@@ -433,7 +433,7 @@ function WelcomePhase() {
- Finish local AI setup when you are ready
+ Finish local AI setup when you're ready
You can use the app now; open model setup when you want full AI features.
@@ -655,8 +655,7 @@ function WelcomePhase() {
>
- StratoSort follows a simple, review-first workflow so you stay in control before any
- files move.
+ StratoSort is review-first, so you stay in control before any files move.
{flowSteps.map((item, idx) => (
diff --git a/src/renderer/phases/discover/AnalysisRunProvider.jsx b/src/renderer/phases/discover/AnalysisRunProvider.jsx
index 319157da..71b22771 100644
--- a/src/renderer/phases/discover/AnalysisRunProvider.jsx
+++ b/src/renderer/phases/discover/AnalysisRunProvider.jsx
@@ -37,7 +37,6 @@ export function AnalysisRunProvider({ children }) {
setAnalysisResults,
setFileStates,
updateFileState,
- resetAnalysisState,
actions,
getCurrentPhase
} = useDiscoverState();
@@ -64,7 +63,11 @@ export function AnalysisRunProvider({ children }) {
clearAnalysisQueue,
retryFailedFiles,
reanalyzeFiles,
- pruneBatchResultsForPath
+ pruneBatchResultsForPath,
+ // The run's own reset, not useDiscoverState's Redux-only one: it also
+ // aborts the run, releases its lock and drops its queued files, and it
+ // keeps finished results (the Redux one clears them all).
+ resetAnalysisState: resetRun
} = useAnalysis({
selectedFiles,
fileStates,
@@ -87,7 +90,8 @@ export function AnalysisRunProvider({ children }) {
// Stuck-run checks. They belong with the run, not with the Discover
// screen: a run that keeps going while the user is on Organize still
- // needs its watchdog.
+ // needs its watchdog. They reset through the run, so a retry is not
+ // blocked by its lock and finished results stay.
const initialStuckCheckRef = useRef(false);
useEffect(() => {
if (initialStuckCheckRef.current) return;
@@ -97,10 +101,10 @@ export function AnalysisRunProvider({ children }) {
const lastActivity = analysisProgress?.lastActivity || Date.now();
if (Date.now() - lastActivity > 2 * 60 * 1000) {
logger.info('Detected stuck analysis state on mount, resetting');
- resetAnalysisState('Stuck analysis detected on mount');
+ resetRun('Stuck analysis detected on mount');
}
}
- }, [isAnalyzing, analysisProgress, resetAnalysisState]);
+ }, [isAnalyzing, analysisProgress, resetRun]);
const analysisProgressRef = useRef(analysisProgress);
analysisProgressRef.current = analysisProgress;
@@ -122,13 +126,13 @@ export function AnalysisRunProvider({ children }) {
if (current === 0 && total > 0 && timeSinceActivity > TIMEOUTS.STUCK_ANALYSIS_CHECK) {
addNotification('Analysis paused. Restarting...', 'info', 3000, 'analysis-stalled');
- resetAnalysisState('Analysis stalled with no progress after 2 minutes');
+ resetRun('Analysis stalled with no progress after 2 minutes');
return;
}
if (timeSinceActivity > TIMEOUTS.ANALYSIS_LOCK) {
addNotification('Analysis timed out. Ready to retry.', 'info', 3000, 'analysis-auto-reset');
- resetAnalysisState('Stuck analysis state after 5 minutes of inactivity');
+ resetRun('Stuck analysis state after 5 minutes of inactivity');
}
};
@@ -136,7 +140,7 @@ export function AnalysisRunProvider({ children }) {
// Defer so the interval handler returns quickly (avoids Long Task violations).
const intervalId = setInterval(() => setTimeout(checkStalled, 0), TIMEOUTS.SERVICE_STARTUP);
return () => clearInterval(intervalId);
- }, [isAnalyzing, addNotification, resetAnalysisState, store]);
+ }, [isAnalyzing, addNotification, resetRun, store]);
const value = useMemo(
() => ({
@@ -146,6 +150,7 @@ export function AnalysisRunProvider({ children }) {
retryFailedFiles,
reanalyzeFiles,
pruneBatchResultsForPath,
+ resetRun,
totalAnalysisFailure,
setTotalAnalysisFailure
}),
@@ -156,6 +161,7 @@ export function AnalysisRunProvider({ children }) {
retryFailedFiles,
reanalyzeFiles,
pruneBatchResultsForPath,
+ resetRun,
totalAnalysisFailure
]
);
@@ -178,3 +184,11 @@ export function useAnalysisRun() {
}
return run;
}
+
+/**
+ * The analysis run, or null outside AnalysisRunProvider. For components such
+ * as the phase error boundary that can render without the provider.
+ */
+export function useOptionalAnalysisRun() {
+ return useContext(AnalysisRunContext);
+}
diff --git a/src/renderer/phases/discover/useAnalysis.js b/src/renderer/phases/discover/useAnalysis.js
index 7c78f2b5..858fbc13 100644
--- a/src/renderer/phases/discover/useAnalysis.js
+++ b/src/renderer/phases/discover/useAnalysis.js
@@ -301,6 +301,21 @@ function dedupeSuggestedNames(/** @type {any} */ results) {
return changed ? next : results;
}
+/**
+ * True when the name was typed by the user in Organize. Re-applying the
+ * naming convention must leave it alone: the effect runs on every mount of
+ * the analysis provider (Dashboard view and back, app launch), not only on
+ * a real settings change.
+ *
+ * @param {any} analysis
+ * @returns {boolean}
+ */
+function hasUserSuggestedName(analysis) {
+ return (
+ typeof analysis?.userSuggestedName === 'string' && analysis.userSuggestedName.trim() !== ''
+ );
+}
+
/**
* Merge file states with new analysis results.
*
@@ -757,13 +772,22 @@ export function useAnalysis(options = {}) {
/**
* Reset analysis state
+ * @param {any} reason
+ * @param {{ discard?: boolean }} [options] discard: the user is starting
+ * over, so a cancelled batch that answers later must not bring its
+ * results back, and a pending auto-advance must not leave Discover.
*/
const resetAnalysisState = useCallback(
- (/** @type {any} */ reason) => {
+ (/** @type {any} */ reason, /** @type {{ discard?: boolean }} */ options = {}) => {
logger.info('Resetting analysis state', { reason });
invalidateEmbeddingStatsCache();
const activeRunId = analysisRunIdRef.current;
- captureCancelledBatchSnapshot(activeRunId);
+ if (options?.discard === true) {
+ cancelledBatchSnapshotRef.current = null;
+ clearAutoAdvanceTimeoutRef(autoAdvanceTimeoutRef);
+ } else {
+ captureCancelledBatchSnapshot(activeRunId);
+ }
requestMainBatchCancel('reset-analysis-state');
analysisRunIdRef.current = activeRunId + 1;
// Ensure any in-flight analysis is stopped and locks are released.
@@ -953,7 +977,7 @@ export function useAnalysis(options = {}) {
// Check if any result actually needs updating
let hasChanges = false;
const updated = prev.map((/** @type {any} */ result) => {
- if (!result?.analysis) return result;
+ if (!result?.analysis || hasUserSuggestedName(result.analysis)) return result;
const newName = generateSuggestedName(
result.name || extractFileName(result.path || ''),
@@ -994,7 +1018,7 @@ export function useAnalysis(options = {}) {
const next = { ...prev };
Object.entries(next).forEach(([filePath, state]) => {
- if (!state?.analysis) return;
+ if (!state?.analysis || hasUserSuggestedName(state.analysis)) return;
const newName = generateSuggestedName(
state.name || extractFileName(filePath),
@@ -1949,9 +1973,19 @@ export function useAnalysis(options = {}) {
collectOrganizedPathKeys(filesState?.organizedFiles)
)
);
- const batchResults = batchResultsRef.current.filter(
- (/** @type {any} */ r) => !organizedKeys.has(toCanonicalPath(r?.path))
+ // Results this run already shown are in the store, and the user may
+ // have edited them in Organize since (userCategory, a typed name).
+ // Put the waiting ones in first, then add only results the store
+ // still lacks: replacing by path would put the run's unedited copy
+ // back over the edit.
+ applyPendingResults();
+ const storedKeys = new Set(
+ (analysisResultsRef.current || []).map((/** @type {any} */ r) => toCanonicalPath(r?.path))
);
+ const batchResults = batchResultsRef.current.filter((/** @type {any} */ r) => {
+ const key = toCanonicalPath(r?.path);
+ return !organizedKeys.has(key) && !storedKeys.has(key);
+ });
// Merge results using extracted helper functions
const mergedResults = dedupeSuggestedNames(
mergeAnalysisResults(analysisResultsRef.current, batchResults)
@@ -2107,6 +2141,7 @@ export function useAnalysis(options = {}) {
captureCancelledBatchSnapshot,
requestMainBatchCancel,
flushPendingResults,
+ applyPendingResults,
applyAnalysisOutcome,
dispatchProgressUpdate,
requeueInFlightFileStates,
diff --git a/src/renderer/phases/discover/useFileHandlers.js b/src/renderer/phases/discover/useFileHandlers.js
index 68cdbef2..a17c90f6 100644
--- a/src/renderer/phases/discover/useFileHandlers.js
+++ b/src/renderer/phases/discover/useFileHandlers.js
@@ -23,7 +23,7 @@ const ensureFileApi = (/** @type {any} */ addNotification, /** @type {any} */ ac
if (!window?.electronAPI?.files) {
logger.warn('[DiscoverPhase] File API unavailable', { actionLabel });
addNotification?.(
- 'File system API not ready. Please wait for the app to finish loading.',
+ 'File system API not ready. Wait for the app to finish loading.',
'warning',
3000,
'file-api-unavailable'
@@ -40,7 +40,7 @@ const ensureSmartFolderApi = (
if (!window?.electronAPI?.smartFolders) {
logger.warn('[DiscoverPhase] Smart folder API unavailable', { actionLabel });
addNotification?.(
- 'Smart folder API not ready. Please wait for the app to finish loading.',
+ 'Smart folder API not ready. Wait for the app to finish loading.',
'warning',
3000,
'smart-folder-api-unavailable'
@@ -435,7 +435,7 @@ export function useFileHandlers({
() =>
reject(
new Error(
- 'Folder scan timeout - the folder may be on a slow network drive or contain too many files'
+ 'Folder scan timed out. The folder may be on a slow network drive or contain too many files'
)
),
SCAN_TIMEOUT
@@ -650,7 +650,7 @@ export function useFileHandlers({
() =>
reject(
new Error(
- 'Folder scan timeout - the folder may be on a slow network drive or contain too many files'
+ 'Folder scan timed out. The folder may be on a slow network drive or contain too many files'
)
),
SCAN_TIMEOUT
diff --git a/src/renderer/phases/organize/useOrganization.js b/src/renderer/phases/organize/useOrganization.js
index d6b2d4df..a77584f5 100644
--- a/src/renderer/phases/organize/useOrganization.js
+++ b/src/renderer/phases/organize/useOrganization.js
@@ -10,7 +10,7 @@
import { useState, useCallback, useEffect, useMemo, useRef } from 'react';
import { IPC_CHANNELS, PHASES } from '../../../shared/constants';
import { createLogger } from '../../../shared/logger';
-import { extractExtension } from '../../../shared/namingConventions';
+import { extractExtension, trailingFileExtension } from '../../../shared/namingConventions';
import { createOrganizeBatchAction, previewBatchOrganize } from '../../components/UndoRedoSystem';
import { updateResultPathsAfterMove } from '../../store/slices/analysisSlice';
import { updateFilePathsAfterMove } from '../../store/slices/filesSlice';
@@ -506,8 +506,6 @@ const normalizeForComparison = (/** @type {any} */ path) => {
return isWindowsPath(path) || isMac ? normalized.toLowerCase() : normalized;
};
-const hasFileExtension = (/** @type {any} */ fileName) => !!extractExtension(fileName);
-
/**
* Helper to join paths using the correct separator based on the root
*/
@@ -595,11 +593,16 @@ function processFileForOrganization({
const suggestedName = edits.suggestedName || fileWithEdits.analysis?.suggestedName || file.name;
const safeSuggestedName = sanitizeDestinationFileName(suggestedName, file.name);
- // Preserve compound extensions like .tar.gz when suggested name omits extension
+ // Re-add the file's own extension (compound-aware, like .tar.gz) unless the
+ // name already ends with it or with another one typed on purpose. Text
+ // after a dot is not an extension by itself: "Receipt from J. Smith" must
+ // still land as a .pdf.
const originalExt = extractExtension(file.name);
- const hasExtension = hasFileExtension(safeSuggestedName);
- const newName =
- hasExtension || !originalExt ? safeSuggestedName : `${safeSuggestedName}${originalExt}`;
+ const keepsName =
+ !originalExt ||
+ safeSuggestedName.toLowerCase().endsWith(originalExt.toLowerCase()) ||
+ Boolean(trailingFileExtension(safeSuggestedName));
+ const newName = keepsName ? safeSuggestedName : `${safeSuggestedName}${originalExt}`;
const dest = joinPath(destinationDir, newName);
const normalized = window.electronAPI?.files?.normalizePath?.(dest) || dest;
@@ -1033,7 +1036,7 @@ export function useOrganization({
if (!resumeInfo && filesToProcess.length === 0) {
addNotification(
- 'No files ready to organize. Please ensure files have been analyzed.',
+ 'No files ready to organize. Make sure the files have been analyzed.',
'warning'
);
logger.warn('[ORGANIZE] No files to process - returning early');
@@ -1638,7 +1641,7 @@ export function useOrganization({
});
}
addNotification(
- `Organization paused — ${successCount} file${successCount === 1 ? '' : 's'} organized so far. Resume when ready.`,
+ `Organization paused with ${successCount} file${successCount === 1 ? '' : 's'} organized so far. Resume when ready.`,
'info',
5000,
'organize-paused'
@@ -1669,7 +1672,7 @@ export function useOrganization({
? result.cancelledCount
: Math.max(0, totalResultCount - successCount);
addNotification(
- `Organization cancelled — ${successCount} file${successCount === 1 ? '' : 's'} organized, ${remaining} skipped.`,
+ `Organization cancelled: ${successCount} file${successCount === 1 ? '' : 's'} organized, ${remaining} skipped.`,
'warning'
);
return;
diff --git a/src/renderer/services/ipc/electronApi.js b/src/renderer/services/ipc/electronApi.js
index 6b8ca0b4..7d182eeb 100644
--- a/src/renderer/services/ipc/electronApi.js
+++ b/src/renderer/services/ipc/electronApi.js
@@ -13,7 +13,7 @@ export function getElectronAPI() {
export function requireElectronAPI() {
const api = getElectronAPI();
if (!api) {
- throw new Error('Electron API not available. Please restart the application.');
+ throw new Error('Electron API not available. Restart the app.');
}
return api;
}
diff --git a/src/renderer/services/ipc/smartFoldersIpc.js b/src/renderer/services/ipc/smartFoldersIpc.js
index 83c4b313..0b800365 100644
--- a/src/renderer/services/ipc/smartFoldersIpc.js
+++ b/src/renderer/services/ipc/smartFoldersIpc.js
@@ -21,7 +21,7 @@ function withDescriptionTimeout(promise, timeoutMs) {
timeoutId = setTimeout(() => {
resolve({
success: false,
- error: 'Description generation timed out. Please try again.'
+ error: 'Description generation timed out. Try again.'
});
}, effectiveTimeoutMs);
});
diff --git a/src/renderer/store/index.js b/src/renderer/store/index.js
index b62e8498..14236475 100644
--- a/src/renderer/store/index.js
+++ b/src/renderer/store/index.js
@@ -484,7 +484,10 @@ const loadState = () => {
graphTourDismissed: resolveDurableGraphTourDismissed(parsed.ui?.graphTourDismissed),
graphInsightsSection: (() => {
const v = parsed.ui?.graphInsightsSection;
- if (v == null) return 'insights';
+ // null is a saved choice (every section collapsed); only a missing
+ // key (older blobs) falls back to the default.
+ if (v === null) return null;
+ if (v === undefined) return 'insights';
return GRAPH_INSIGHTS_SECTION_KEYS.includes(v) ? v : 'insights';
})(),
graphLegendHintDismissed: parsed.ui?.graphLegendHintDismissed === true,
diff --git a/src/renderer/store/middleware/ipcMiddleware.js b/src/renderer/store/middleware/ipcMiddleware.js
index e321aa7c..b9b0ca2c 100644
--- a/src/renderer/store/middleware/ipcMiddleware.js
+++ b/src/renderer/store/middleware/ipcMiddleware.js
@@ -235,7 +235,7 @@ function safeDispatch(actionCreator, data) {
eventQueue.push({
actionCreator: addNotification,
data: {
- message: 'System is busy - some updates may be delayed.',
+ message: 'System is busy, so some updates may be delayed.',
severity: 'warning',
duration: 5000
}
diff --git a/src/renderer/store/middleware/persistenceMiddleware.js b/src/renderer/store/middleware/persistenceMiddleware.js
index 8b41103d..fee74e66 100644
--- a/src/renderer/store/middleware/persistenceMiddleware.js
+++ b/src/renderer/store/middleware/persistenceMiddleware.js
@@ -667,11 +667,11 @@ const persistenceMiddleware = (/** @type {any} */ store) => {
if (saveResult.degraded) {
const messages = {
reduced:
- 'Storage space limited - some file history may not be preserved between sessions.',
+ 'Storage space limited. Some file history may not be preserved between sessions.',
minimal:
- 'Storage space very limited - only settings and current phase will be preserved.',
- emergency: 'Storage space critically low - cleared old data to continue.',
- failed: 'Unable to save any data - changes will be lost when you close the app.'
+ 'Storage space very limited. Only settings and the current phase will be preserved.',
+ emergency: 'Storage space critically low. Old data was cleared to continue.',
+ failed: 'Unable to save any data. Changes will be lost when you close the app.'
};
const severity = saveResult.degraded === 'failed' ? 'error' : 'warning';
store.dispatch(
diff --git a/src/renderer/store/slices/aiProviderSlice.js b/src/renderer/store/slices/aiProviderSlice.js
index b2d85f82..1cbd50d3 100644
--- a/src/renderer/store/slices/aiProviderSlice.js
+++ b/src/renderer/store/slices/aiProviderSlice.js
@@ -1,5 +1,5 @@
// @ts-check
-import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
+import { createSlice, createAsyncThunk, isPending } from '@reduxjs/toolkit';
const _api = () => window.electronAPI?.aiProvider;
@@ -281,7 +281,22 @@ const slice = createSlice({
})
.addCase(acknowledgeCloud.rejected, (s, a) => {
s.lastError = /** @type {any} */ (a.payload)?.message || a.error.message;
- });
+ })
+ // A new user action supersedes the last failure. Without this an old
+ // error (e.g. CONSENT_DECLINED) stayed on screen after later actions
+ // succeeded, because only fetchAiConfig.pending used to clear it.
+ .addMatcher(
+ isPending(
+ setProviderConfig,
+ setProviderKey,
+ removeProviderKey,
+ setRouting,
+ acknowledgeCloud
+ ),
+ (s) => {
+ s.lastError = null;
+ }
+ );
}
});
diff --git a/src/renderer/store/slices/uiSlice.js b/src/renderer/store/slices/uiSlice.js
index acca188e..ceeb5c35 100644
--- a/src/renderer/store/slices/uiSlice.js
+++ b/src/renderer/store/slices/uiSlice.js
@@ -437,6 +437,14 @@ const uiSlice = createSlice({
selectedTheme: state?.selectedTheme ?? initialState.selectedTheme,
graphInsightsDockCollapsed:
state?.graphInsightsDockCollapsed ?? initialState.graphInsightsDockCollapsed,
+ // The settings cache mirrors what main has saved; it is not session
+ // state. Nothing refetches it after a reset, so dropping it made
+ // selectNamingDefaults fall back to the hard-coded defaults, which
+ // Discover then sent to main as a naming override on every analyze.
+ settings: state?.settings ?? initialState.settings,
+ settingsLoaded: state?.settingsLoaded ?? initialState.settingsLoaded,
+ settingsLoading: state?.settingsLoading ?? initialState.settingsLoading,
+ settingsError: state?.settingsError ?? initialState.settingsError,
settingsScrollTargetId: null,
organizeFocusRequest: null,
// Preserve `previousPhase` across reset. The persistence layer
diff --git a/src/renderer/store/thunks/fileThunks.js b/src/renderer/store/thunks/fileThunks.js
index 31f390df..beb2a0c4 100644
--- a/src/renderer/store/thunks/fileThunks.js
+++ b/src/renderer/store/thunks/fileThunks.js
@@ -10,6 +10,7 @@ import { removeSelectedFile, setFileStates } from '../slices/filesSlice';
import { removeAnalysisResult } from '../slices/analysisSlice';
import { atomicRemoveFilesWithCleanup } from '../slices/atomicActions';
import { updateEmbeddingState } from '../slices/analysisSlice';
+import { addNotification } from '../slices/systemSlice';
import { embeddingsIpc } from '../../services/ipc';
import { logger } from '../../../shared/logger';
import { toCanonicalPath } from '../../utils/canonicalPath';
@@ -87,6 +88,23 @@ export const setEmbeddingPolicyForFile =
embeddingStatus: nextStatus
})
);
+ } else if (result?.success === false) {
+ // Main stored nothing (e.g. notFound: no history entry for this path).
+ // Say so, or the menu click looks accepted while organize ignores it.
+ logger.warn('[fileThunks] Embedding policy not saved', {
+ policy,
+ notFound: Boolean(result?.notFound),
+ error: result?.error
+ });
+ dispatch(
+ addNotification({
+ message: result?.notFound
+ ? 'The embedding setting was not changed: this file has no saved analysis yet. Analyze it first, then try again.'
+ : 'The embedding setting could not be changed. Try again.',
+ severity: 'warning',
+ duration: 6000
+ })
+ );
}
} catch (err) {
logger.error('[fileThunks] Failed to set embedding policy', { error: err?.message });
diff --git a/src/renderer/utils/analysisHistoryFetch.js b/src/renderer/utils/analysisHistoryFetch.js
index 5b5ef6a3..a20ca70a 100644
--- a/src/renderer/utils/analysisHistoryFetch.js
+++ b/src/renderer/utils/analysisHistoryFetch.js
@@ -20,8 +20,9 @@ export async function fetchAnalysisHistoryPages(options = {}) {
const getHistory = window?.electronAPI?.analysisHistory?.get;
if (typeof getHistory !== 'function') return [];
- const pageSize = Math.min(MAX_PAGE_SIZE, toPositiveInt(options.pageSize, DEFAULT_PAGE_SIZE));
- const maxEntries = Math.max(pageSize, toPositiveInt(options.maxEntries, DEFAULT_MAX_ENTRIES));
+ const basePageSize = Math.min(MAX_PAGE_SIZE, toPositiveInt(options.pageSize, DEFAULT_PAGE_SIZE));
+ const maxEntries = Math.max(basePageSize, toPositiveInt(options.maxEntries, DEFAULT_MAX_ENTRIES));
+ let pageSize = basePageSize;
/** @type {any[]} */
const allEntries = [];
@@ -40,6 +41,25 @@ export async function fetchAnalysisHistoryPages(options = {}) {
break;
}
+ // The preload rejects a response over its size cap (entries carry full
+ // transcript segments). Retry the same offset with a smaller page; at
+ // one entry, skip that entry rather than end the whole history there.
+ // The reason string is set by validateResult in src/preload/ipcValidator.js.
+ if (page && page.reason === 'payload-too-large') {
+ if (pageSize > 1) {
+ pageSize = Math.max(1, Math.floor(pageSize / 2));
+ logger.warn('History page too large; retrying with a smaller page', { offset, pageSize });
+ continue;
+ }
+ logger.warn('Skipping a history entry that exceeds the IPC size cap', { offset });
+ offset += 1;
+ // Keep the small page: the next entries are often large too, and
+ // jumping back to the full size would re-read and reject a full page
+ // per skipped entry. The doubling below grows it back once pages
+ // succeed, so a lone large entry costs a few small calls.
+ continue;
+ }
+
if (!Array.isArray(page)) {
logger.warn('History page payload is invalid; stopping pagination', {
offset,
@@ -59,6 +79,12 @@ export async function fetchAnalysisHistoryPages(options = {}) {
if (page.length < pageSize) {
break;
}
+
+ // Grow back after a shrunken page succeeds, so only the window of large
+ // entries is read in small pages.
+ if (pageSize < basePageSize) {
+ pageSize = Math.min(basePageSize, pageSize * 2);
+ }
}
return allEntries.slice(0, maxEntries);
diff --git a/src/renderer/utils/canonicalPath.js b/src/renderer/utils/canonicalPath.js
index 37f4b64e..408e81e2 100644
--- a/src/renderer/utils/canonicalPath.js
+++ b/src/renderer/utils/canonicalPath.js
@@ -8,9 +8,9 @@
* same file. Canonical form: Unicode composed (NFC), forward slashes,
* lowercased when the path is Windows-style.
*
- * Main composes every path it validates and returns that spelling in its
- * result rows, while a Mac app can save "März.pdf" decomposed. Without NFC
- * here a moved file's result row would not find its queue entry.
+ * On macOS main composes every path it validates and returns that spelling
+ * in its result rows, while a Mac app can save "März.pdf" decomposed. Without
+ * NFC here a moved file's result row would not find its queue entry.
*
* Single source of truth — keep every renderer-side path-keyed map/set
* (writes AND reads) on this helper so lookups can't miss on key style.
diff --git a/src/renderer/utils/errorMapping.js b/src/renderer/utils/errorMapping.js
index 08164009..5f460c71 100644
--- a/src/renderer/utils/errorMapping.js
+++ b/src/renderer/utils/errorMapping.js
@@ -13,23 +13,23 @@ const DEFAULT_NOTIFICATION = {
const ERROR_TYPE_MAP = {
TIMEOUT: {
severity: 'warning',
- message: 'Operation timed out. Please try again.'
+ message: 'Operation timed out. Try again.'
},
IPC_TIMEOUT: {
severity: 'warning',
- message: 'The AI is busy processing other requests. Please try again shortly.'
+ message: 'The AI is busy with other requests. Try again shortly.'
},
RATE_LIMITED: {
severity: 'warning',
- message: 'Too many requests. Please wait a moment and try again.'
+ message: 'Too many requests. Wait a moment and try again.'
},
CIRCUIT_OPEN: {
severity: 'warning',
- message: 'AI service is temporarily recovering. Please wait a moment and try again.'
+ message: 'AI service is temporarily recovering. Wait a moment and try again.'
},
HANDLER_NOT_READY: {
severity: 'warning',
- message: 'Service is still starting up. Please wait a moment and try again.'
+ message: 'Service is still starting up. Wait a moment and try again.'
},
NETWORK: {
severity: 'warning',
@@ -146,17 +146,17 @@ const ERROR_CODE_MAP = {
[AI_ERROR_CODES.LLAMA_MODEL_LOAD_FAILED]: {
severity: 'error',
message:
- 'Could not load the AI model. Re-download it from Settings → Models, or switch to a smaller model if this keeps happening.'
+ 'Could not load the AI model. Re-download it from Settings → Model management, or switch to a smaller model if this keeps happening.'
},
[AI_ERROR_CODES.LLAMA_MODEL_NOT_FOUND]: {
severity: 'error',
message:
- 'AI model file is missing. Open Settings → Models to install it, or run the model setup wizard from the welcome screen.'
+ 'AI model file is missing. Open Settings → Model management to install it, or run the model setup wizard from the welcome screen.'
},
[AI_ERROR_CODES.LLAMA_MODEL_INCOMPATIBLE_CPU]: {
severity: 'error',
message:
- 'Your CPU does not support instructions required by this model (SIGILL). Switch to the small Qwen 0.5B profile in Settings → Models, or install a build matching your CPU.'
+ 'Your CPU does not support instructions required by this model (SIGILL). Switch to the small Qwen 0.5B profile in Settings → Default AI models, or install a build matching your CPU.'
},
[AI_ERROR_CODES.LLAMA_MODEL_PATH_MISMATCH]: {
severity: 'error',
@@ -166,11 +166,11 @@ const ERROR_CODE_MAP = {
[AI_ERROR_CODES.LLAMA_MODEL_AUTO_FALLBACK]: {
severity: 'warning',
message:
- 'The configured AI model was unavailable, so StratoSort switched to a smaller default model. Quality may be reduced — reinstall the preferred model from Settings → Models to restore it.'
+ 'The configured AI model was unavailable, so StratoSort switched to a smaller default model. Quality may be reduced. Reinstall the preferred model from Settings → Model management to restore it.'
},
[AI_ERROR_CODES.LLAMA_INFERENCE_FAILED]: {
severity: 'error',
- message: 'AI inference failed. Please try again.'
+ message: 'AI inference failed. Try again.'
},
[AI_ERROR_CODES.LLAMA_GPU_ERROR]: {
severity: 'warning',
@@ -182,7 +182,7 @@ const ERROR_CODE_MAP = {
},
[AI_ERROR_CODES.VECTOR_DB_INIT_FAILED]: {
severity: 'error',
- message: 'Vector database failed to initialize. Please restart the app.'
+ message: 'Vector database failed to initialize. Restart the app.'
},
[AI_ERROR_CODES.VECTOR_DB_PERSIST_FAILED]: {
severity: 'warning',
@@ -190,7 +190,7 @@ const ERROR_CODE_MAP = {
},
[AI_ERROR_CODES.VECTOR_DB_QUERY_FAILED]: {
severity: 'error',
- message: 'Search failed. Please try again.'
+ message: 'Search failed. Try again.'
},
[AI_ERROR_CODES.VECTOR_DB_DIMENSION_MISMATCH]: {
severity: 'warning',
@@ -198,15 +198,15 @@ const ERROR_CODE_MAP = {
},
[AI_ERROR_CODES.EMBEDDING_GENERATION_FAILED]: {
severity: 'error',
- message: 'Failed to generate embeddings. Please try again.'
+ message: 'Failed to generate embeddings. Try again.'
},
[AI_ERROR_CODES.ANALYSIS_FAILED]: {
severity: 'error',
- message: 'Analysis failed. Please try again.'
+ message: 'Analysis failed. Try again.'
},
[AI_ERROR_CODES.MIGRATION_FAILED]: {
severity: 'error',
- message: 'Migration failed. Please restart the app or check logs.'
+ message: 'Migration failed. Restart the app or check logs.'
},
// ── File-system codes surfaced at the IPC boundary ──
[AI_ERROR_CODES.FILE_NOT_FOUND]: {
@@ -248,7 +248,7 @@ const ERROR_CODE_MAP = {
// ── Availability / model state ──
[AI_ERROR_CODES.MODEL_NOT_AVAILABLE]: {
severity: 'warning',
- message: 'AI model is not ready. Wait for setup to finish or open Settings → Models.'
+ message: 'AI model is not ready. Wait for setup to finish or open Settings → Model management.'
},
[AI_ERROR_CODES.INVALID_FILE_TYPE]: {
severity: 'warning',
@@ -257,11 +257,11 @@ const ERROR_CODE_MAP = {
// ── Validation ──
[AI_ERROR_CODES.VALIDATION_ERROR]: {
severity: 'warning',
- message: 'Request was invalid. Please check the form and try again.'
+ message: 'Request was invalid. Check the form and try again.'
},
[AI_ERROR_CODES.INVALID_INPUT]: {
severity: 'warning',
- message: 'One or more inputs were invalid. Please review and try again.'
+ message: 'One or more inputs were invalid. Review them and try again.'
},
[AI_ERROR_CODES.INVALID_PATH]: {
severity: 'warning',
@@ -277,7 +277,7 @@ const ERROR_CODE_MAP = {
},
[AI_ERROR_CODES.INVALID_FOLDER_DATA]: {
severity: 'warning',
- message: 'Folder configuration is invalid. Please review the values and retry.'
+ message: 'Folder configuration is invalid. Review the values and retry.'
},
[AI_ERROR_CODES.INVALID_FOLDER_NAME]: {
severity: 'warning',
@@ -321,27 +321,27 @@ const ERROR_CODE_MAP = {
// ── Smart folder operations ──
[AI_ERROR_CODES.SAVE_FAILED]: {
severity: 'error',
- message: 'Save failed. Please try again.'
+ message: 'Save failed. Try again.'
},
[AI_ERROR_CODES.UPDATE_FAILED]: {
severity: 'error',
- message: 'Update failed. Please try again.'
+ message: 'Update failed. Try again.'
},
[AI_ERROR_CODES.EDIT_FAILED]: {
severity: 'error',
- message: 'Edit failed. Please try again.'
+ message: 'Edit failed. Try again.'
},
[AI_ERROR_CODES.DELETE_FAILED]: {
severity: 'error',
- message: 'Delete failed. Please try again.'
+ message: 'Delete failed. Try again.'
},
[AI_ERROR_CODES.ADD_FOLDER_FAILED]: {
severity: 'error',
- message: 'Could not add that folder. Please try again.'
+ message: 'Could not add that folder. Try again.'
},
[AI_ERROR_CODES.CONFIG_SAVE_FAILED]: {
severity: 'error',
- message: 'Could not save configuration. Please try again.'
+ message: 'Could not save configuration. Try again.'
},
// ── Batch operations ──
[AI_ERROR_CODES.BATCH_OPERATION_FAILED]: {
@@ -375,16 +375,16 @@ const ERROR_CODE_MAP = {
},
[AI_ERROR_CODES.TIMEOUT]: {
severity: 'warning',
- message: 'Operation timed out. Please try again.'
+ message: 'Operation timed out. Try again.'
},
[AI_ERROR_CODES.SERVICE_UNAVAILABLE]: {
severity: 'warning',
- message: 'A service is temporarily unavailable. Please try again shortly.'
+ message: 'A service is temporarily unavailable. Try again shortly.'
},
// ── Generic ──
[AI_ERROR_CODES.UNKNOWN_ERROR]: {
severity: 'error',
- message: 'Something went wrong. Please try again.'
+ message: 'Something went wrong. Try again.'
},
[AI_ERROR_CODES.OPERATION_CANCELLED]: {
severity: 'info',
@@ -392,7 +392,7 @@ const ERROR_CODE_MAP = {
},
[AI_ERROR_CODES.QUEUE_FULL]: {
severity: 'warning',
- message: 'The processing queue is full. Please wait for current work to finish.'
+ message: 'The processing queue is full. Wait for current work to finish.'
}
};
diff --git a/src/renderer/utils/platform.js b/src/renderer/utils/platform.js
index 20575591..435d60bb 100644
--- a/src/renderer/utils/platform.js
+++ b/src/renderer/utils/platform.js
@@ -23,6 +23,10 @@ export function getPathSeparator() {
return isWindows ? '\\' : '/';
}
+// The separator this platform doesn't use, and runs of the one it does.
+const OTHER_SEPARATOR = isWindows ? /\//g : /\\/g;
+const SEPARATOR_RUN = isWindows ? /\\+/g : /\/+/g;
+
/**
* Join path segments using the platform-specific separator
* Handles both forward and back slashes in input paths
@@ -31,18 +35,17 @@ export function getPathSeparator() {
*/
export function joinPath(...segments) {
const sep = getPathSeparator();
- const otherSep = isWindows ? '/' : '\\';
let result = segments
.filter((s) => s && typeof s === 'string')
- .map((s) => s.replace(new RegExp(`[${otherSep.replace('\\', '\\\\')}]`, 'g'), sep))
+ .map((s) => s.replace(OTHER_SEPARATOR, sep))
.join(sep);
// Preserve UNC path prefix (\\server\share) on Windows before collapsing duplicates
if (isWindows && result.startsWith('\\\\')) {
result = '\\\\' + result.slice(2).replace(/\\+/g, '\\');
} else {
- result = result.replace(new RegExp(`[${sep.replace('\\', '\\\\')}]+`, 'g'), sep);
+ result = result.replace(SEPARATOR_RUN, sep);
}
return result;
@@ -57,16 +60,15 @@ export function normalizePath(inputPath) {
if (!inputPath || typeof inputPath !== 'string') return inputPath;
const sep = getPathSeparator();
- const otherSep = isWindows ? '/' : '\\';
- let normalized = inputPath.replace(new RegExp(`[${otherSep.replace('\\', '\\\\')}]`, 'g'), sep);
+ let normalized = inputPath.replace(OTHER_SEPARATOR, sep);
// Remove duplicate separators (but preserve UNC paths on Windows)
if (isWindows && normalized.startsWith('\\\\')) {
// UNC path - preserve leading \\, normalize the rest
normalized = `\\\\${normalized.slice(2).replace(/\\+/g, '\\')}`;
} else {
- normalized = normalized.replace(new RegExp(`[${sep.replace('\\', '\\\\')}]+`, 'g'), sep);
+ normalized = normalized.replace(SEPARATOR_RUN, sep);
}
return normalized;
diff --git a/src/shared/atomicFileOperations.js b/src/shared/atomicFileOperations.js
index 2c3df204..538e0d74 100644
--- a/src/shared/atomicFileOperations.js
+++ b/src/shared/atomicFileOperations.js
@@ -1108,8 +1108,13 @@ class AtomicFileOperations {
const attemptDestination = finalDestination;
try {
return await this._withDestinationLock(attemptDestination, async () => {
- // Check existence first to prevent silent overwrite (Node's fs.rename overwrites by default)
- if (await this.fileExists(attemptDestination)) {
+ // Check existence first to prevent silent overwrite (Node's fs.rename overwrites by default).
+ // A case-only rename finds the source itself here; that name is
+ // free, or the file would be renamed to `invoice_1.pdf` instead.
+ if (
+ (await this.fileExists(attemptDestination)) &&
+ !(await isCaseOnlyRenameOfSelf(normalizedSource, attemptDestination))
+ ) {
const eexistError = /** @type {NodeJS.ErrnoException} */ (
new Error(
`EEXIST: file already exists, rename '${normalizedSource}' -> '${attemptDestination}'`
@@ -1757,24 +1762,48 @@ class AtomicFileOperations {
for (const id of staleTransactions) {
const transaction = this.activeTransactions.get(id);
- try {
- if (transaction && transaction.status === 'active') {
- // A stale ACTIVE transaction is abandoned mid-flight (caller
- // crashed or hung). Deleting its backups + journal outright would
- // destroy the only rollback material and strand half-applied
- // operations — roll it back first, then clean up.
+ if (!transaction) continue;
+ const status = transaction.status;
+ if (status === 'committed' || status === 'rolled_back') {
+ // Rollback material is no longer needed: remove backups, journal,
+ // and the tracking entry.
+ await this.cleanupBackups(id);
+ continue;
+ }
+ if (status === 'rolling_back') {
+ // A rollback is still in flight and will settle the status; a later
+ // pass handles whatever it ends as.
+ continue;
+ }
+ if (status === 'active') {
+ // A stale ACTIVE transaction is abandoned mid-flight (caller
+ // crashed or hung). Deleting its backups + journal outright would
+ // destroy the only rollback material and strand half-applied
+ // operations — roll it back first, then clean up.
+ try {
await this.rollbackTransaction(id);
+ await this.cleanupBackups(id);
+ continue;
+ } catch (error) {
+ // rollbackTransaction sets 'rolled_back' before it throws; record
+ // the real outcome so the journal is kept for startup recovery.
+ transaction.status = 'rollback_failed';
+ transaction.rollbackFailure = {
+ originalError: 'Stale transaction',
+ rollbackError: error?.message,
+ timestamp: Date.now()
+ };
+ await this.writeJournal(id);
+ logger.warn('[AtomicFileOps] Stale transaction rollback failed', {
+ transactionId: id,
+ error: error?.message
+ });
}
- // Committed / rolled-back / failed: rollback material is no longer
- // needed, cleanup removes backups, journal, and tracking entry.
- await this.cleanupBackups(id);
- } catch (error) {
- logger.warn('[AtomicFileOps] Stale transaction cleanup failed', {
- transactionId: id,
- status: transaction?.status,
- error: error?.message
- });
}
+ // 'rollback_failed' (or unknown): the backups may be the only copy of
+ // what was replaced. Stop tracking it in memory but leave the backups
+ // and journal on disk for recoverFromJournals at the next startup.
+ this.activeTransactions.delete(id);
}
return staleTransactions.length;
@@ -2032,6 +2061,30 @@ async function isDifferentFile(source, dest) {
return destStat.dev !== sourceStat.dev || destStat.ino !== sourceStat.ino;
}
+/**
+ * Whether `dest` is only `source` under a different casing, as it is for a
+ * case-only rename (Invoice.pdf -> invoice.pdf) on a case-insensitive
+ * filesystem: there the existence probe finds the source itself, so the name
+ * is not taken. The stat check (same dev + ino) keeps a case-sensitive volume,
+ * where the other-cased name can be a different file, counted as occupied.
+ * Any stat failure answers false, so callers fall back to "taken".
+ * @param {string} source
+ * @param {string} dest
+ * @returns {Promise}
+ */
+async function isCaseOnlyRenameOfSelf(source, dest) {
+ const normalizedSource = resolveFsPath(source);
+ const normalizedDest = resolveFsPath(dest);
+ if (normalizedSource === normalizedDest) return false;
+ if (!isCaseInsensitiveFileSystem()) return false;
+ if (foldPathForCompare(normalizedSource) !== foldPathForCompare(normalizedDest)) return false;
+ try {
+ return !(await isDifferentFile(normalizedSource, normalizedDest));
+ } catch {
+ return false;
+ }
+}
+
/**
* Rename that refuses to replace an existing destination.
*
@@ -2111,6 +2164,7 @@ module.exports = {
atomicFileOps,
crossDeviceMove,
renameNoReplace,
+ isCaseOnlyRenameOfSelf,
// Shared per-name lock: anything that claims a destination name by
// probe-then-write outside renameNoReplace/atomicMove must take it too.
withPathLock,
diff --git a/src/shared/config/ConfigurationManager.js b/src/shared/config/ConfigurationManager.js
index ba554249..cc816259 100644
--- a/src/shared/config/ConfigurationManager.js
+++ b/src/shared/config/ConfigurationManager.js
@@ -18,6 +18,10 @@
const { CONFIG_SCHEMA, SENSITIVE_KEYS, DEPRECATED_MAPPINGS } = require('./configSchema');
const { parseEnvValue, getEnvVar, validateValue } = require('./configValidation');
+// Path segments override() must never walk into or assign: they reach the
+// object prototype instead of a config value.
+const UNSAFE_PATH_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
+
/**
* Configuration Manager Class
* Manages loading, validation, and access to configuration values.
@@ -263,6 +267,10 @@ class ConfigurationManager {
}
const parts = path.split('.');
+ if (parts.some((part) => UNSAFE_PATH_KEYS.has(part))) {
+ this._validationErrors.push({ path, value, reason: 'unsafe_path' });
+ return;
+ }
// Validate against schema if definition exists (coerce types but allow unrecognized paths)
if (parts.length === 2) {
diff --git a/src/shared/ipcInvokeTimeout.js b/src/shared/ipcInvokeTimeout.js
index a02a6372..2a5d3556 100644
--- a/src/shared/ipcInvokeTimeout.js
+++ b/src/shared/ipcInvokeTimeout.js
@@ -50,6 +50,17 @@ const ANALYZE_BATCH_INVOKE_TIMEOUT_MS =
*/
const FILE_OPERATION_INVOKE_TIMEOUT_MS = 2 ** 31 - 1;
+/**
+ * WHISPER.INSTALL_MODEL answers only once the whole model (~148 MB for
+ * base.en) has downloaded and been checked. On a slow link the 330 s default
+ * fired first: the banner showed "Action failed" while the download, which
+ * ignores the abort, went on and succeeded. The download has no total-time
+ * limit, only a 60 s stall timeout (scripts/setup-whisper-model.js), so any
+ * fixed budget just moves the cutoff; the stall timeout is what guarantees
+ * the request settles.
+ */
+const WHISPER_MODEL_INSTALL_INVOKE_TIMEOUT_MS = FILE_OPERATION_INVOKE_TIMEOUT_MS;
+
/**
* @param {string} channel
* @returns {number} Timeout in milliseconds
@@ -82,6 +93,9 @@ function getIpcInvokeTimeout(channel) {
if (channel === IPC_CHANNELS.FILES.PERFORM_OPERATION) {
timeout = FILE_OPERATION_INVOKE_TIMEOUT_MS;
}
+ if (channel === IPC_CHANNELS.WHISPER.INSTALL_MODEL) {
+ timeout = WHISPER_MODEL_INSTALL_INVOKE_TIMEOUT_MS;
+ }
// Embedding search/scoring operations involve embedding generation through the semaphore
if (
channel === IPC_CHANNELS.EMBEDDINGS.SEARCH ||
@@ -147,5 +161,6 @@ module.exports = {
ANALYZE_BATCH_INVOKE_TIMEOUT_MS,
FILE_OPERATION_INVOKE_TIMEOUT_MS,
VC_RUNTIME_INSTALL_INVOKE_TIMEOUT_MS,
+ WHISPER_MODEL_INSTALL_INVOKE_TIMEOUT_MS,
getIpcInvokeTimeout
};
diff --git a/src/shared/logger.js b/src/shared/logger.js
index abc4d49a..75314445 100644
--- a/src/shared/logger.js
+++ b/src/shared/logger.js
@@ -1146,10 +1146,15 @@ class Logger {
if (this.logFile && this.enableFile) {
streams = [];
+ // Streams accept every level so the pino level alone filters:
+ // setLevel only moves `this.pino.level`, and a stream pinned to the
+ // level at init would keep dropping debug records after a runtime
+ // switch to 'debug'.
+ const streamLevel = 'trace';
try {
const fileStream = _getSharedFileDestination(this.logFile);
this._fileStream = fileStream;
- streams.push({ level: this.level, stream: fileStream });
+ streams.push({ level: streamLevel, stream: fileStream });
} catch (error) {
console.error('[Logger] Failed to open log file stream:', error?.message);
_emitFileError(error);
@@ -1161,16 +1166,16 @@ class Logger {
const prettyFactory = _safeRequire ? _safeRequire('pino-pretty') : null;
if (typeof prettyFactory === 'function') {
const pretty = prettyFactory({ colorize: true });
- streams.push({ level: this.level, stream: pretty });
+ streams.push({ level: streamLevel, stream: pretty });
} else {
throw new Error('pino-pretty not available');
}
} catch (error) {
console.warn('[Logger] pino-pretty unavailable, using stdout:', error?.message);
- streams.push({ level: this.level, stream: process.stdout });
+ streams.push({ level: streamLevel, stream: process.stdout });
}
} else {
- streams.push({ level: this.level, stream: process.stdout });
+ streams.push({ level: streamLevel, stream: process.stdout });
}
}
} else if (isDev) {
diff --git a/src/shared/namingConventions.js b/src/shared/namingConventions.js
index 60b4864f..3ca62b57 100644
--- a/src/shared/namingConventions.js
+++ b/src/shared/namingConventions.js
@@ -7,6 +7,8 @@
* @module shared/namingConventions
*/
+const { isPlausibleContentDate } = require('./contentDateSanity');
+
/**
* Format a date according to the specified format
* @param {Date} date - Date to format
@@ -164,9 +166,10 @@ function generatePreviewName(originalName, settings) {
const { convention, separator, dateFormat, caseConvention } = settings;
const safeSeparator = normalizeSeparator(separator);
- const baseName = originalName.replace(/\.[^/.]+$/, '');
const dotIdx = originalName.lastIndexOf('.');
- const extension = dotIdx > 0 ? originalName.slice(dotIdx) : '';
+ const extension =
+ getCompoundExtension(originalName) || (dotIdx > 0 ? originalName.slice(dotIdx) : '');
+ const baseName = extension ? originalName.slice(0, -extension.length) : originalName;
const today = new Date();
let previewName;
@@ -210,9 +213,12 @@ function generateSuggestedNameFromAnalysis({
const safeOriginalName = String(originalFileName || '').trim();
if (!safeOriginalName) return '';
+ // Keep compound extensions whole: logs.tar.gz renamed must stay a .tar.gz.
const extDotIdx = safeOriginalName.lastIndexOf('.');
- const extension = extDotIdx > 0 ? safeOriginalName.slice(extDotIdx) : '';
- const originalBase = safeOriginalName.replace(/\.[^/.]+$/, '');
+ const extension =
+ getCompoundExtension(safeOriginalName) ||
+ (extDotIdx > 0 ? safeOriginalName.slice(extDotIdx) : '');
+ const originalBase = extension ? safeOriginalName.slice(0, -extension.length) : safeOriginalName;
const convention = settings?.convention || 'keep-original';
const separator = normalizeSeparator(settings?.separator ?? '-');
@@ -286,6 +292,22 @@ function generateSuggestedNameFromAnalysis({
return ms >= MIN_DATE_MS && ms <= MAX_DATE_MS;
};
+ /**
+ * Local midnight of a written year, month and day, or null when they do not
+ * name a real day: new Date(2024, 12, 45) silently rolls over to 2025-02-14.
+ * @param {string} y @param {string} mo @param {string} d @returns {Date|null}
+ */
+ const calendarDate = (y, mo, d) => {
+ const year = Number(y);
+ const month = Number(mo);
+ const day = Number(d);
+ const local = new Date(year, month - 1, day);
+ if (local.getFullYear() !== year || local.getMonth() !== month - 1 || local.getDate() !== day) {
+ return null;
+ }
+ return isReasonableDate(local) ? local : null;
+ };
+
/** @param {any} value @returns {Date|null} */
const parseDateLike = (value) => {
if (!value) return null;
@@ -299,32 +321,31 @@ function generateSuggestedNameFromAnalysis({
if (typeof value !== 'string') return null;
const raw = value.trim();
if (!raw) return null;
- const m = raw.match(/^(\d{4})-(\d{2})-(\d{2})$/);
- if (m) {
- const local = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
- return Number.isNaN(local.getTime()) ? null : local;
- }
- const m2 = raw.match(/^(\d{4})(\d{2})(\d{2})$/);
- if (m2) {
- const local = new Date(Number(m2[1]), Number(m2[2]) - 1, Number(m2[3]));
- return Number.isNaN(local.getTime()) ? null : local;
- }
+ const m = raw.match(/^(\d{4})-(\d{2})-(\d{2})$/) || raw.match(/^(\d{4})(\d{2})(\d{2})$/);
+ if (m) return calendarDate(m[1], m[2], m[3]);
const parsed = new Date(raw);
return Number.isNaN(parsed.getTime()) ? null : parsed;
};
+ // Each written-date form, tried in this order. A date is a whole run of
+ // digits, so an order or tracking number is not read as one; the compact
+ // form may carry a camera time (IMG20240315123456, 17 digits with ms).
+ const FILE_NAME_DATE_PATTERNS = [
+ /(? {
const s = String(nameBase || '');
- const m = s.match(/(\d{4})-(\d{2})-(\d{2})/);
- if (m) {
- const d = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]));
- return Number.isNaN(d.getTime()) ? null : d;
- }
- const m2 = s.match(/(\d{4})(\d{2})(\d{2})/);
- if (m2) {
- const d = new Date(Number(m2[1]), Number(m2[2]) - 1, Number(m2[3]));
- return Number.isNaN(d.getTime()) ? null : d;
+ for (const pattern of FILE_NAME_DATE_PATTERNS) {
+ for (const m of s.matchAll(pattern)) {
+ // A file name date outranks the file's own times, so it must be a
+ // real day in a plausible year (Order 98765432 is not 9880-07-02).
+ if (!isPlausibleContentDate(m[1])) continue;
+ const d = calendarDate(m[1], m[2], m[3]);
+ if (d) return d;
+ }
}
return null;
};
@@ -343,7 +364,7 @@ function generateSuggestedNameFromAnalysis({
const MAX_SUBJECT_LENGTH = 50;
let rawSubject =
typeof analysis?.suggestedName === 'string' && analysis.suggestedName.trim()
- ? analysis.suggestedName.trim().replace(/\.[^/.]+$/, '')
+ ? stripSuggestedNameExtension(analysis.suggestedName.trim(), extension)
: originalBase;
const conventionAddsDate = ['subject-date', 'date-subject', 'project-subject-date'].includes(
@@ -432,6 +453,50 @@ function getCompoundExtension(fileName) {
return '';
}
+// A suffix written as a file type: one case, letters and digits, starting
+// with a letter (.pdf, .MP3). Not ". Smith", "._Louis", ".Smith" or ".1",
+// which are the dots of initials, abbreviations and version numbers.
+const FILE_EXTENSION_LIKE_RE = /^\.(?:[a-z][a-z0-9]{0,9}|[A-Z][A-Z0-9]{0,9})$/;
+
+/**
+ * The extension a typed or suggested name ends with, or '' when the text
+ * after its last dot is part of the name rather than a file type.
+ * @param {any} name
+ * @returns {string}
+ */
+function trailingFileExtension(name) {
+ if (typeof name !== 'string') return '';
+ const dotIdx = name.lastIndexOf('.');
+ if (dotIdx <= 0) return '';
+ const suffix = name.slice(dotIdx);
+ return FILE_EXTENSION_LIKE_RE.test(suffix) ? suffix : '';
+}
+
+/**
+ * A suggested name without its extension: the file's own one (any case), or
+ * else one that reads as a file type. "St._Louis_trip" and "Report_v2.1"
+ * keep their dots.
+ * @param {string} name
+ * @param {string} extension - the original file's extension, compound-aware
+ * @returns {string}
+ */
+function stripSuggestedNameExtension(name, extension) {
+ if (extension) {
+ const ext = extension.toLowerCase();
+ if (name.toLowerCase().endsWith(ext)) {
+ return name.slice(0, -ext.length);
+ }
+ // Fallback names flatten logs.tar.gz to logs_tar.gz; do not keep "tar"
+ // in the subject when the extension re-added is .tar.gz.
+ if (getCompoundExtension(ext)) {
+ const flattened = new RegExp(`[\\s_-]tar\\${ext.slice('.tar'.length)}$`, 'i');
+ if (flattened.test(name)) return name.replace(flattened, '') || name;
+ }
+ }
+ const typed = trailingFileExtension(name);
+ return typed ? name.slice(0, -typed.length) : name;
+}
+
/**
* Extract extension from filename.
* Handles compound extensions (e.g. .tar.gz, .tar.bz2).
@@ -605,6 +670,7 @@ module.exports = {
mainProcessNamingAlreadyApplied,
resolveDiscoverSuggestedName,
extractExtension,
+ trailingFileExtension,
extractFileName,
makeUniqueFileName
};
diff --git a/src/shared/pathSanitization.js b/src/shared/pathSanitization.js
index 6c3d2ced..86e45a4a 100644
--- a/src/shared/pathSanitization.js
+++ b/src/shared/pathSanitization.js
@@ -185,9 +185,13 @@ function sanitizePath(filePath) {
}
const sanitized = processedPath;
- // 2. Unicode normalization (NFD to NFC for consistency)
- // This helps prevent homograph attacks and ensures consistent encoding
- let normalized = sanitized.normalize('NFC');
+ // 2. Unicode normalization (NFD to NFC) on macOS only. APFS/HFS+ look names
+ // up normalization-insensitively, so composing there is harmless. NTFS and
+ // ext4 store the bytes as given: an NFD name (unzipped from a Mac, say) is
+ // a different file from its NFC spelling, and composing it here pointed
+ // every later fs call at a file that does not exist. Comparison keys
+ // (normalizePathForIndex) still compose on every platform.
+ let normalized = PLATFORM === 'darwin' ? sanitized.normalize('NFC') : sanitized;
// 3. Normalize the path first (resolves .., ., etc.)
// This must happen BEFORE the length check so that ".." segments are
@@ -404,9 +408,11 @@ function isPathWithinAllowed(targetPath, allowedBasePaths) {
// Check if target starts with base path
if (normalizedTarget.startsWith(normalizedBase)) {
- // Ensure it's a proper subdirectory (not just a prefix match)
+ // Ensure it's a proper subdirectory (not just a prefix match). A drive
+ // or filesystem root ('D:\', '/') keeps its trailing separator after
+ // normalize, so the prefix already ends on a separator boundary.
const remainder = normalizedTarget.slice(normalizedBase.length);
- if (remainder === '' || remainder.startsWith(path.sep)) {
+ if (remainder === '' || remainder.startsWith(path.sep) || normalizedBase.endsWith(path.sep)) {
return true;
}
}
diff --git a/src/shared/smartFolderNameValidation.js b/src/shared/smartFolderNameValidation.js
index 2956d693..cb57caad 100644
--- a/src/shared/smartFolderNameValidation.js
+++ b/src/shared/smartFolderNameValidation.js
@@ -71,7 +71,7 @@ function validateSmartFolderName(rawName) {
if (ILLEGAL_CHARS.test(sanitizedName)) {
return {
valid: false,
- error: 'Folder name contains invalid characters. Please avoid: < > : " | ? *',
+ error: 'Folder name contains invalid characters: < > : " | ? *',
errorCode: ERROR_CODES.INVALID_FOLDER_NAME_CHARS,
sanitizedName,
warning: null
diff --git a/src/shared/supportInfo.js b/src/shared/supportInfo.js
index fea6b020..75126fe4 100644
--- a/src/shared/supportInfo.js
+++ b/src/shared/supportInfo.js
@@ -118,7 +118,7 @@ function buildVersionString(info) {
*/
function buildSupportMailtoUrl(info = {}) {
const versionLabel = info?.appVersion ? `v${info.appVersion}` : 'unknown version';
- const subject = encodeURIComponent(`StratoSort Stack support — ${versionLabel}`);
+ const subject = encodeURIComponent(`StratoSort Stack support (${versionLabel})`);
const body = encodeURIComponent(buildSupportReportBody(info));
return `mailto:${SUPPORT_EMAIL}?subject=${subject}&body=${body}`;
}
diff --git a/test/AnalysisError.test.js b/test/AnalysisError.test.js
index 5b14ac88..28acdfda 100644
--- a/test/AnalysisError.test.js
+++ b/test/AnalysisError.test.js
@@ -31,7 +31,7 @@ describe('AnalysisError', () => {
const message = error.getUserFriendlyMessage();
const steps = error.getActionableSteps();
expect(message).toContain('AI engine');
- expect(steps).toContain('Check Settings > Models');
+ expect(steps).toContain('Check Settings → Local AI engine');
});
test('model missing error formats message', () => {
diff --git a/test/AnalysisRunProvider.resetRun.test.js b/test/AnalysisRunProvider.resetRun.test.js
new file mode 100644
index 00000000..1467b296
--- /dev/null
+++ b/test/AnalysisRunProvider.resetRun.test.js
@@ -0,0 +1,101 @@
+/**
+ * @jest-environment jsdom
+ *
+ * AnalysisRunProvider hands phases the run's own reset as resetRun. It must
+ * be useAnalysis's resetAnalysisState, which aborts the run and releases its
+ * lock, not useDiscoverState's, which clears only Redux and would leave the
+ * run going unseen.
+ */
+import React from 'react';
+import { render } from '@testing-library/react';
+
+const mockRunReset = jest.fn();
+const mockReduxOnlyReset = jest.fn();
+let mockAnalysisState = { isAnalyzing: false };
+
+jest.mock('react-redux', () => ({
+ useStore: () => ({ getState: () => ({ analysis: mockAnalysisState }) })
+}));
+
+jest.mock('../src/renderer/contexts/NotificationContext', () => ({
+ useNotification: () => ({ addNotification: jest.fn() })
+}));
+
+jest.mock('../src/renderer/phases/discover/useDiscoverState', () => ({
+ useDiscoverState: () => ({
+ selectedFiles: [],
+ analysisResults: [],
+ isAnalyzing: mockAnalysisState.isAnalyzing,
+ analysisProgress: mockAnalysisState.analysisProgress || { current: 0, total: 0 },
+ fileStates: {},
+ namingSettings: {},
+ setIsAnalyzing: jest.fn(),
+ setAnalysisProgress: jest.fn(),
+ setCurrentAnalysisFile: jest.fn(),
+ setAnalysisResults: jest.fn(),
+ setFileStates: jest.fn(),
+ updateFileState: jest.fn(),
+ resetAnalysisState: mockReduxOnlyReset,
+ actions: { setPhaseData: jest.fn(), advancePhase: jest.fn() },
+ getCurrentPhase: () => 'complete'
+ })
+}));
+
+jest.mock('../src/renderer/phases/discover/useAnalysis', () => ({
+ useAnalysis: () => ({
+ analyzeFiles: jest.fn(),
+ cancelAnalysis: jest.fn(),
+ clearAnalysisQueue: jest.fn(),
+ retryFailedFiles: jest.fn(),
+ reanalyzeFiles: jest.fn(),
+ pruneBatchResultsForPath: jest.fn(),
+ resetAnalysisState: mockRunReset
+ })
+}));
+
+import {
+ AnalysisRunProvider,
+ useAnalysisRun
+} from '../src/renderer/phases/discover/AnalysisRunProvider';
+
+afterEach(() => {
+ mockRunReset.mockReset();
+ mockReduxOnlyReset.mockReset();
+ mockAnalysisState = { isAnalyzing: false };
+});
+
+test('resetRun is the run reset from useAnalysis, not the Redux-only one', () => {
+ let run;
+ function Probe() {
+ run = useAnalysisRun();
+ return null;
+ }
+ render(
+
+
+
+ );
+
+ run.resetRun('Analyze more files');
+
+ expect(mockRunReset).toHaveBeenCalledWith('Analyze more files');
+ expect(mockReduxOnlyReset).not.toHaveBeenCalled();
+});
+
+test('the stuck-run watchdog uses the run reset, which keeps finished results', () => {
+ // The Redux-only reset returns the slice to its initial state, which wiped
+ // every result, and left the run's lock held so a retry was refused.
+ mockAnalysisState = {
+ isAnalyzing: true,
+ analysisProgress: { current: 3, total: 10, lastActivity: Date.now() - 6 * 60 * 1000 }
+ };
+ const { unmount } = render(
+
+
+
+ );
+
+ expect(mockRunReset).toHaveBeenCalledWith(expect.stringMatching(/stuck|stalled/i));
+ expect(mockReduxOnlyReset).not.toHaveBeenCalled();
+ unmount();
+});
diff --git a/test/BatchAnalysisService.edge.test.js b/test/BatchAnalysisService.edge.test.js
index 8aa6bb59..bf13f708 100644
--- a/test/BatchAnalysisService.edge.test.js
+++ b/test/BatchAnalysisService.edge.test.js
@@ -140,10 +140,10 @@ describe('BatchAnalysisService (edge)', () => {
for (let i = 0; i < items.length; i++) {
const r = await processor(items[i], i);
results.push(r);
- if (r.success) successful++;
+ if (r?.success) successful++;
if (options?.onProgress)
options.onProgress({ completed: i + 1, total: items.length, percent: 100 });
- if (options?.stopOnError && !r.success) break;
+ if (options?.stopOnError && !r?.success) break;
}
return { results, errors, successful };
});
@@ -203,6 +203,43 @@ describe('BatchAnalysisService (edge)', () => {
}
});
+ // The drain wait used to live on the service singleton and check the run
+ // that created it: cancelling that run made another run's waiting file
+ // return null as if it had been cancelled too.
+ test('cancelling one run during backpressure does not skip another run waiting on it', async () => {
+ jest.useFakeTimers();
+ const startedAt = Date.now();
+ mockAnalysisQueue.getStats.mockImplementation(() =>
+ Date.now() - startedAt < 1200
+ ? { queueLength: 100, capacityPercent: 80, failedItemsCount: 0, deadLetterCount: 0 }
+ : { queueLength: 10, capacityPercent: 40, failedItemsCount: 0, deadLetterCount: 0 }
+ );
+
+ try {
+ const BatchAnalysisService = require('../src/main/services/BatchAnalysisService');
+ const service = new BatchAnalysisService({ concurrency: 1 });
+
+ let cancelA = false;
+ const runA = service.analyzeFiles(['C:\\a.pdf'], [], {
+ concurrency: 1,
+ isCancelled: () => cancelA
+ });
+ const runB = service.analyzeFiles(['C:\\b.pdf'], [], {
+ concurrency: 1,
+ isCancelled: () => false
+ });
+
+ await advance(200);
+ cancelA = true;
+ await advance(3000);
+
+ await expect(runA).resolves.toEqual(expect.objectContaining({ successful: 0 }));
+ await expect(runB).resolves.toEqual(expect.objectContaining({ total: 1, successful: 1 }));
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
test('flushAllEmbeddings failures are tolerated (Promise.allSettled)', async () => {
const { flushAllEmbeddings: flushDocs } = require('../src/main/analysis/documentAnalysis');
const { flushAllEmbeddings: flushImages } = require('../src/main/analysis/imageAnalysis');
diff --git a/test/ChatHistoryStore.search.test.js b/test/ChatHistoryStore.search.test.js
index 46a5be86..2194069c 100644
--- a/test/ChatHistoryStore.search.test.js
+++ b/test/ChatHistoryStore.search.test.js
@@ -81,7 +81,9 @@ function makeFakeDb({ conversations = [], messagesByConv = new Map() } = {}) {
);
}
// Per-conversation messages for the decrypt scan
- if (trimmed.startsWith('SELECT document_answer, model_answer, meta FROM messages')) {
+ if (
+ trimmed.startsWith('SELECT document_answer, model_answer, follow_ups FROM messages')
+ ) {
return messagesByConv.get(args[0]) || [];
}
throw new Error(`Unhandled SQL in fake db: ${trimmed}`);
@@ -186,7 +188,7 @@ describe('ChatHistoryStore — searchConversations after encryption rollout', ()
expect(results.items.map((r) => r.id)).toContain('c3');
});
- test('finds matches in encrypted modelAnswer + meta', () => {
+ test('finds matches in encrypted modelAnswer and follow-ups', () => {
const conv = {
id: 'c4',
title: 'Internal',
@@ -201,7 +203,7 @@ describe('ChatHistoryStore — searchConversations after encryption rollout', ()
model_answer: encrypt(
JSON.stringify([{ text: 'I would recommend SAML SSO over OAuth here.' }])
),
- meta: encrypt(JSON.stringify({ topic: 'authentication-strategy' }))
+ follow_ups: encrypt(JSON.stringify(['Compare authentication-strategy options']))
}
];
const store = buildStore({
@@ -215,6 +217,36 @@ describe('ChatHistoryStore — searchConversations after encryption rollout', ()
);
});
+ test('JSON keys and metadata do not match every conversation', () => {
+ // Stage 2 used to substring-match the serialized JSON, so a key like
+ // "text" or "mode" (or retrieval meta) matched every stored answer.
+ const conv = {
+ id: 'c5',
+ title: 'Internal',
+ document_scope: '[]',
+ created_at: 't5',
+ updated_at: 't5'
+ };
+ const msgs = [
+ {
+ text: 'unrelated',
+ document_answer: encrypt(JSON.stringify([{ text: 'Rent is due monthly.', citations: [] }])),
+ model_answer: encrypt(JSON.stringify([{ text: 'Nothing else to add.' }])),
+ follow_ups: encrypt(JSON.stringify([])),
+ meta: encrypt(JSON.stringify({ mode: 'hybrid', queryMeta: { searchResult: 1 } }))
+ }
+ ];
+ const store = buildStore({
+ conversations: [conv],
+ messagesByConv: new Map([['c5', msgs]])
+ });
+
+ for (const term of ['text', 'citations', 'mode', 'hybrid', 'search', 'result']) {
+ expect(store.searchConversations(term).items).toEqual([]);
+ }
+ expect(store.searchConversations('rent is due').items.map((r) => r.id)).toEqual(['c5']);
+ });
+
test('case-insensitive match across both stages', () => {
const c1 = {
id: 'c1',
@@ -445,3 +477,36 @@ describe('ChatHistoryStore — searchConversations after encryption rollout', ()
});
});
});
+
+describe('ChatHistoryStore — LIKE pattern escaping', () => {
+ // The SQL stage runs `LIKE ? ESCAPE '\'`. The escape character itself has
+ // to be escaped too, or "C:\Users" turns "\U" into a literal "U" and a
+ // message with the real path no longer matches.
+ function patternFor(query) {
+ const fake = makeFakeDb();
+ const prepare = fake.prepare.bind(fake);
+ /** @type {string[]} */
+ const seen = [];
+ fake.prepare = (sql) => {
+ const statement = prepare(sql);
+ const all = statement.all;
+ statement.all = (...args) => {
+ if (String(sql).includes('LIKE ?')) seen.push(String(args[0]));
+ return all(...args);
+ };
+ return statement;
+ };
+ const store = buildStore({ conversations: [], messagesByConv: new Map() });
+ store._db = fake;
+ store.searchConversations(query);
+ return seen[0];
+ }
+
+ test.each([
+ ['a backslash', 'C:\\Users', '%C:\\\\Users%'],
+ ['LIKE wildcards', '50%_off', '%50\\%\\_off%'],
+ ['a trailing backslash', 'folder\\', '%folder\\\\%']
+ ])('escapes %s', (_label, query, expected) => {
+ expect(patternFor(query)).toBe(expected);
+ });
+});
diff --git a/test/ChatService.cancelDuringRetrieval.test.js b/test/ChatService.cancelDuringRetrieval.test.js
new file mode 100644
index 00000000..0a27ed64
--- /dev/null
+++ b/test/ChatService.cancelDuringRetrieval.test.js
@@ -0,0 +1,172 @@
+/**
+ * A Stop or a conversation delete while chat is still retrieving sources must
+ * not persist anything. Retrieval ignores the stream signal, so the cancel
+ * used to surface later as the local queue's INFERENCE_SLOT_ABORTED (a plain
+ * Error, not an AbortError). The catch then saved an "Error: Inference slot
+ * aborted..." turn and, for a deleted conversation, recreated it.
+ */
+
+jest.mock('../src/shared/logger', () => ({
+ createLogger: () => ({
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn()
+ })
+}));
+
+const ChatService = require('../src/main/services/ChatService');
+
+function slotAbortedError() {
+ const err = new Error('Inference slot aborted before queuing (text)');
+ err.code = 'INFERENCE_SLOT_ABORTED';
+ return err;
+}
+
+function makeService({ generate } = {}) {
+ const store = {
+ initialize: jest.fn(async () => undefined),
+ // The conversation was deleted (or never existed yet).
+ getConversation: jest.fn(() => null),
+ createConversation: jest.fn(),
+ addMessage: jest.fn(),
+ updateTitle: jest.fn()
+ };
+ const llamaService = {
+ generateTextStreaming: jest.fn(
+ generate ||
+ (async () => {
+ throw slotAbortedError();
+ })
+ )
+ };
+ const service = new ChatService({ llamaService, chatHistoryStore: store });
+ jest.spyOn(service, '_resolveGenerateBackend').mockReturnValue(null);
+ return { service, store, llamaService };
+}
+
+function deferredRetrieval(service, sessionId) {
+ let resolve;
+ const pending = new Promise((r) => {
+ resolve = r;
+ });
+ jest.spyOn(service, '_runRetrieval').mockImplementation(async () => {
+ await pending;
+ return {
+ retrieval: { sources: [], meta: {} },
+ prompt: 'p',
+ memory: { sessionId, _lines: [] }
+ };
+ });
+ return () => resolve();
+}
+
+function expectNothingPersisted(store) {
+ expect(store.createConversation).not.toHaveBeenCalled();
+ expect(store.addMessage).not.toHaveBeenCalled();
+}
+
+describe('ChatService.queryStreaming cancel while retrieving', () => {
+ test('Stop during retrieval saves no error turn and reports a cancel', async () => {
+ const { service, store, llamaService } = makeService();
+ const finishRetrieval = deferredRetrieval(service, 'conv-1');
+ const events = [];
+ const run = service.queryStreaming({
+ sessionId: 'conv-1',
+ requestId: 'r1',
+ query: 'what does the lease say about pets?',
+ onEvent: (evt) => events.push(evt)
+ });
+
+ await service.cancelStreamingRequest({ requestId: 'r1' });
+ finishRetrieval();
+ await run;
+
+ expectNothingPersisted(store);
+ expect(llamaService.generateTextStreaming).not.toHaveBeenCalled();
+ expect(events.filter((e) => e.type === 'error')).toEqual([
+ { type: 'error', error: 'Generation canceled' }
+ ]);
+ });
+
+ test('deleting the conversation during retrieval does not recreate it, even with strictScope', async () => {
+ const { service, store } = makeService();
+ const finishRetrieval = deferredRetrieval(service, 'conv-2');
+ const run = service.queryStreaming({
+ sessionId: 'conv-2',
+ requestId: 'r2',
+ query: 'summarize the selected contract',
+ strictScope: true,
+ onEvent: () => {}
+ });
+
+ await service.resetSession('conv-2');
+ finishRetrieval();
+ await run;
+
+ expectNothingPersisted(store);
+ });
+
+ test('a slot-aborted error after a cancel during generation saves nothing', async () => {
+ const { service, store } = makeService({
+ generate: async () => {
+ await service.cancelStreamingRequest({ requestId: 'r3' });
+ throw slotAbortedError();
+ }
+ });
+ deferredRetrieval(service, 'conv-3')();
+ const events = [];
+ await service.queryStreaming({
+ sessionId: 'conv-3',
+ requestId: 'r3',
+ query: 'what does the lease say about pets?',
+ onEvent: (evt) => events.push(evt)
+ });
+
+ expectNothingPersisted(store);
+ expect(events.find((e) => e.type === 'error')?.error).toBe('Generation canceled');
+ });
+
+ test('a real generation failure still saves the error turn', async () => {
+ const { service, store } = makeService({
+ generate: async () => {
+ throw new Error('model crashed');
+ }
+ });
+ deferredRetrieval(service, 'conv-4')();
+ const events = [];
+ await service.queryStreaming({
+ sessionId: 'conv-4',
+ requestId: 'r4',
+ query: 'what does the lease say about pets?',
+ onEvent: (evt) => events.push(evt)
+ });
+
+ const assistantRows = store.addMessage.mock.calls
+ .map(([, msg]) => msg)
+ .filter((m) => m.role === 'assistant');
+ expect(assistantRows).toHaveLength(1);
+ expect(assistantRows[0].modelAnswer[0].text).toContain('model crashed');
+ expect(events.find((e) => e.type === 'error')?.error).toBe('model crashed');
+ });
+
+ test('the conversational path reports a cancel, not a failure', async () => {
+ const { service, store } = makeService({
+ generate: async () => {
+ await service.cancelStreamingRequest({ requestId: 'r5' });
+ throw slotAbortedError();
+ }
+ });
+ jest.spyOn(service, '_isConversational').mockReturnValue(true);
+ const events = [];
+ await service.queryStreaming({
+ sessionId: 'conv-5',
+ requestId: 'r5',
+ query: 'hello there',
+ onEvent: (evt) => events.push(evt)
+ });
+
+ expect(store.addMessage).not.toHaveBeenCalled();
+ expect(events.find((e) => e.type === 'error')?.error).toBe('Generation canceled');
+ });
+});
diff --git a/test/ChatService.contextFileLimit.test.js b/test/ChatService.contextFileLimit.test.js
new file mode 100644
index 00000000..c4724b2c
--- /dev/null
+++ b/test/ChatService.contextFileLimit.test.js
@@ -0,0 +1,71 @@
+/**
+ * @jest-environment node
+ *
+ * The chat IPC schema and the renderer allow 1000 scoped documents, but
+ * context scoring used to stop at 200, so in Strict scope files 201+ were
+ * never searched.
+ */
+
+const mockLogger = {
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn()
+};
+jest.mock('../src/shared/logger', () => ({
+ createLogger: () => mockLogger
+}));
+
+const ChatService = require('../src/main/services/ChatService');
+
+function makeService() {
+ const vectorDbService = {
+ initialize: jest.fn(async () => undefined),
+ getCollectionDimension: jest.fn(async () => 2),
+ // Only the last selected file is on topic.
+ getFile: jest.fn(async (id) => ({
+ filePath: `/${id}.txt`,
+ fileName: `${id}.txt`,
+ embedding: id === 'f1000' ? [1, 0] : [0, 1]
+ }))
+ };
+ const embeddingService = { embedText: jest.fn(async () => ({ vector: [1, 0] })) };
+ const service = new ChatService({
+ searchService: { hybridSearch: jest.fn() },
+ vectorDbService,
+ embeddingService,
+ chatHistoryStore: null
+ });
+ return { service, vectorDbService };
+}
+
+const ids = (n) => Array.from({ length: n }, (_, i) => `f${i + 1}`);
+
+describe('ChatService context-file limit', () => {
+ beforeEach(() => jest.clearAllMocks());
+
+ test('scores all 1000 files the IPC schema allows', async () => {
+ const { service, vectorDbService } = makeService();
+
+ const scored = await service._retrieval.scoreContextFiles('pets', ids(1000));
+
+ expect(vectorDbService.getFile).toHaveBeenCalledTimes(1000);
+ expect(scored.find((r) => r.id === 'f1000')?.score).toBeCloseTo(1);
+ expect(mockLogger.warn).not.toHaveBeenCalledWith(
+ expect.stringContaining('over the limit'),
+ expect.anything()
+ );
+ });
+
+ test('logs when a scope over the limit is truncated', async () => {
+ const { service, vectorDbService } = makeService();
+
+ await service._retrieval.scoreContextFiles('pets', ids(1005));
+
+ expect(vectorDbService.getFile).toHaveBeenCalledTimes(1000);
+ expect(mockLogger.warn).toHaveBeenCalledWith(
+ expect.stringContaining('over the limit'),
+ expect.objectContaining({ requested: 1005, limit: 1000 })
+ );
+ });
+});
diff --git a/test/ClusteringService.userLabels.test.js b/test/ClusteringService.userLabels.test.js
new file mode 100644
index 00000000..2c5f5f04
--- /dev/null
+++ b/test/ClusteringService.userLabels.test.js
@@ -0,0 +1,184 @@
+/**
+ * Cluster names the user gives must survive a restart and stay with the same
+ * files when k-means renumbers clusters on a recompute.
+ */
+
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+
+jest.mock('../src/shared/logger', () => {
+ const logger = {
+ setContext: jest.fn(),
+ info: jest.fn(),
+ debug: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn()
+ };
+ return { logger, createLogger: jest.fn(() => logger) };
+});
+
+jest.mock('../src/main/llamaUtils', () => ({
+ getTextModel: jest.fn(() => 'test-model')
+}));
+
+let mockUserDataDir = '';
+jest.mock('electron', () => ({
+ app: { getPath: jest.fn(() => mockUserDataDir) }
+}));
+
+const { ClusteringService } = require('../src/main/services/ClusteringService');
+
+const LABELS_FILE = 'cluster-user-labels.json';
+
+/** Files whose ids name the group they belong to; embeddings are unused because kmeans is stubbed. */
+const makeFiles = (/** @type {string[]} */ ids) =>
+ ids.map((id) => ({ id, embedding: [1, 0, 0], metadata: { name: `${id}.txt` } }));
+
+/**
+ * A service whose next computeClusters groups files exactly as given.
+ * @param {string[][]} groups
+ */
+function stubClustering(/** @type {any} */ service, groups) {
+ const ids = groups.flat();
+ const assignments = [];
+ groups.forEach((group, clusterIdx) => group.forEach(() => assignments.push(clusterIdx)));
+ service.getAllFileEmbeddings = jest.fn(async () => makeFiles(ids));
+ service.kmeans = jest.fn(() => ({
+ assignments,
+ centroids: groups.map(() => [1, 0, 0])
+ }));
+}
+
+const newService = () =>
+ new ClusteringService({ vectorDbService: { peekFiles: jest.fn() }, llamaService: null });
+
+const labelsById = (/** @type {any} */ service) =>
+ Object.fromEntries(service.getClustersForGraph().map((c) => [c.id, c.label]));
+
+describe('ClusteringService user cluster names', () => {
+ beforeEach(() => {
+ mockUserDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'cluster-labels-'));
+ });
+
+ afterEach(() => {
+ fs.rmSync(mockUserDataDir, { recursive: true, force: true });
+ });
+
+ const taxes = ['tax-1', 'tax-2', 'tax-3', 'tax-4'];
+ const photos = ['photo-1', 'photo-2', 'photo-3', 'photo-4'];
+
+ test('a rename is loaded again after a restart', async () => {
+ const first = newService();
+ stubClustering(first, [photos, taxes]);
+ await first.computeClusters(2);
+ await first.renameCluster('cluster:1', 'Taxes', path.join(mockUserDataDir, LABELS_FILE));
+
+ // A new service is what the app has after a restart
+ const second = newService();
+ stubClustering(second, [photos, taxes]);
+ await second.computeClusters(2);
+
+ expect(labelsById(second)['cluster:1']).toBe('Taxes');
+ });
+
+ test('the name follows its files when the cluster indices change', async () => {
+ const service = newService();
+ stubClustering(service, [photos, taxes]);
+ await service.computeClusters(2);
+ await service.renameCluster('cluster:1', 'Taxes', path.join(mockUserDataDir, LABELS_FILE));
+
+ // Recompute puts the photos at index 1 and the tax files at index 0
+ stubClustering(service, [taxes, photos]);
+ await service.computeClusters(2);
+
+ const labels = labelsById(service);
+ expect(labels['cluster:0']).toBe('Taxes');
+ expect(labels['cluster:1']).not.toBe('Taxes');
+ });
+
+ test('the name is not shown on a cluster that now holds mostly other files', async () => {
+ const service = newService();
+ stubClustering(service, [photos, taxes]);
+ await service.computeClusters(2);
+ await service.renameCluster('cluster:1', 'Taxes', path.join(mockUserDataDir, LABELS_FILE));
+
+ // Two tax files were removed and the other two landed among new files:
+ // overlaps 1/9 and 1/5, both below the bar
+ const others = ['note-1', 'note-2', 'note-3', 'note-4', 'note-5', 'note-6'];
+ stubClustering(service, [photos, ['tax-1', ...others.slice(0, 5)], ['tax-2', 'note-6']]);
+ await service.computeClusters(3);
+
+ expect(Object.values(labelsById(service))).not.toContain('Taxes');
+ });
+
+ test('a group that grows step by step keeps its name', async () => {
+ const service = newService();
+ stubClustering(service, [photos, taxes]);
+ await service.computeClusters(2);
+ await service.renameCluster('cluster:1', 'Taxes', path.join(mockUserDataDir, LABELS_FILE));
+
+ // Each step keeps the overlap above half, though the last group shares
+ // only 4 of 9 files with the one that was renamed.
+ stubClustering(service, [photos, [...taxes, 'tax-5', 'tax-6']]);
+ await service.computeClusters(2);
+ stubClustering(service, [photos, [...taxes, 'tax-5', 'tax-6', 'tax-7', 'tax-8', 'tax-9']]);
+ await service.computeClusters(2);
+
+ expect(labelsById(service)['cluster:1']).toBe('Taxes');
+ });
+
+ test('a rename in a later session keeps names saved earlier', async () => {
+ const filePath = path.join(mockUserDataDir, LABELS_FILE);
+ const first = newService();
+ stubClustering(first, [photos, taxes]);
+ await first.computeClusters(2);
+ await first.renameCluster('cluster:0', 'Photos', filePath);
+
+ // After a restart, a new rename must not overwrite the earlier name in the file
+ const second = newService();
+ stubClustering(second, [photos, taxes]);
+ await second.computeClusters(2);
+ await second.renameCluster('cluster:1', 'Taxes', filePath);
+
+ const saved = JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ expect(saved.labels.map((/** @type {any} */ e) => e.label).sort()).toEqual(['Photos', 'Taxes']);
+ });
+
+ test('renaming a cluster again replaces its saved name', async () => {
+ const filePath = path.join(mockUserDataDir, LABELS_FILE);
+ const service = newService();
+ stubClustering(service, [photos, taxes]);
+ await service.computeClusters(2);
+ await service.renameCluster('cluster:1', 'Taxes', filePath);
+ await service.renameCluster('cluster:1', 'Tax returns', filePath);
+
+ const saved = JSON.parse(fs.readFileSync(filePath, 'utf8'));
+ expect(saved.labels).toHaveLength(1);
+ expect(saved.labels[0].label).toBe('Tax returns');
+ expect(labelsById(service)['cluster:1']).toBe('Tax returns');
+ });
+
+ test('index-keyed names from an older file are not applied to new clusters', async () => {
+ fs.writeFileSync(
+ path.join(mockUserDataDir, LABELS_FILE),
+ JSON.stringify({ 'cluster:1': 'Old' })
+ );
+ const service = newService();
+ stubClustering(service, [photos, taxes]);
+ await service.computeClusters(2);
+
+ expect(Object.values(labelsById(service))).not.toContain('Old');
+ });
+
+ test('renaming a cluster that no longer exists fails instead of storing it by index', async () => {
+ const service = newService();
+ stubClustering(service, [photos, taxes]);
+ await service.computeClusters(2);
+
+ await expect(
+ service.renameCluster('cluster:7', 'Taxes', path.join(mockUserDataDir, LABELS_FILE))
+ ).rejects.toThrow('Cluster not found');
+ expect(fs.existsSync(path.join(mockUserDataDir, LABELS_FILE))).toBe(false);
+ });
+});
diff --git a/test/CompletePhase.analyzeMoreFiles.test.js b/test/CompletePhase.analyzeMoreFiles.test.js
new file mode 100644
index 00000000..6c07fdbd
--- /dev/null
+++ b/test/CompletePhase.analyzeMoreFiles.test.js
@@ -0,0 +1,100 @@
+/**
+ * @jest-environment jsdom
+ *
+ * The analysis run lives above the phases, so the user can reach Complete
+ * while later files are still analyzing. "Analyze more files" used to clear
+ * only Redux: the run kept going unseen, with no progress card or Stop
+ * button, and the next files were queued behind it. It now resets the run
+ * itself before clearing the batch.
+ */
+import React from 'react';
+import { render, screen, fireEvent } from '@testing-library/react';
+import '@testing-library/jest-dom';
+
+const mockCalls = [];
+
+jest.mock('../src/renderer/store/hooks', () => ({
+ useAppDispatch: () => (action) => mockCalls.push(action),
+ useAppSelector: (selector) =>
+ selector({
+ files: {
+ organizedFiles: [{ originalName: 'invoice.pdf', path: '/dest/finance/invoice.pdf' }],
+ organizedPathIndex: []
+ },
+ analysis: { results: [] }
+ })
+}));
+
+jest.mock('../src/renderer/store/selectors', () => {
+ const actual = jest.requireActual('../src/renderer/store/selectors');
+ return {
+ selectRedactPaths: () => false,
+ selectOrganizedCount: actual.selectOrganizedCount,
+ selectMovedCount: actual.selectMovedCount
+ };
+});
+
+jest.mock('../src/renderer/store/slices/uiSlice', () => ({
+ setPhase: (phase) => `setPhase:${phase}`,
+ resetUi: () => 'resetUi'
+}));
+jest.mock('../src/renderer/store/slices/filesSlice', () => ({
+ resetFilesState: () => 'resetFilesState'
+}));
+jest.mock('../src/renderer/store/slices/analysisSlice', () => ({
+ resetAnalysisState: () => 'resetAnalysisState'
+}));
+jest.mock('../src/renderer/store/middleware/persistenceMiddleware', () => ({
+ cancelPendingPersistence: jest.fn()
+}));
+
+const mockResetRun = jest.fn((reason) => mockCalls.push(`resetRun:${reason}`));
+jest.mock('../src/renderer/phases/discover/AnalysisRunProvider', () => ({
+ useAnalysisRun: () => ({ resetRun: mockResetRun })
+}));
+
+jest.mock('../src/renderer/components/UndoRedoSystem', () => ({
+ UndoRedoToolbar: () => null
+}));
+jest.mock('framer-motion', () => ({
+ motion: { div: ({ children, className }) =>
{children}
},
+ useReducedMotion: () => true
+}));
+jest.mock('../src/renderer/hooks/useFileActions', () => ({
+ useFileActions: () => ({ revealFile: jest.fn() })
+}));
+jest.mock('../src/renderer/contexts/NotificationContext', () => ({
+ useNotification: () => ({
+ showError: jest.fn(),
+ showInfo: jest.fn(),
+ showSuccess: jest.fn(),
+ showWarning: jest.fn()
+ })
+}));
+jest.mock('../src/renderer/services/ipc', () => ({
+ filesIpc: { openFolder: jest.fn(), exportOrganizeReport: jest.fn() }
+}));
+
+import CompletePhase from '../src/renderer/phases/CompletePhase';
+
+describe('CompletePhase "Analyze more files"', () => {
+ beforeEach(() => {
+ mockCalls.length = 0;
+ mockResetRun.mockClear();
+ });
+
+ test('resets the analysis run before clearing the batch', () => {
+ render();
+ fireEvent.click(screen.getByText(/Analyze more files/i));
+
+ expect(mockResetRun).toHaveBeenCalledTimes(1);
+ // First, so the run's own final writes land before Redux is cleared.
+ expect(mockCalls).toEqual([
+ 'resetRun:Analyze more files',
+ 'resetUi',
+ 'resetFilesState',
+ 'resetAnalysisState',
+ 'setPhase:discover'
+ ]);
+ });
+});
diff --git a/test/DataMigrationService.test.js b/test/DataMigrationService.test.js
index 10a10cf8..a9d49360 100644
--- a/test/DataMigrationService.test.js
+++ b/test/DataMigrationService.test.js
@@ -20,6 +20,11 @@ jest.mock('../src/shared/logger', () => ({
})
}));
+const mockLoadSettings = jest.fn(async () => ({}));
+jest.mock('../src/main/services/SettingsService', () => ({
+ getInstance: () => ({ load: mockLoadSettings })
+}));
+
const fs = require('fs').promises;
const { app } = require('electron');
const path = require('path');
@@ -57,6 +62,35 @@ describe('DataMigrationService', () => {
});
});
+ describe('legacy name used as the live vector folder', () => {
+ afterEach(() => {
+ mockLoadSettings.mockResolvedValue({});
+ fs.access.mockReset();
+ fs.rm.mockReset();
+ });
+
+ test('migrate keeps it and still removes the other legacy paths', async () => {
+ mockLoadSettings.mockResolvedValue({ vectorDbPersistPath: 'vector_storage' });
+ fs.access.mockResolvedValue(undefined);
+ fs.rm.mockResolvedValue(undefined);
+
+ await svc.migrate();
+
+ const removed = fs.rm.mock.calls.map(([p]) => path.basename(p));
+ expect(removed).not.toContain('vector_storage');
+ expect(removed).toContain('chroma_db');
+ });
+
+ test('needsMigration ignores it', async () => {
+ mockLoadSettings.mockResolvedValue({ vectorDbPersistPath: 'chroma_db' });
+ fs.access.mockImplementation(async (p) => {
+ if (path.basename(p) !== 'chroma_db') throw Object.assign(new Error(), { code: 'ENOENT' });
+ });
+
+ await expect(svc.needsMigration()).resolves.toBe(false);
+ });
+ });
+
describe('migrate', () => {
test('deletes legacy data and reports success', async () => {
// Setup: access succeeds for one path, fails for others
diff --git a/test/DownloadWatcher.moveIndexSync.test.js b/test/DownloadWatcher.moveIndexSync.test.js
new file mode 100644
index 00000000..0a487fc5
--- /dev/null
+++ b/test/DownloadWatcher.moveIndexSync.test.js
@@ -0,0 +1,254 @@
+/**
+ * @jest-environment node
+ *
+ * Under the default 'during_analysis' timing the analysis pass indexes a
+ * download under its Downloads path. The watcher then moves (or renames) the
+ * file itself, and both watchers ignore their own tracked moves, so nothing
+ * re-keyed that vector: the old id stayed behind, the organized file had no
+ * vector at its real path and its history said embedding 'skipped'.
+ */
+
+const mockFs = {
+ stat: jest.fn().mockResolvedValue({
+ isDirectory: () => false,
+ size: 100,
+ birthtime: new Date('2026-11-01T00:00:00Z'),
+ mtime: new Date('2026-11-01T00:00:00Z')
+ }),
+ access: jest.fn().mockResolvedValue(undefined),
+ mkdir: jest.fn().mockResolvedValue(undefined),
+ rename: jest.fn().mockResolvedValue(undefined)
+};
+jest.mock('fs', () => ({ promises: mockFs, constants: { R_OK: 4 } }));
+
+jest.mock('chokidar', () => ({
+ watch: jest.fn().mockReturnValue({ on: jest.fn().mockReturnThis(), close: jest.fn() })
+}));
+
+jest.mock('../src/shared/logger', () => {
+ const logger = {
+ setContext: jest.fn(),
+ info: jest.fn(),
+ debug: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn()
+ };
+ return { logger, createLogger: jest.fn(() => logger) };
+});
+
+jest.mock('../src/shared/atomicFileOperations', () => ({
+ crossDeviceMove: jest.fn().mockResolvedValue(undefined),
+ renameNoReplace: jest.fn().mockResolvedValue(undefined)
+}));
+
+jest.mock('../src/shared/fileOperationTracker', () => ({
+ getInstance: jest.fn(() => ({
+ wasRecentlyOperated: jest.fn().mockReturnValue(false),
+ recordOperation: jest.fn()
+ }))
+}));
+
+// Default settings: the analysis pass embeds, the final stage does not.
+jest.mock('../src/main/services/embedding/embeddingGate', () => ({
+ shouldEmbed: jest
+ .fn()
+ .mockResolvedValue({ shouldEmbed: false, timing: 'during_analysis', policy: 'embed' })
+}));
+
+jest.mock('../src/main/ipc/analysisUtils', () => ({
+ recordAnalysisResult: jest.fn().mockResolvedValue(undefined)
+}));
+
+jest.mock('../src/main/services/autoOrganize/namingUtils', () => ({
+ generateSuggestedNameFromAnalysis: jest.fn(() => 'invoice-2026-11-01')
+}));
+
+const mockSearchService = { invalidateIndex: jest.fn() };
+jest.mock('../src/main/ipc/semantic', () => ({
+ getSearchServiceInstance: jest.fn(() => mockSearchService)
+}));
+
+const path = require('path');
+const { recordAnalysisResult } = require('../src/main/ipc/analysisUtils');
+const { getSemanticFileId } = require('../src/shared/fileIdUtils');
+const DownloadWatcher = require('../src/main/services/DownloadWatcher');
+
+const FINANCE = { id: 'f1', name: 'Finance', path: path.resolve('/smart/Finance') };
+const SOURCE = path.resolve('/downloads/invoice.pdf');
+const DEST = path.join(FINANCE.path, 'invoice-2026-11-01.pdf');
+
+function handoffFor(filePath) {
+ return {
+ vector: [0.1, 0.2],
+ model: 'embed-model',
+ meta: { path: filePath },
+ wasEnqueued: true,
+ chunksEmbedded: true
+ };
+}
+
+function makeWatcher({ coordinator, vectorRow = null } = {}) {
+ const calls = [];
+ const filePathCoordinator =
+ coordinator === undefined
+ ? {
+ atomicPathUpdate: jest.fn(async (oldPath, newPath) => {
+ calls.push(['atomicPathUpdate', oldPath, newPath]);
+ return { success: true, errors: [], updated: { vectorDb: true } };
+ })
+ }
+ : coordinator;
+ recordAnalysisResult.mockImplementation(async ({ filePath }) => {
+ calls.push(['recordAnalysisResult', filePath]);
+ });
+ const analysisHistoryService = {
+ getAnalysisByPath: jest.fn().mockResolvedValue({ embedding: { status: null } }),
+ updateEmbeddingStateByPath: jest.fn().mockResolvedValue(undefined)
+ };
+ const vectorDbService = {
+ getFile: jest.fn().mockResolvedValue(vectorRow),
+ upsertFile: jest.fn()
+ };
+ const watcher = new DownloadWatcher({
+ analyzeDocumentFile: jest.fn(),
+ analyzeImageFile: jest.fn(),
+ getCustomFolders: jest.fn(() => [FINANCE]),
+ autoOrganizeService: { processNewFile: jest.fn() },
+ settingsService: { load: jest.fn().mockResolvedValue({ autoOrganize: true }) },
+ analysisHistoryService,
+ vectorDbService,
+ folderMatcher: { embedText: jest.fn() },
+ filePathCoordinator
+ });
+ watcher._ensureDirectory = jest.fn().mockResolvedValue(undefined);
+ return { watcher, filePathCoordinator, analysisHistoryService, vectorDbService, calls };
+}
+
+function autoOrganizeResult() {
+ const analysis = { summary: 'An invoice', subject: 'Invoice', category: 'Finance' };
+ return {
+ source: SOURCE,
+ destination: DEST,
+ analysis: { ...analysis, _embeddingForPersistence: handoffFor(SOURCE) },
+ confidence: 0.9
+ };
+}
+
+describe('DownloadWatcher re-keys the analysis index after its own move', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ });
+
+ test('auto-organize moves the vector, chunks and queue item to the destination', async () => {
+ const { watcher, filePathCoordinator, calls } = makeWatcher();
+ watcher.autoOrganizeService.processNewFile.mockResolvedValue(autoOrganizeResult());
+
+ await watcher._attemptAutoOrganize(SOURCE);
+
+ expect(filePathCoordinator.atomicPathUpdate).toHaveBeenCalledWith(SOURCE, DEST, {
+ type: 'move',
+ folderMeta: { newSmartFolder: 'Finance', newSmartFolderPath: FINANCE.path }
+ });
+ // Before history is written, so the destination entry is the one that stays.
+ const order = calls.map((c) => c[0]);
+ expect(order.indexOf('atomicPathUpdate')).toBeLessThan(order.indexOf('recordAnalysisResult'));
+ expect(mockSearchService.invalidateIndex).toHaveBeenCalledWith(
+ expect.objectContaining({ oldPath: SOURCE, newPath: DEST })
+ );
+ });
+
+ test('the moved file is marked done, not skipped, when its row is already at the new id', async () => {
+ const { watcher, analysisHistoryService, vectorDbService } = makeWatcher({
+ vectorRow: { id: 'x' }
+ });
+ watcher.autoOrganizeService.processNewFile.mockResolvedValue(autoOrganizeResult());
+
+ await watcher._attemptAutoOrganize(SOURCE);
+
+ expect(vectorDbService.getFile).toHaveBeenCalledWith(getSemanticFileId(DEST));
+ expect(analysisHistoryService.updateEmbeddingStateByPath).toHaveBeenCalledWith(DEST, {
+ status: 'done'
+ });
+ expect(analysisHistoryService.updateEmbeddingStateByPath).not.toHaveBeenCalledWith(
+ DEST,
+ expect.objectContaining({ status: 'skipped' })
+ );
+ // The analysis vector is reused, not computed again.
+ expect(vectorDbService.upsertFile).not.toHaveBeenCalled();
+ });
+
+ test('a vector still queued leaves the moved file pending', async () => {
+ const { watcher, analysisHistoryService } = makeWatcher({ vectorRow: null });
+ watcher.autoOrganizeService.processNewFile.mockResolvedValue(autoOrganizeResult());
+
+ await watcher._attemptAutoOrganize(SOURCE);
+
+ expect(analysisHistoryService.updateEmbeddingStateByPath).toHaveBeenCalledWith(DEST, {
+ status: 'pending',
+ model: 'embed-model'
+ });
+ });
+
+ test('without a coordinator the move still completes and history keeps the old skipped state', async () => {
+ const { watcher, analysisHistoryService } = makeWatcher({ coordinator: null });
+ watcher.autoOrganizeService.processNewFile.mockResolvedValue(autoOrganizeResult());
+
+ const outcome = await watcher._attemptAutoOrganize(SOURCE);
+
+ expect(outcome).toEqual({ handled: true, shouldFallback: false });
+ expect(analysisHistoryService.updateEmbeddingStateByPath).toHaveBeenCalledWith(DEST, {
+ status: 'skipped'
+ });
+ });
+
+ test('a coordinator that throws does not fail the organize', async () => {
+ const { watcher } = makeWatcher({
+ coordinator: { atomicPathUpdate: jest.fn().mockRejectedValue(new Error('locked')) }
+ });
+ watcher.autoOrganizeService.processNewFile.mockResolvedValue(autoOrganizeResult());
+
+ const outcome = await watcher._attemptAutoOrganize(SOURCE);
+
+ expect(outcome).toEqual({ handled: true, shouldFallback: false });
+ expect(recordAnalysisResult).toHaveBeenCalledWith(expect.objectContaining({ filePath: DEST }));
+ });
+
+ test('a fallback rename re-keys the index to the renamed file', async () => {
+ const { watcher, filePathCoordinator, analysisHistoryService } = makeWatcher({
+ vectorRow: { id: 'x' }
+ });
+ watcher.settingsService.load.mockResolvedValue({ namingConvention: 'subject-date' });
+ watcher.analyzeDocumentFile.mockResolvedValue({
+ summary: 'An invoice',
+ subject: 'Invoice',
+ _embeddingForPersistence: handoffFor(SOURCE)
+ });
+ const renamed = path.join(path.dirname(SOURCE), 'invoice-2026-11-01.pdf');
+
+ await watcher._fallbackOrganize(SOURCE);
+
+ expect(filePathCoordinator.atomicPathUpdate).toHaveBeenCalledWith(
+ SOURCE,
+ renamed,
+ expect.objectContaining({ type: 'move' })
+ );
+ expect(analysisHistoryService.updateEmbeddingStateByPath).not.toHaveBeenCalledWith(
+ renamed,
+ expect.objectContaining({ status: 'skipped' })
+ );
+ });
+
+ test('a fallback that does not rename leaves the index alone', async () => {
+ const { watcher, filePathCoordinator } = makeWatcher();
+ watcher.settingsService.load.mockResolvedValue({});
+ watcher.analyzeDocumentFile.mockResolvedValue({
+ summary: 'An invoice',
+ subject: 'Invoice',
+ _embeddingForPersistence: handoffFor(SOURCE)
+ });
+
+ await watcher._fallbackOrganize(SOURCE);
+
+ expect(filePathCoordinator.atomicPathUpdate).not.toHaveBeenCalled();
+ });
+});
diff --git a/test/DownloadsTriageService.organizeDedupHistory.test.js b/test/DownloadsTriageService.organizeDedupHistory.test.js
new file mode 100644
index 00000000..90ae3642
--- /dev/null
+++ b/test/DownloadsTriageService.organizeDedupHistory.test.js
@@ -0,0 +1,170 @@
+/**
+ * @jest-environment node
+ *
+ * When Organize finds an identical copy already in the destination folder,
+ * the source is removed and the kept sibling is reported as the destination.
+ * That is a deletion, not a move: sending it to batchPathUpdate re-pointed
+ * the kept file's path at the removed file's history entry, so a lookup of
+ * the kept file returned the removed file's analysis.
+ */
+jest.unmock('fs');
+jest.unmock('fs/promises');
+jest.unmock('os');
+
+const path = require('path');
+const fs = require('fs').promises;
+const os = require('os');
+
+const mockPerformFileMove = jest.fn();
+
+jest.mock('../src/main/ipc/files/batchOrganizeHandler', () => ({
+ performFileMove: (...args) => mockPerformFileMove(...args),
+ computeFileChecksum: jest.fn()
+}));
+
+jest.mock('electron', () => ({
+ app: { getPath: jest.fn() },
+ shell: { trashItem: jest.fn() }
+}));
+
+const mockServices = { undoRedo: null, coordinator: null };
+
+jest.mock('../src/main/services/ServiceContainer', () => ({
+ container: {
+ tryResolve: jest.fn((id) => {
+ if (id === 'filePathCoordinator') return mockServices.coordinator;
+ if (id === 'undoRedo') return mockServices.undoRedo;
+ return null;
+ }),
+ has: jest.fn(() => true),
+ resolve: jest.fn()
+ },
+ ServiceIds: {
+ ORAMA_VECTOR: 'oramaVector',
+ UNDO_REDO: 'undoRedo',
+ ANALYSIS_HISTORY: 'analysisHistory',
+ FOLDER_MATCHING: 'folderMatching',
+ PARALLEL_EMBEDDING: 'parallelEmbedding',
+ FILE_PATH_COORDINATOR: 'filePathCoordinator'
+ }
+}));
+
+jest.mock('../src/main/core/customFolders', () => ({
+ loadCustomFolders: jest.fn().mockResolvedValue([])
+}));
+
+let mockTargetDir;
+jest.mock('../src/main/services/triage/FastTriageClassifier', () => {
+ const actual = jest.requireActual('../src/main/services/triage/FastTriageClassifier');
+ class MockClassifier {
+ async classifyFile() {
+ return {
+ bucket: 'keep',
+ signal: 'lexical-match',
+ confidence: 0.95,
+ why: 'test keep',
+ suggestedFolder: { id: 'sf1', name: 'Target', path: mockTargetDir }
+ };
+ }
+ }
+ return { ...actual, FastTriageClassifier: MockClassifier };
+});
+
+const { DownloadsTriageService } = require('../src/main/services/triage/DownloadsTriageService');
+
+describe('DownloadsTriageService act(organize) with a duplicate already in the folder', () => {
+ let testDir;
+ let service;
+
+ beforeEach(async () => {
+ testDir = await fs.mkdtemp(path.join(os.tmpdir(), 'triage-dedup-hist-'));
+ mockTargetDir = path.join(testDir, 'Target');
+ await fs.mkdir(mockTargetDir, { recursive: true });
+ await fs.writeFile(path.join(testDir, 'report.pdf'), 'same bytes');
+ await fs.writeFile(path.join(testDir, 'notes.txt'), 'other');
+ // The scan root must sit inside Downloads.
+ require('electron').app.getPath.mockReturnValue(testDir);
+
+ mockServices.undoRedo = { recordBatch: jest.fn().mockResolvedValue('undo-1') };
+ mockServices.coordinator = {
+ batchPathUpdate: jest.fn().mockResolvedValue({ success: true }),
+ handleFileDeletion: jest.fn().mockResolvedValue({ success: true })
+ };
+
+ // report.pdf is a dedup skip (its identical copy is kept as
+ // "report (1).pdf"); everything else moves normally.
+ mockPerformFileMove.mockReset();
+ mockPerformFileMove.mockImplementation(async (op) => {
+ if (path.basename(op.source) === 'report.pdf') {
+ await fs.unlink(op.source);
+ return {
+ skipped: true,
+ destination: path.join(mockTargetDir, 'report (1).pdf'),
+ reason: 'duplicate'
+ };
+ }
+ await fs.rename(op.source, op.destination);
+ return { destination: op.destination };
+ });
+
+ service = new DownloadsTriageService();
+ });
+
+ afterEach(async () => {
+ await fs.rm(testDir, { recursive: true, force: true });
+ });
+
+ async function organize(names) {
+ const started = await service.start({ folderPath: testDir, minAgeHours: 0 });
+ const rows = started.buckets.keep.filter((r) => names.includes(path.basename(r.filePath)));
+ expect(rows).toHaveLength(names.length);
+ return service.act({
+ triageId: started.triageId,
+ action: 'organize',
+ files: rows.map((r) => ({
+ path: r.filePath,
+ size: r.size,
+ suggestedFolderPath: r.suggestedFolder.path
+ }))
+ });
+ }
+
+ test('only real moves reach batchPathUpdate; the removed source is a deletion', async () => {
+ const result = await organize(['report.pdf', 'notes.txt']);
+
+ expect(result.success).toBe(true);
+ // The renderer still sees both files leave the triage list.
+ expect(result.moved).toHaveLength(2);
+
+ expect(mockServices.coordinator.batchPathUpdate).toHaveBeenCalledTimes(1);
+ const [changes] = mockServices.coordinator.batchPathUpdate.mock.calls[0];
+ expect(changes).toEqual([
+ {
+ oldPath: path.join(testDir, 'notes.txt'),
+ newPath: path.join(mockTargetDir, 'notes.txt')
+ }
+ ]);
+ expect(mockServices.coordinator.handleFileDeletion).toHaveBeenCalledTimes(1);
+ expect(mockServices.coordinator.handleFileDeletion).toHaveBeenCalledWith(
+ path.join(testDir, 'report.pdf')
+ );
+ });
+
+ test('a request where every file is a duplicate still removes the source from history', async () => {
+ const result = await organize(['report.pdf']);
+
+ expect(result.success).toBe(true);
+ expect(mockServices.undoRedo.recordBatch).not.toHaveBeenCalled();
+ expect(mockServices.coordinator.batchPathUpdate).not.toHaveBeenCalled();
+ expect(mockServices.coordinator.handleFileDeletion).toHaveBeenCalledWith(
+ path.join(testDir, 'report.pdf')
+ );
+ });
+
+ test('a failing index cleanup does not fail the organize', async () => {
+ mockServices.coordinator.handleFileDeletion.mockRejectedValue(new Error('index busy'));
+ const result = await organize(['report.pdf']);
+ expect(result.success).toBe(true);
+ expect(result.moved).toHaveLength(1);
+ });
+});
diff --git a/test/ErrorHandler.crashDumps.test.js b/test/ErrorHandler.crashDumps.test.js
new file mode 100644
index 00000000..325e630f
--- /dev/null
+++ b/test/ErrorHandler.crashDumps.test.js
@@ -0,0 +1,100 @@
+/**
+ * cleanupCrashDumps must sweep Crashpad's report folders (reports/ on
+ * Windows, new/pending/completed on macOS/Linux) and never delete Crashpad's
+ * own database files (root `metadata`, `settings.dat`). Uses a real temp dir.
+ */
+
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+
+const errorHandler = require('../src/main/errors/ErrorHandler');
+
+const DAY = 24 * 60 * 60 * 1000;
+const uuid = (n) => `00000000-0000-4000-8000-${String(n).padStart(12, '0')}`;
+
+/** Write a file and backdate its mtime by `ageMs`. */
+function writeAged(filePath, ageMs) {
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
+ fs.writeFileSync(filePath, 'x');
+ const t = new Date(Date.now() - ageMs);
+ fs.utimesSync(filePath, t, t);
+}
+
+describe('ErrorHandler.cleanupCrashDumps (Crashpad layout)', () => {
+ let dir;
+
+ beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'crash-dumps-'));
+ });
+
+ afterEach(() => {
+ fs.rmSync(dir, { recursive: true, force: true });
+ });
+
+ test('deletes stale dumps under reports/ with their attachments and keeps Crashpad database files', async () => {
+ writeAged(path.join(dir, 'metadata'), 60 * DAY);
+ writeAged(path.join(dir, 'settings.dat'), 60 * DAY);
+ writeAged(path.join(dir, 'reports', `${uuid(1)}.dmp`), 45 * DAY);
+ writeAged(path.join(dir, 'attachments', uuid(1), 'log.txt'), 45 * DAY);
+ writeAged(path.join(dir, 'reports', `${uuid(2)}.dmp`), 2 * DAY);
+
+ await errorHandler.cleanupCrashDumps(dir, 30, 20);
+
+ expect(fs.existsSync(path.join(dir, 'metadata'))).toBe(true);
+ expect(fs.existsSync(path.join(dir, 'settings.dat'))).toBe(true);
+ expect(fs.existsSync(path.join(dir, 'reports', `${uuid(1)}.dmp`))).toBe(false);
+ expect(fs.existsSync(path.join(dir, 'attachments', uuid(1)))).toBe(false);
+ expect(fs.existsSync(path.join(dir, 'reports', `${uuid(2)}.dmp`))).toBe(true);
+ });
+
+ test('sweeps completed/ and pending/ and removes the sibling .meta', async () => {
+ writeAged(path.join(dir, 'completed', `${uuid(3)}.dmp`), 40 * DAY);
+ writeAged(path.join(dir, 'completed', `${uuid(3)}.meta`), 40 * DAY);
+ writeAged(path.join(dir, 'pending', `${uuid(4)}.dmp`), 40 * DAY);
+
+ await errorHandler.cleanupCrashDumps(dir, 30, 20);
+
+ expect(fs.readdirSync(path.join(dir, 'completed'))).toEqual([]);
+ expect(fs.readdirSync(path.join(dir, 'pending'))).toEqual([]);
+ });
+
+ test('applies the count cap across all report folders combined, oldest first', async () => {
+ writeAged(path.join(dir, 'reports', `${uuid(5)}.dmp`), 5 * DAY);
+ writeAged(path.join(dir, 'completed', `${uuid(6)}.dmp`), 4 * DAY);
+ writeAged(path.join(dir, 'pending', `${uuid(7)}.dmp`), 3 * DAY);
+ writeAged(path.join(dir, 'reports', `${uuid(8)}.dmp`), 1 * DAY);
+
+ await errorHandler.cleanupCrashDumps(dir, 30, 2);
+
+ expect(fs.existsSync(path.join(dir, 'reports', `${uuid(5)}.dmp`))).toBe(false);
+ expect(fs.existsSync(path.join(dir, 'completed', `${uuid(6)}.dmp`))).toBe(false);
+ expect(fs.existsSync(path.join(dir, 'pending', `${uuid(7)}.dmp`))).toBe(true);
+ expect(fs.existsSync(path.join(dir, 'reports', `${uuid(8)}.dmp`))).toBe(true);
+ });
+
+ test('leaves a just-written dump in new/ alone even when over the cap', async () => {
+ writeAged(path.join(dir, 'new', `${uuid(9)}.dmp`), 0);
+ writeAged(path.join(dir, 'reports', `${uuid(10)}.dmp`), 1 * DAY);
+
+ await errorHandler.cleanupCrashDumps(dir, 30, 0);
+
+ expect(fs.existsSync(path.join(dir, 'new', `${uuid(9)}.dmp`))).toBe(true);
+ expect(fs.existsSync(path.join(dir, 'reports', `${uuid(10)}.dmp`))).toBe(false);
+ });
+
+ test('still clears stray root-level dumps from older layouts', async () => {
+ writeAged(path.join(dir, 'old.dmp'), 40 * DAY);
+ writeAged(path.join(dir, 'old.ips'), 40 * DAY);
+
+ await errorHandler.cleanupCrashDumps(dir, 30, 20);
+
+ expect(fs.readdirSync(dir)).toEqual([]);
+ });
+
+ test('is a no-op when the crash-dumps folder does not exist', async () => {
+ await expect(
+ errorHandler.cleanupCrashDumps(path.join(dir, 'missing'), 30, 20)
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/test/ErrorHandler.extended.test.js b/test/ErrorHandler.extended.test.js
index fc64cfe6..8cb9910f 100644
--- a/test/ErrorHandler.extended.test.js
+++ b/test/ErrorHandler.extended.test.js
@@ -178,7 +178,7 @@ describe('ErrorHandler - extended coverage', () => {
const result = errorHandler.parseError(error);
expect(result.type).toBe('NETWORK_ERROR');
- expect(result.message).toContain('network-related error');
+ expect(result.message).toContain('network error');
});
test('preserves short user-friendly error messages', () => {
@@ -196,21 +196,21 @@ describe('ErrorHandler - extended coverage', () => {
const result = errorHandler.parseError(error);
expect(result.type).toBe('UNKNOWN');
- expect(result.message).toBe('Something went wrong. Please try again.');
+ expect(result.message).toBe('Something went wrong. Try again.');
});
test('replaces messages containing undefined with generic', () => {
const error = new Error('Cannot read property of undefined');
const result = errorHandler.parseError(error);
- expect(result.message).toBe('Something went wrong. Please try again.');
+ expect(result.message).toBe('Something went wrong. Try again.');
});
test('replaces messages containing null with generic', () => {
const error = new Error('Expected value but got null');
const result = errorHandler.parseError(error);
- expect(result.message).toBe('Something went wrong. Please try again.');
+ expect(result.message).toBe('Something went wrong. Try again.');
});
test('includes originalMessage in details', () => {
diff --git a/test/FolderMatchingService.resetPersisted.test.js b/test/FolderMatchingService.resetPersisted.test.js
index caddef8e..86cda31d 100644
--- a/test/FolderMatchingService.resetPersisted.test.js
+++ b/test/FolderMatchingService.resetPersisted.test.js
@@ -43,7 +43,12 @@ jest.mock('../src/main/services/EmbeddingCache', () =>
}))
);
+jest.mock('../src/main/analysis/embeddingQueue/queueManager', () => ({
+ dropOtherModelEmbeddings: jest.fn(() => 0)
+}));
+
const FolderMatchingService = require('../src/main/services/FolderMatchingService');
+const queueManager = require('../src/main/analysis/embeddingQueue/queueManager');
const RESET_DONE = '[FolderMatchingService] Vector DB collections reset after model change';
const messages = (fn) => fn.mock.calls.map(([msg]) => msg);
@@ -83,6 +88,13 @@ describe('embedding model change reset', () => {
expect(messages(mockLogger.info)).not.toContain(RESET_DONE);
expect(messages(mockLogger.warn).some((m) => /in memory only/.test(m))).toBe(true);
});
+
+ test('pending embeddings from the previous model are dropped from the queues', async () => {
+ await fireEmbeddingModelChange({
+ handleEmbeddingModelChange: jest.fn().mockResolvedValue({ resetPersisted: true })
+ });
+ expect(queueManager.dropOtherModelEmbeddings).toHaveBeenCalledWith('new');
+ });
});
describe('folder dimension-mismatch self-heal', () => {
diff --git a/test/LlamaService.configChangeDrain.test.js b/test/LlamaService.configChangeDrain.test.js
new file mode 100644
index 00000000..fe626fe2
--- /dev/null
+++ b/test/LlamaService.configChangeDrain.test.js
@@ -0,0 +1,202 @@
+/**
+ * updateConfig must not hold the load lock while it waits for in-flight
+ * operations. An op that already holds an inference slot loads through
+ * acquireLoadLock, so waiting for it under the lock was a circular wait that
+ * stalled settings saves (and the whole analysis lane) for the full 60 s
+ * idle-wait timeout. These tests drive the real ModelAccessCoordinator.
+ */
+
+jest.mock('../src/shared/logger', () => ({
+ createLogger: () => ({
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn()
+ })
+}));
+
+jest.mock('../src/main/services/DegradationManager', () => ({
+ DegradationManager: jest.fn().mockImplementation(() => ({
+ checkSystemReadiness: jest.fn().mockResolvedValue({ ready: true, issues: [], gpuInfo: {} }),
+ handleError: jest.fn().mockResolvedValue({ action: 'none' })
+ }))
+}));
+
+jest.mock('../src/main/services/ModelMemoryManager', () => ({
+ ModelMemoryManager: jest.fn().mockImplementation(() => ({
+ ensureModelLoaded: jest.fn().mockResolvedValue(true),
+ unloadAll: jest.fn().mockResolvedValue(undefined)
+ }))
+}));
+
+jest.mock('../src/main/services/PerformanceMetrics', () => ({
+ PerformanceMetrics: jest.fn().mockImplementation(() => ({
+ recordEmbedding: jest.fn(),
+ recordModelLoad: jest.fn(),
+ destroy: jest.fn()
+ }))
+}));
+
+jest.mock('../src/main/services/GPUMonitor', () => ({
+ GPUMonitor: jest.fn().mockImplementation(() => ({})),
+ getInstance: jest.fn(() => ({}))
+}));
+
+jest.mock('../src/main/services/SettingsService', () => ({
+ getInstance: jest.fn(() => ({
+ load: jest.fn().mockResolvedValue({}),
+ save: jest.fn().mockResolvedValue(undefined)
+ }))
+}));
+
+jest.mock('../src/main/services/LlamaResilience', () => ({
+ withLlamaResilience: (fn) => fn({}),
+ cleanupLlamaCircuits: jest.fn(),
+ resetLlamaCircuit: jest.fn(),
+ shouldFallbackToCPU: jest.fn()
+}));
+
+jest.mock('../src/main/services/PerformanceService', () => ({
+ getRecommendedConcurrency: jest.fn().mockResolvedValue({
+ maxConcurrent: 1,
+ reason: 'test-mock',
+ vramMB: 0,
+ gpuName: null
+ })
+}));
+
+// The shared p-queue mock runs every task at once. The coordinator's load
+// lock and inference slots are concurrency-1 queues, so these tests need a
+// queue that actually enforces its limit.
+jest.mock('p-queue', () => {
+ class PQueue {
+ constructor(opts = {}) {
+ this.concurrency = opts.concurrency || Infinity;
+ this.pending = 0;
+ this._waiting = [];
+ }
+
+ get size() {
+ return this._waiting.length;
+ }
+
+ add(fn) {
+ return new Promise((resolve, reject) => {
+ this._waiting.push({ fn, resolve, reject });
+ this._next();
+ });
+ }
+
+ _next() {
+ while (this.pending < this.concurrency && this._waiting.length > 0) {
+ const { fn, resolve, reject } = this._waiting.shift();
+ this.pending += 1;
+ Promise.resolve()
+ .then(fn)
+ .then(resolve, reject)
+ .finally(() => {
+ this.pending -= 1;
+ this._next();
+ });
+ }
+ }
+ }
+ return { default: PQueue };
+});
+
+const { LlamaService } = require('../src/main/services/LlamaService');
+const { ModelAccessCoordinator } = require('../src/main/services/ModelAccessCoordinator');
+
+function deferred() {
+ let resolve;
+ const promise = new Promise((r) => {
+ resolve = r;
+ });
+ return { promise, resolve };
+}
+
+/**
+ * Mirrors an inference call: take a slot, then load through the load lock
+ * (as _ensureModelLoaded always does), then run.
+ */
+function runTextOp(coordinator, id, work) {
+ return coordinator.withModel(
+ 'text',
+ async () => {
+ const release = await coordinator.acquireLoadLock('text');
+ release();
+ await work;
+ },
+ { operationId: id }
+ );
+}
+
+function buildService(loadedModels) {
+ const service = new LlamaService();
+ service._ensureConfigLoaded = jest.fn().mockResolvedValue(undefined);
+ service._coordinator = new ModelAccessCoordinator({ inferenceSlots: 1 });
+ service._modelMemoryManager = {
+ unloadAll: jest.fn().mockResolvedValue(undefined),
+ getMemoryStatus: jest.fn(() => ({ loadedModels }))
+ };
+ return service;
+}
+
+describe('LlamaService.updateConfig drain before load lock', () => {
+ test('a model change with a queued request finishes promptly and unloads', async () => {
+ const service = buildService([]);
+ const coordinator = service._coordinator;
+
+ const firstWork = deferred();
+ const op1 = runTextOp(coordinator, 'op-1', firstWork.promise);
+ // op-2 is queued for the single text slot; when it gets the slot it
+ // needs the load lock.
+ const op2 = runTextOp(coordinator, 'op-2', Promise.resolve());
+ await new Promise((r) => setTimeout(r, 20));
+
+ const started = Date.now();
+ const update = service.updateConfig({ textModel: 'new-model.gguf' }, { skipSave: true });
+ await new Promise((r) => setTimeout(r, 50));
+ firstWork.resolve();
+
+ await update;
+ await Promise.all([op1, op2]);
+
+ // Before the fix this waited out the full 60 s idle timeout.
+ expect(Date.now() - started).toBeLessThan(5000);
+ expect(service._modelMemoryManager.unloadAll).toHaveBeenCalledTimes(1);
+ expect(service._staleModelTypes.has('text')).toBe(false);
+ expect(service._configChangeGate).toBeNull();
+ }, 15000);
+
+ test('an op that takes a slot after the drain only costs a short re-check, then the swap is deferred', async () => {
+ const service = buildService(['text']);
+ const coordinator = service._coordinator;
+
+ const realAcquire = coordinator.acquireLoadLock.bind(coordinator);
+ /** @type {Promise | null} */
+ let lateOp = null;
+ coordinator.acquireLoadLock = async (type, options) => {
+ const release = await realAcquire(type, options);
+ // updateConfig passes onForceRelease; the simulated ops do not. Once
+ // updateConfig holds the lock, start an op that will block on it.
+ if (options?.onForceRelease && !lateOp) {
+ lateOp = runTextOp(coordinator, 'late-op', Promise.resolve());
+ await new Promise((r) => setTimeout(r, 20));
+ }
+ return release;
+ };
+
+ const started = Date.now();
+ await service.updateConfig({ textModel: 'new-model.gguf' }, { skipSave: true });
+
+ expect(Date.now() - started).toBeLessThan(10000);
+ // The late op was still active, so unloading was skipped and the old
+ // model is marked stale for the next locked load to swap.
+ expect(service._modelMemoryManager.unloadAll).not.toHaveBeenCalled();
+ expect(service._staleModelTypes.has('text')).toBe(true);
+
+ // Releasing the lock lets the late op finish.
+ await lateOp;
+ }, 15000);
+});
diff --git a/test/ModelDownloadManager.cancelAfterBody.test.js b/test/ModelDownloadManager.cancelAfterBody.test.js
new file mode 100644
index 00000000..0a83a2a2
--- /dev/null
+++ b/test/ModelDownloadManager.cancelAfterBody.test.js
@@ -0,0 +1,281 @@
+/**
+ * Cancelling a model download after its last byte has arrived:
+ * - during the SHA-256 check the model must not be renamed into place;
+ * - while a vision model's projector (mmproj) downloads, cancelling the
+ * model must reach the projector download;
+ * - while the file is being renamed the cancel is refused, since the rename
+ * cannot be undone.
+ */
+const { EventEmitter } = require('events');
+const path = require('path');
+
+jest.mock('electron', () => ({
+ app: {
+ getPath: jest.fn(() => require('path').join('C:', 'fake-user-data'))
+ }
+}));
+
+const mockFs = {
+ mkdir: jest.fn().mockResolvedValue(),
+ readdir: jest.fn(),
+ stat: jest.fn(),
+ statfs: jest.fn(),
+ unlink: jest.fn().mockResolvedValue(),
+ rename: jest.fn().mockResolvedValue(),
+ access: jest.fn()
+};
+
+jest.mock('fs', () => ({
+ promises: mockFs,
+ createWriteStream: jest.fn(),
+ createReadStream: jest.fn()
+}));
+
+jest.mock('https', () => ({
+ get: jest.fn()
+}));
+
+jest.mock('../src/shared/logger', () => ({
+ createLogger: () => ({ info: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() })
+}));
+
+// sha256 of empty input: the mocked read stream yields no bytes.
+const EMPTY_SHA = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
+
+jest.mock('../src/shared/modelRegistry', () => {
+ const sha = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
+ const catalog = {
+ 'alpha.gguf': {
+ displayName: 'Alpha',
+ type: 'text',
+ size: 1000,
+ url: 'https://huggingface.co/models/alpha.gguf',
+ checksum: sha
+ },
+ 'seer.gguf': {
+ displayName: 'Seer',
+ type: 'vision',
+ size: 1000,
+ url: 'https://huggingface.co/models/seer.gguf',
+ checksum: sha,
+ clipModel: {
+ name: 'seer-mmproj.gguf',
+ url: 'https://huggingface.co/models/seer-mmproj.gguf',
+ size: 200,
+ checksum: sha
+ }
+ }
+ };
+ return {
+ MODEL_CATALOG: catalog,
+ getModel: (name) => catalog[name] || null
+ };
+});
+
+const https = require('https');
+const fsModule = require('fs');
+const { ModelDownloadManager } = require('../src/main/services/ModelDownloadManager');
+
+const MODELS_DIR = path.join('C:', 'fake-user-data', 'models');
+
+function makeRequest() {
+ const request = new EventEmitter();
+ request.setTimeout = jest.fn();
+ request.destroy = jest.fn();
+ return request;
+}
+
+/** A 200 response whose body "arrives" in full unless `hang` is set. */
+function makeResponse(contentLength, { hang = false } = {}) {
+ const response = new EventEmitter();
+ response.statusCode = 200;
+ response.statusMessage = 'OK';
+ response.headers = { 'content-length': String(contentLength) };
+ response.resume = jest.fn();
+ response.unpipe = jest.fn();
+ response.pipe = (ws) => {
+ if (!hang) {
+ setTimeout(() => {
+ response.complete = true;
+ ws.emit('finish');
+ }, 0);
+ }
+ return ws;
+ };
+ return response;
+}
+
+const flush = () => new Promise((resolve) => setTimeout(resolve, 5));
+
+describe('ModelDownloadManager cancel after the body has arrived', () => {
+ /** @type {Set} */
+ let written;
+ /** @type {Array<{ stream: EventEmitter }>} */
+ let readStreams;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ written = new Set();
+ readStreams = [];
+ mockFs.statfs.mockResolvedValue({ bavail: 1024 * 1024 * 1024, bsize: 4096 });
+ mockFs.unlink.mockResolvedValue(undefined);
+ mockFs.rename.mockResolvedValue(undefined);
+ mockFs.access.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' }));
+ // A partial exists only once its write stream was opened; its size is the
+ // catalog size so the size check passes.
+ mockFs.stat.mockImplementation(async (filePath) => {
+ if (!written.has(filePath)) {
+ throw Object.assign(new Error('missing'), { code: 'ENOENT' });
+ }
+ return { size: filePath.includes('mmproj') ? 200 : 1000 };
+ });
+ fsModule.createWriteStream.mockImplementation((filePath) => {
+ written.add(filePath);
+ const ws = new EventEmitter();
+ ws.destroy = jest.fn();
+ ws.closed = true;
+ return ws;
+ });
+ });
+
+ /** Read streams that finish hashing only when the test says so. */
+ function useSlowChecksum() {
+ fsModule.createReadStream.mockImplementation(() => {
+ const stream = new EventEmitter();
+ stream.destroy = jest.fn();
+ readStreams.push({ stream });
+ return stream;
+ });
+ }
+
+ function useFastChecksum() {
+ fsModule.createReadStream.mockImplementation(() => {
+ const stream = new EventEmitter();
+ stream.destroy = jest.fn();
+ setTimeout(() => stream.emit('end'), 0);
+ return stream;
+ });
+ }
+
+ test('a cancel during the checksum stops the install and drops the partial', async () => {
+ useSlowChecksum();
+ https.get.mockImplementation((_options, onResponse) => {
+ setTimeout(() => onResponse(makeResponse(1000)), 0);
+ return makeRequest();
+ });
+ const manager = new ModelDownloadManager();
+ const download = manager.downloadModel('alpha.gguf');
+ const outcome = download.then(
+ (value) => ({ value }),
+ (error) => ({ error })
+ );
+
+ // Wait until the body is written and the checksum read has started.
+ for (let i = 0; i < 50 && readStreams.length === 0; i += 1) await flush();
+ expect(readStreams).toHaveLength(1);
+
+ expect(manager.cancelDownload('alpha.gguf')).toBe(true);
+ // Even if the hash finishes afterwards, the result must stay cancelled.
+ readStreams[0].stream.emit('end');
+
+ const result = await outcome;
+ expect(result.error?.message).toBe('Download cancelled');
+ expect(readStreams[0].stream.destroy).toHaveBeenCalled();
+ expect(mockFs.rename).not.toHaveBeenCalled();
+ expect(mockFs.unlink).toHaveBeenCalledWith(path.join(MODELS_DIR, 'alpha.gguf.partial'));
+ expect(manager.isDownloading('alpha.gguf')).toBe(false);
+ expect(manager.getStatus().active).toBe(0);
+ });
+
+ test('cancelling a vision model while its projector downloads stops the projector', async () => {
+ useFastChecksum();
+ /** @type {Array<{ options: any, request: any }>} */
+ const requests = [];
+ https.get.mockImplementation((options, onResponse) => {
+ const request = makeRequest();
+ requests.push({ options, request });
+ const isProjector = options.path.includes('mmproj');
+ setTimeout(
+ () => onResponse(makeResponse(isProjector ? 200 : 1000, { hang: isProjector })),
+ 0
+ );
+ return request;
+ });
+ const manager = new ModelDownloadManager();
+ const outcome = manager.downloadModel('seer.gguf').then(
+ (value) => ({ value }),
+ (error) => ({ error })
+ );
+
+ for (let i = 0; i < 50 && requests.length < 2; i += 1) await flush();
+ expect(requests).toHaveLength(2);
+ await flush();
+ // The model stays "in progress" while its projector is still coming.
+ expect(manager.isDownloading('seer.gguf')).toBe(true);
+ expect(manager.isDownloading('seer-mmproj.gguf')).toBe(true);
+
+ expect(manager.cancelDownload('seer.gguf')).toBe(true);
+
+ const result = await outcome;
+ expect(result.error?.message).toBe('Download cancelled');
+ expect(requests[1].request.destroy).toHaveBeenCalled();
+ expect(manager.isDownloading('seer.gguf')).toBe(false);
+ expect(manager.isDownloading('seer-mmproj.gguf')).toBe(false);
+ expect(manager.getStatus().active).toBe(0);
+ });
+
+ test('a vision model with its projector still resolves and leaves no entry behind', async () => {
+ useFastChecksum();
+ https.get.mockImplementation((options, onResponse) => {
+ const isProjector = options.path.includes('mmproj');
+ setTimeout(() => onResponse(makeResponse(isProjector ? 200 : 1000)), 0);
+ return makeRequest();
+ });
+ const manager = new ModelDownloadManager();
+ const result = await manager.downloadModel('seer.gguf');
+ expect(result).toEqual(
+ expect.objectContaining({
+ success: true,
+ degraded: false,
+ downloadedBytes: 1200,
+ totalBytes: 1200
+ })
+ );
+ expect(mockFs.rename).toHaveBeenCalledTimes(2);
+ expect(manager.getStatus().active).toBe(0);
+ });
+
+ test('a cancel while the file is renamed into place is refused', async () => {
+ useFastChecksum();
+ https.get.mockImplementation((_options, onResponse) => {
+ setTimeout(() => onResponse(makeResponse(1000)), 0);
+ return makeRequest();
+ });
+ /** @type {() => void} */
+ let finishRename = () => {};
+ mockFs.rename.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ finishRename = () => resolve(undefined);
+ })
+ );
+ const manager = new ModelDownloadManager();
+ const download = manager.downloadModel('alpha.gguf');
+
+ for (let i = 0; i < 50 && mockFs.rename.mock.calls.length === 0; i += 1) await flush();
+ expect(mockFs.rename).toHaveBeenCalledTimes(1);
+ expect(manager.cancelDownload('alpha.gguf')).toBe(false);
+ // A second start of the same file is still blocked during the rename.
+ await expect(manager.downloadModel('alpha.gguf')).rejects.toThrow('already in progress');
+
+ finishRename();
+ await expect(download).resolves.toEqual(expect.objectContaining({ success: true }));
+ expect(manager.getStatus().active).toBe(0);
+ });
+
+ test('the checksum helper still resolves without a signal', async () => {
+ useFastChecksum();
+ const manager = new ModelDownloadManager();
+ await expect(manager._verifyChecksum('x', EMPTY_SHA)).resolves.toBe(true);
+ });
+});
diff --git a/test/ModelDownloadManager.concurrentStart.test.js b/test/ModelDownloadManager.concurrentStart.test.js
new file mode 100644
index 00000000..d6742aaa
--- /dev/null
+++ b/test/ModelDownloadManager.concurrentStart.test.js
@@ -0,0 +1,104 @@
+/**
+ * Two near-simultaneous requests for the same model must not both start.
+ *
+ * The in-progress guard ran before the partial-file and disk-space awaits,
+ * and the slot was only claimed after them, so both requests passed the
+ * guard and streamed into the same `.partial`. The slot is now claimed right
+ * after the guard and released on every exit before the request opens.
+ */
+const { EventEmitter } = require('events');
+
+jest.mock('electron', () => ({
+ app: {
+ getPath: jest.fn(() => require('path').join('C:', 'fake-user-data'))
+ }
+}));
+
+const mockFs = {
+ mkdir: jest.fn().mockResolvedValue(),
+ readdir: jest.fn(),
+ stat: jest.fn(),
+ statfs: jest.fn(),
+ unlink: jest.fn().mockResolvedValue(),
+ rename: jest.fn().mockResolvedValue(),
+ access: jest.fn()
+};
+
+jest.mock('fs', () => ({
+ promises: mockFs,
+ createWriteStream: jest.fn(),
+ createReadStream: jest.fn()
+}));
+
+jest.mock('https', () => ({
+ get: jest.fn()
+}));
+
+jest.mock('../src/shared/logger', () => ({
+ createLogger: () => ({ info: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() })
+}));
+
+jest.mock('../src/shared/modelRegistry', () => {
+ const sha = 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
+ const catalog = {
+ 'alpha.gguf': {
+ displayName: 'Alpha',
+ type: 'text',
+ size: 1000,
+ url: 'https://huggingface.co/models/alpha.gguf',
+ checksum: sha
+ }
+ };
+ return {
+ MODEL_CATALOG: catalog,
+ getModel: (name) => catalog[name] || null
+ };
+});
+
+const https = require('https');
+const { ModelDownloadManager } = require('../src/main/services/ModelDownloadManager');
+
+function makeRequest() {
+ const request = new EventEmitter();
+ request.setTimeout = jest.fn();
+ request.destroy = jest.fn();
+ return request;
+}
+
+describe('ModelDownloadManager claims the download slot before its first await', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ mockFs.statfs.mockResolvedValue({ bavail: 1024 * 1024 * 1024, bsize: 4096 });
+ mockFs.stat.mockRejectedValue(Object.assign(new Error('missing'), { code: 'ENOENT' }));
+ // The request never answers: the first download stays in flight.
+ https.get.mockImplementation(() => makeRequest());
+ });
+
+ test('a second request started in the same tick is refused and opens no stream', async () => {
+ const manager = new ModelDownloadManager();
+ const first = manager.downloadModel('alpha.gguf');
+ first.catch(() => {});
+ const second = manager.downloadModel('alpha.gguf');
+
+ await expect(second).rejects.toThrow('Download already in progress: alpha.gguf');
+ // Let the first request get past its partial and disk checks.
+ for (let i = 0; i < 20 && https.get.mock.calls.length === 0; i += 1) {
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ }
+ expect(https.get).toHaveBeenCalledTimes(1);
+ expect(manager.isDownloading('alpha.gguf')).toBe(true);
+
+ manager.cancelDownload('alpha.gguf');
+ await expect(first).rejects.toThrow();
+ });
+
+ test('a start that fails its disk-space check releases the slot', async () => {
+ mockFs.statfs.mockResolvedValue({ bavail: 0, bsize: 4096 });
+ const manager = new ModelDownloadManager();
+
+ await expect(manager.downloadModel('alpha.gguf')).rejects.toThrow(/disk space/i);
+ expect(manager.isDownloading('alpha.gguf')).toBe(false);
+ expect(manager.getStatus().active).toBe(0);
+ expect(https.get).not.toHaveBeenCalled();
+ });
+});
diff --git a/test/NotificationService.activationListeners.test.js b/test/NotificationService.activationListeners.test.js
new file mode 100644
index 00000000..0182bf27
--- /dev/null
+++ b/test/NotificationService.activationListeners.test.js
@@ -0,0 +1,92 @@
+/**
+ * Clicking a tray notification focuses the app and, 100 ms later, tells the
+ * renderer which view to open. Each click used to add a once('closed')
+ * listener to every window to clear that timer; the main window stays open
+ * all session, so the listeners piled up (MaxListenersExceededWarning past
+ * ten clicks). The timer is harmless after a close: the emit skips
+ * destroyed windows.
+ */
+
+const { EventEmitter } = require('events');
+
+jest.mock('electron', () => ({
+ Notification: Object.assign(jest.fn(), { isSupported: jest.fn(() => true) }),
+ BrowserWindow: {
+ getAllWindows: jest.fn(() => [])
+ }
+}));
+
+jest.mock('../src/shared/logger', () => {
+ const logger = {
+ setContext: jest.fn(),
+ info: jest.fn(),
+ debug: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn()
+ };
+ return { logger, createLogger: jest.fn(() => logger) };
+});
+
+jest.mock('../src/main/ipc/ipcWrappers', () => ({
+ safeSend: jest.fn(() => true)
+}));
+
+const NotificationService = require('../src/main/services/NotificationService');
+const { BrowserWindow } = require('electron');
+const { safeSend } = require('../src/main/ipc/ipcWrappers');
+
+function makeWindow() {
+ const win = new EventEmitter();
+ let destroyed = false;
+ Object.assign(win, {
+ webContents: { id: 1, send: jest.fn() },
+ isDestroyed: () => destroyed,
+ isMinimized: () => false,
+ restore: jest.fn(),
+ show: jest.fn(),
+ focus: jest.fn(),
+ destroy: () => {
+ destroyed = true;
+ win.emit('closed');
+ }
+ });
+ return win;
+}
+
+describe('NotificationService activation', () => {
+ let service;
+
+ beforeEach(() => {
+ jest.useFakeTimers();
+ jest.clearAllMocks();
+ service = new NotificationService({ settingsService: { load: jest.fn() } });
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ test('repeated clicks add no listeners to the window', () => {
+ const win = makeWindow();
+ BrowserWindow.getAllWindows.mockReturnValue([win]);
+
+ for (let i = 0; i < 15; i++) {
+ service._handleNotificationActivation({ type: 'file_organized', data: { i } });
+ }
+ jest.advanceTimersByTime(100);
+
+ expect(win.listenerCount('closed')).toBe(0);
+ expect(safeSend).toHaveBeenCalledTimes(15);
+ });
+
+ test('a window closed before the timer fires is not sent to', () => {
+ const win = makeWindow();
+ BrowserWindow.getAllWindows.mockReturnValue([win]);
+
+ service._handleNotificationActivation({ type: 'file_organized', data: null });
+ win.destroy();
+ jest.advanceTimersByTime(100);
+
+ expect(safeSend).not.toHaveBeenCalled();
+ });
+});
diff --git a/test/OramaVectorService.readAllDocuments.test.js b/test/OramaVectorService.readAllDocuments.test.js
new file mode 100644
index 00000000..f2d8be1f
--- /dev/null
+++ b/test/OramaVectorService.readAllDocuments.test.js
@@ -0,0 +1,119 @@
+/**
+ * _getAllFileDocuments / _getAllFolderDocuments used to start with
+ * persist(db). Its default 'binary' format returns an encoded string, never
+ * the `{ docs: { docs } }` object the code looked for, so every call encoded
+ * the whole collection (vector index included) on the main thread and threw
+ * the result away before falling back to paged search. They now read Orama's
+ * docs store directly.
+ */
+
+const fs = require('fs').promises;
+const path = require('path');
+
+jest.mock('electron', () => ({
+ app: { getPath: jest.fn() }
+}));
+
+jest.mock('../src/shared/logger', () => ({
+ createLogger: () => ({
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn()
+ })
+}));
+
+jest.mock('../src/shared/singletonFactory', () => ({
+ createSingletonHelpers: () => ({
+ getInstance: jest.fn(),
+ createInstance: jest.fn(),
+ registerWithContainer: jest.fn(),
+ resetInstance: jest.fn()
+ })
+}));
+
+// Mock only the persistence plugin (ESM in jest); the core Orama engine runs
+// for real so the docs store has its real shape.
+jest.mock('@orama/plugin-data-persistence', () => ({
+ persist: jest.fn(async () => '{}'),
+ restore: jest.fn(async () => {
+ throw new Error('restore not available in test');
+ })
+}));
+
+jest.mock('../src/main/llamaUtils', () => ({
+ getEmbeddingModel: jest.fn(() => 'nomic-embed-text-v1.5-Q8_0.gguf'),
+ loadLlamaConfig: jest.fn().mockResolvedValue({
+ selectedEmbeddingModel: 'nomic-embed-text-v1.5-Q8_0.gguf'
+ })
+}));
+
+const TEMP_DIR = path.join(__dirname, 'temp-orama-read-all-docs-test');
+
+const { app } = require('electron');
+const { persist } = require('@orama/plugin-data-persistence');
+const { OramaVectorService } = require('../src/main/services/OramaVectorService');
+
+const vec = (/** @type {number} */ seed) =>
+ Array.from({ length: 768 }, (_, i) => Math.sin(seed * 31 + i));
+
+describe('OramaVectorService reads every document from the docs store', () => {
+ /** @type {any} */
+ let service;
+
+ beforeAll(async () => {
+ await fs.mkdir(TEMP_DIR, { recursive: true }).catch(() => {});
+ });
+
+ afterAll(async () => {
+ await fs.rm(TEMP_DIR, { recursive: true, force: true }).catch(() => {});
+ });
+
+ beforeEach(async () => {
+ jest.clearAllMocks();
+ /** @type {any} */ (app.getPath).mockReturnValue(TEMP_DIR);
+ service = new OramaVectorService();
+ await service.initialize();
+ });
+
+ afterEach(async () => {
+ await service.cleanup();
+ });
+
+ test('files: no full persist() export, every doc returned with its vector, as copies', async () => {
+ await service.batchUpsertFiles([
+ { id: 'file:A', vector: vec(1), meta: { path: '/lib/A.pdf', fileName: 'A.pdf' } },
+ { id: 'file:B', vector: vec(2), meta: { path: '/lib/B.pdf', fileName: 'B.pdf' } }
+ ]);
+ /** @type {any} */ (persist).mockClear();
+
+ const docs = await service._getAllFileDocuments();
+
+ expect(persist).not.toHaveBeenCalled();
+ expect(docs.map((/** @type {any} */ d) => d.id).sort()).toEqual(['file:A', 'file:B']);
+ // The store's docs keep their vectors (the paged-search fallback nulls them on its copies).
+ expect(docs.every((/** @type {any} */ d) => Array.isArray(d.embedding))).toBe(true);
+
+ // A caller changing a returned doc must not change the stored one.
+ docs[0].fileName = 'changed.pdf';
+ const again = await service._getAllFileDocuments();
+ expect(again.find((/** @type {any} */ d) => d.id === docs[0].id).fileName).not.toBe(
+ 'changed.pdf'
+ );
+ });
+
+ test('folders: no full persist() export, every folder returned', async () => {
+ await service.upsertFolder({
+ id: 'folder:Finance',
+ vector: vec(3),
+ meta: { path: '/lib/Finance', name: 'Finance' }
+ });
+ /** @type {any} */ (persist).mockClear();
+
+ const docs = await service._getAllFolderDocuments();
+
+ expect(persist).not.toHaveBeenCalled();
+ expect(docs.map((/** @type {any} */ d) => d.id)).toEqual(['folder:Finance']);
+ expect(docs[0].folderName).toBe('Finance');
+ });
+});
diff --git a/test/OramaVectorService.restore.test.js b/test/OramaVectorService.restore.test.js
index 97cd0c65..dfe73c80 100644
--- a/test/OramaVectorService.restore.test.js
+++ b/test/OramaVectorService.restore.test.js
@@ -339,18 +339,13 @@ describe('OramaVectorService restore behavior', () => {
};
}
- mockPersist.mockResolvedValueOnce({
- docs: {
- docs
- }
- });
-
const service = new OramaVectorService();
service._dimension = 3;
service._schemas = {
files: { id: 'string', embedding: 'vector[3]', hasVector: 'boolean', filePath: 'string' }
};
- service._databases = { files: { _name: 'files-db' } };
+ // Orama's in-memory docs store shape; the repair reads it directly rather than persist()ing.
+ service._databases = { files: { _name: 'files-db', data: { docs: { docs } } } };
service._embeddingStore = { files: new Map() };
service._collectionDimensions = {};
service._clearQueryCache = jest.fn();
@@ -364,7 +359,7 @@ describe('OramaVectorService restore behavior', () => {
repairedDocs: docCount
})
);
- expect(mockPersist).toHaveBeenCalledWith({ _name: 'files-db' });
+ expect(mockPersist).not.toHaveBeenCalled();
expect(mockSearch).not.toHaveBeenCalled();
expect(mockInsert).toHaveBeenCalledTimes(docCount);
expect(service.persistAll).toHaveBeenCalledTimes(1);
diff --git a/test/OramaVectorService.restoreWorker.test.js b/test/OramaVectorService.restoreWorker.test.js
index 725d82d1..27c27ac0 100644
--- a/test/OramaVectorService.restoreWorker.test.js
+++ b/test/OramaVectorService.restoreWorker.test.js
@@ -416,7 +416,9 @@ describe('OramaVectorService restore through the worker', () => {
await expect(viaWorker.hasUsableVector(`file:${i}`)).resolves.toBe(true);
}
expect(viaWorker._restoreWorkerDisabledReason).toBeNull();
- });
+ // Three service start-ups, a persist and two restores: about 1.5 s alone
+ // with coverage, past the 10 s default on a loaded machine.
+ }, 30000);
test('a primary that fails to decode falls back to .bak the same way through the worker', async () => {
const seed = await startService({ worker: false });
diff --git a/test/OramaVectorService.test.js b/test/OramaVectorService.test.js
index 1c1166ab..d2a1ffa6 100644
--- a/test/OramaVectorService.test.js
+++ b/test/OramaVectorService.test.js
@@ -209,6 +209,31 @@ describe('OramaVectorService', () => {
expect(result.success).toBe(false);
expect(result.error).toBe('dimension_mismatch');
});
+
+ test('rejects a vector with NaN or Infinity values instead of storing it', async () => {
+ const nanVector = new Array(768).fill(0.1);
+ nanVector[3] = Number.NaN;
+ const infVector = new Array(768).fill(0.1);
+ infVector[5] = Number.POSITIVE_INFINITY;
+
+ const nanResult = await service.upsertFile({
+ ...testFile,
+ id: 'file-nan',
+ vector: nanVector
+ });
+ const infResult = await service.batchUpsertFiles([
+ { ...testFile, id: 'file-inf', vector: infVector }
+ ]);
+
+ expect(nanResult).toEqual(
+ expect.objectContaining({ success: false, error: 'invalid_vector_values' })
+ );
+ expect(infResult.failed).toEqual([
+ expect.objectContaining({ id: 'file-inf', error: 'invalid_vector_values' })
+ ]);
+ expect(await service.getFile('file-nan')).toBeNull();
+ expect(await service.getFile('file-inf')).toBeNull();
+ });
});
describe('single-doc lookup error handling (F-041)', () => {
@@ -318,6 +343,24 @@ describe('OramaVectorService', () => {
expect(maxActive).toBeLessThanOrEqual(2);
});
+ test('batchUpsertFiles fails only the wrong-dimension items and writes the rest', async () => {
+ const files = [
+ { id: 'file-ok-1', vector: new Array(768).fill(0.1), meta: { path: '/docs/ok-1.txt' } },
+ { id: 'file-stale', vector: new Array(384).fill(0.1), meta: { path: '/docs/stale.txt' } },
+ { id: 'file-ok-2', vector: new Array(768).fill(0.2), meta: { path: '/docs/ok-2.txt' } }
+ ];
+
+ const result = await service.batchUpsertFiles(files);
+
+ expect(result.count).toBe(2);
+ expect(result.failed).toEqual([
+ { id: 'file-stale', error: 'dimension_mismatch', requiresRebuild: true }
+ ]);
+ expect(await service.getFile('file-ok-1')).not.toBeNull();
+ expect(await service.getFile('file-ok-2')).not.toBeNull();
+ expect(await service.getFile('file-stale')).toBeNull();
+ });
+
test('batchUpsertFolders uses bounded worker concurrency', async () => {
service._batchUpsertConcurrency = 2;
let active = 0;
diff --git a/test/OrganizationSuggestionService.test.js b/test/OrganizationSuggestionService.test.js
index 6d617364..ee6abeaf 100644
--- a/test/OrganizationSuggestionService.test.js
+++ b/test/OrganizationSuggestionService.test.js
@@ -424,6 +424,20 @@ describe('OrganizationSuggestionService', () => {
expect(service.feedbackHistory[0].file.name).toBe(file.name);
});
+ // Startup-scan learning counts toward the pattern but writes no
+ // feedback-history row (the capped list undo retracts from).
+ test('recordScanFeedback updates the pattern without a history row, once per key', async () => {
+ const file = createTestFile();
+ const suggestion = { folder: 'Invoices', path: '/docs/Invoices', confidence: 0.8 };
+
+ expect(await service.recordScanFeedback(file, suggestion, 'scan-key-1')).toBe(true);
+ expect(await service.recordScanFeedback(file, suggestion, 'scan-key-1')).toBe(false);
+
+ expect(service.userPatterns.get('pdf:documents:invoices').count).toBe(1);
+ expect(service.feedbackHistory).toHaveLength(0);
+ expect(service.patternMatcher.exportPatterns().scanLearnedKeys).toEqual(['scan-key-1']);
+ });
+
// Test 8: Batch Suggestions - Project Detection
test('should detect common project in batch suggestions', async () => {
const files = [
diff --git a/test/OrganizeResumeService.caseOnlyRename.test.js b/test/OrganizeResumeService.caseOnlyRename.test.js
new file mode 100644
index 00000000..f6216543
--- /dev/null
+++ b/test/OrganizeResumeService.caseOnlyRename.test.js
@@ -0,0 +1,76 @@
+/**
+ * @jest-environment node
+ */
+/**
+ * Resuming a case-only rename (Invoice.pdf -> invoice.pdf) on a
+ * case-insensitive filesystem found the source itself at the destination,
+ * took the name for occupied, and committed the file as `invoice_1.pdf`.
+ * Both the resume collision walk and atomicMove now treat a destination that
+ * is the source itself (same dev + ino) as free.
+ *
+ * On a case-sensitive host the other-cased name simply does not exist, so the
+ * same expectations hold there too.
+ */
+
+jest.unmock('fs');
+jest.unmock('fs/promises');
+jest.unmock('os');
+
+const path = require('path');
+const fs = require('fs').promises;
+const os = require('os');
+
+const { resumeIncompleteBatches } = require('../src/main/services/OrganizeResumeService');
+const { atomicFileOps } = require('../src/shared/atomicFileOperations');
+
+describe('case-only rename keeps its name', () => {
+ let testDir;
+
+ beforeEach(async () => {
+ testDir = await fs.mkdtemp(path.join(os.tmpdir(), 'resume-case-only-'));
+ });
+
+ afterEach(async () => {
+ await fs.rm(testDir, { recursive: true, force: true }).catch(() => {});
+ });
+
+ test('atomicMove renames Invoice.pdf to invoice.pdf, not invoice_1.pdf', async () => {
+ const source = path.join(testDir, 'Invoice.pdf');
+ const dest = path.join(testDir, 'invoice.pdf');
+ await fs.writeFile(source, 'invoice-bytes');
+
+ const committed = await atomicFileOps.atomicMove(source, dest);
+
+ expect(path.basename(committed)).toBe('invoice.pdf');
+ expect(await fs.readdir(testDir)).toEqual(['invoice.pdf']);
+ });
+
+ test('resume commits the case-only rename under the planned name', async () => {
+ const source = path.join(testDir, 'Invoice.pdf');
+ const dest = path.join(testDir, 'invoice.pdf');
+ await fs.writeFile(source, 'invoice-bytes');
+
+ const markOrganizeOpDone = jest.fn(async () => {});
+ const markOrganizeOpError = jest.fn(async () => {});
+ const serviceIntegration = {
+ processingState: {
+ getIncompleteOrganizeBatches: () => [
+ { id: 'b1', operations: [{ source, destination: dest, status: 'pending' }] }
+ ],
+ markOrganizeOpStarted: jest.fn(async () => {}),
+ markOrganizeOpDone,
+ markOrganizeOpError,
+ completeOrganizeBatch: jest.fn(async () => {})
+ }
+ };
+ const logger = { info: jest.fn(), warn: jest.fn(), debug: jest.fn() };
+
+ await resumeIncompleteBatches(serviceIntegration, logger, () => null);
+
+ expect(markOrganizeOpError).not.toHaveBeenCalled();
+ const committed = markOrganizeOpDone.mock.calls.at(-1)?.[2]?.destination;
+ expect(path.basename(committed)).toBe('invoice.pdf');
+ expect(await fs.readdir(testDir)).toEqual(['invoice.pdf']);
+ expect(await fs.readFile(dest, 'utf8')).toBe('invoice-bytes');
+ });
+});
diff --git a/test/OrganizeResumeService.collisionRecovery.test.js b/test/OrganizeResumeService.collisionRecovery.test.js
index 9f1f50b6..d6a5e3b9 100644
--- a/test/OrganizeResumeService.collisionRecovery.test.js
+++ b/test/OrganizeResumeService.collisionRecovery.test.js
@@ -232,7 +232,11 @@ describe('OrganizeResumeService: crash after a collision-suffixed move', () => {
}
]);
- await resumeIncompleteBatches({ processingState }, logger, getMainWindow);
+ // sorted/ is a Smart Folder, so the destination policy allows the moves.
+ const smartFolderWatcher = {
+ getSmartFolders: () => [{ path: path.join(testDir, 'sorted') }]
+ };
+ await resumeIncompleteBatches({ processingState, smartFolderWatcher }, logger, getMainWindow);
expect(processingState.markOrganizeOpError).not.toHaveBeenCalled();
// r_1 is the other file's name, so the first goes past it; the second
diff --git a/test/OrganizeResumeService.locking.test.js b/test/OrganizeResumeService.locking.test.js
index a4211069..a8d1ee47 100644
--- a/test/OrganizeResumeService.locking.test.js
+++ b/test/OrganizeResumeService.locking.test.js
@@ -83,6 +83,8 @@ function makeBatch(overrides = {}) {
function makeServiceIntegration(batches) {
return {
+ // A Smart Folder, so the destination policy allows the replayed move.
+ smartFolderWatcher: { getSmartFolders: () => [{ path: '/organized' }] },
processingState: {
getIncompleteOrganizeBatches: jest.fn().mockReturnValue(batches),
markOrganizeOpStarted: jest.fn().mockResolvedValue(undefined),
diff --git a/test/OrganizeResumeService.policy.test.js b/test/OrganizeResumeService.policy.test.js
new file mode 100644
index 00000000..f600911b
--- /dev/null
+++ b/test/OrganizeResumeService.policy.test.js
@@ -0,0 +1,218 @@
+/**
+ * @jest-environment node
+ */
+/**
+ * Startup resume replays journaled organize ops without anyone asking, so it
+ * must hold every move to the live handler's rules: a folder the user
+ * declined (or that would need confirming) is refused rather than prompted
+ * for, ops the live run refused stay refused, and the strict allowlist
+ * applies. It must also leave alone a batch a live run owns: one started in
+ * this session, or one closed while resume waited for the batch lock.
+ */
+
+const path = require('path');
+const fs = require('fs').promises;
+const fssync = require('fs');
+const os = require('os');
+const { dialog } = require('electron');
+const { resumeIncompleteBatches } = require('../src/main/services/OrganizeResumeService');
+const { acquireBatchLock, releaseBatchLock } = require('../src/main/ipc/files/batchLockManager');
+const { _resetDestinationPolicyForTests } = require('../src/main/ipc/files/destinationPolicy');
+
+describe('OrganizeResumeService replay policy', () => {
+ let testDir;
+ let inbox;
+ let sorted;
+ let elsewhere;
+ let processingState;
+ let logger;
+ const getMainWindow = () => null;
+ const savedStrict = process.env.STRATOSORT_STRICT_FILE_OPS;
+
+ /** @param {any[]} batches */
+ function makeProcessingState(batches) {
+ return {
+ getIncompleteOrganizeBatches: jest.fn().mockReturnValue(batches),
+ markOrganizeOpStarted: jest.fn().mockResolvedValue(undefined),
+ markOrganizeOpDone: jest.fn().mockResolvedValue(undefined),
+ markOrganizeOpError: jest.fn().mockResolvedValue(undefined),
+ markOrganizeOpsPersisted: jest.fn().mockResolvedValue(undefined),
+ completeOrganizeBatch: jest.fn().mockResolvedValue(undefined)
+ };
+ }
+
+ function smartFolderWatcher() {
+ return { getSmartFolders: () => [{ path: sorted }], watchedPaths: [sorted] };
+ }
+
+ beforeEach(async () => {
+ jest.clearAllMocks();
+ _resetDestinationPolicyForTests();
+ delete process.env.STRATOSORT_STRICT_FILE_OPS;
+ testDir = await fs.mkdtemp(path.join(os.tmpdir(), 'resume-policy-'));
+ inbox = path.join(testDir, 'inbox');
+ sorted = path.join(testDir, 'sorted');
+ elsewhere = path.join(testDir, 'elsewhere');
+ await Promise.all([inbox, sorted, elsewhere].map((d) => fs.mkdir(d, { recursive: true })));
+ logger = { info: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() };
+ });
+
+ afterEach(async () => {
+ if (savedStrict === undefined) delete process.env.STRATOSORT_STRICT_FILE_OPS;
+ else process.env.STRATOSORT_STRICT_FILE_OPS = savedStrict;
+ await fs.rm(testDir, { recursive: true, force: true }).catch(() => {});
+ });
+
+ test('refuses, without a dialog, a pending move into a folder that is not trusted', async () => {
+ const source = path.join(inbox, 'a.txt');
+ const destination = path.join(elsewhere, 'a.txt');
+ await fs.writeFile(source, 'A');
+ processingState = makeProcessingState([
+ { id: 'batch1', operations: [{ source, destination, status: 'pending' }] }
+ ]);
+
+ await resumeIncompleteBatches(
+ { processingState, smartFolderWatcher: smartFolderWatcher() },
+ logger,
+ getMainWindow
+ );
+
+ expect(fssync.existsSync(source)).toBe(true);
+ expect(fssync.existsSync(destination)).toBe(false);
+ expect(dialog.showMessageBox).not.toHaveBeenCalled();
+ expect(processingState.markOrganizeOpStarted).not.toHaveBeenCalled();
+ expect(processingState.markOrganizeOpError).toHaveBeenCalledWith(
+ 'batch1',
+ 0,
+ expect.stringMatching(/^Invalid destination path: /)
+ );
+ expect(processingState.markOrganizeOpDone).not.toHaveBeenCalled();
+ expect(processingState.completeOrganizeBatch).toHaveBeenCalledWith('batch1');
+ });
+
+ test('still replays a pending move into a Smart Folder', async () => {
+ const source = path.join(inbox, 'a.txt');
+ const destination = path.join(sorted, 'a.txt');
+ await fs.writeFile(source, 'A');
+ processingState = makeProcessingState([
+ { id: 'batch1', operations: [{ source, destination, status: 'pending' }] }
+ ]);
+
+ await resumeIncompleteBatches(
+ { processingState, smartFolderWatcher: smartFolderWatcher() },
+ logger,
+ getMainWindow
+ );
+
+ expect(await fs.readFile(destination, 'utf8')).toBe('A');
+ expect(processingState.markOrganizeOpError).not.toHaveBeenCalled();
+ expect(processingState.markOrganizeOpDone).toHaveBeenCalledWith('batch1', 0, { destination });
+ });
+
+ test('leaves an op the live run refused failed, even if its folder is allowed now', async () => {
+ const source = path.join(inbox, 'a.txt');
+ const destination = path.join(sorted, 'a.txt');
+ await fs.writeFile(source, 'A');
+ processingState = makeProcessingState([
+ {
+ id: 'batch1',
+ operations: [
+ {
+ source,
+ destination,
+ status: 'failed',
+ error: `Invalid destination path: Destination folder was not approved: ${sorted}`
+ }
+ ]
+ }
+ ]);
+
+ await resumeIncompleteBatches(
+ { processingState, smartFolderWatcher: smartFolderWatcher() },
+ logger,
+ getMainWindow
+ );
+
+ expect(fssync.existsSync(source)).toBe(true);
+ expect(fssync.existsSync(destination)).toBe(false);
+ expect(processingState.markOrganizeOpStarted).not.toHaveBeenCalled();
+ expect(processingState.markOrganizeOpDone).not.toHaveBeenCalled();
+ });
+
+ test('applies the strict allowlist to the source of a replayed move', async () => {
+ process.env.STRATOSORT_STRICT_FILE_OPS = 'true';
+ const source = path.join(inbox, 'a.txt');
+ const destination = path.join(sorted, 'a.txt');
+ await fs.writeFile(source, 'A');
+ processingState = makeProcessingState([
+ { id: 'batch1', operations: [{ source, destination, status: 'pending' }] }
+ ]);
+
+ await resumeIncompleteBatches(
+ { processingState, smartFolderWatcher: smartFolderWatcher() },
+ logger,
+ getMainWindow
+ );
+
+ expect(fssync.existsSync(source)).toBe(true);
+ expect(processingState.markOrganizeOpError).toHaveBeenCalledWith(
+ 'batch1',
+ 0,
+ expect.stringMatching(/^Invalid source path: /)
+ );
+ });
+
+ test('skips a batch this session started', async () => {
+ const source = path.join(inbox, 'a.txt');
+ const destination = path.join(sorted, 'a.txt');
+ await fs.writeFile(source, 'A');
+ processingState = makeProcessingState([
+ { id: 'live', operations: [{ source, destination, status: 'pending' }], pausedAt: 'x' }
+ ]);
+ processingState.isSessionOrganizeBatch = jest.fn((id) => id === 'live');
+
+ await resumeIncompleteBatches(
+ { processingState, smartFolderWatcher: smartFolderWatcher() },
+ logger,
+ getMainWindow
+ );
+
+ expect(fssync.existsSync(source)).toBe(true);
+ expect(processingState.markOrganizeOpStarted).not.toHaveBeenCalled();
+ // A paused live batch must stay open so the renderer's Resume still works.
+ expect(processingState.completeOrganizeBatch).not.toHaveBeenCalled();
+ });
+
+ test('does not replay a batch a live run closed while resume waited for the lock', async () => {
+ const source = path.join(inbox, 'a.txt');
+ const destination = path.join(sorted, 'a.txt');
+ await fs.writeFile(source, 'A');
+ const batch = {
+ id: 'batch_1700000000000_0000abcd',
+ completedAt: null,
+ operations: [{ source, destination, status: 'pending' }]
+ };
+ processingState = makeProcessingState([batch]);
+
+ // A live run holds the batch; the user cancels it, which closes the
+ // journal entry with this op still pending.
+ expect(await acquireBatchLock(batch.id)).toBe(true);
+ const run = resumeIncompleteBatches(
+ { processingState, smartFolderWatcher: smartFolderWatcher() },
+ logger,
+ getMainWindow
+ );
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ batch.completedAt = new Date().toISOString();
+ releaseBatchLock(batch.id);
+ await run;
+
+ expect(fssync.existsSync(source)).toBe(true);
+ expect(fssync.existsSync(destination)).toBe(false);
+ expect(processingState.markOrganizeOpStarted).not.toHaveBeenCalled();
+ expect(processingState.completeOrganizeBatch).not.toHaveBeenCalled();
+ // The lock was handed back.
+ await expect(acquireBatchLock('probe', 1000)).resolves.toBe(true);
+ releaseBatchLock('probe');
+ });
+});
diff --git a/test/PatternPersistence.test.js b/test/PatternPersistence.test.js
index 56420897..25a6b80e 100644
--- a/test/PatternPersistence.test.js
+++ b/test/PatternPersistence.test.js
@@ -84,6 +84,18 @@ describe('PatternPersistence', () => {
expect(loaded.feedbackHistory).toEqual([withKey, withoutKey]);
});
+ it('keeps the startup-scan learned keys across a load, and loads files saved without them', async () => {
+ fs.readFile.mockResolvedValueOnce(
+ JSON.stringify({ patterns: [], feedbackHistory: [], scanLearnedKeys: ['a.pdf\u0000finance'] })
+ );
+ const withKeys = await new PatternPersistence().load();
+ expect(withKeys.scanLearnedKeys).toEqual(['a.pdf\u0000finance']);
+
+ fs.readFile.mockResolvedValueOnce(JSON.stringify({ patterns: [], feedbackHistory: [] }));
+ const older = await new PatternPersistence().load();
+ expect(older.scanLearnedKeys).toEqual([]);
+ });
+
it('awaits deferred throttled save completion', async () => {
jest.useFakeTimers();
try {
diff --git a/test/ProcessingStateService.sessionBatches.test.js b/test/ProcessingStateService.sessionBatches.test.js
new file mode 100644
index 00000000..b4340773
--- /dev/null
+++ b/test/ProcessingStateService.sessionBatches.test.js
@@ -0,0 +1,69 @@
+/**
+ * Startup resume tells a crash-interrupted batch from a live one by asking
+ * whether this process created it; a batch loaded from the journal on disk
+ * is never a session batch.
+ */
+
+jest.mock('electron', () => ({
+ app: {
+ getPath: jest.fn(() => 'C:\\fake-user-data')
+ }
+}));
+
+jest.mock('../src/shared/logger', () => ({
+ createLogger: () => ({
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn()
+ })
+}));
+
+const fs = require('fs').promises;
+const ProcessingStateService = require('../src/main/services/ProcessingStateService');
+
+describe('ProcessingStateService.isSessionOrganizeBatch', () => {
+ beforeEach(() => {
+ jest.restoreAllMocks();
+ jest.spyOn(fs, 'readFile').mockResolvedValue(
+ JSON.stringify({
+ schemaVersion: '1.0.0',
+ analysis: { jobs: {}, ready: {}, lastUpdated: '' },
+ organize: {
+ batches: {
+ 'from-disk': {
+ id: 'from-disk',
+ operations: [{ source: '/a', destination: '/b', status: 'pending' }],
+ startedAt: '2026-01-01T00:00:00.000Z',
+ completedAt: null
+ }
+ },
+ lastUpdated: ''
+ }
+ })
+ );
+ jest.spyOn(fs, 'writeFile').mockResolvedValue();
+ jest.spyOn(fs, 'rename').mockResolvedValue();
+ jest.spyOn(fs, 'mkdir').mockResolvedValue();
+ jest.spyOn(fs, 'unlink').mockResolvedValue();
+ });
+
+ test('is true only for batches this process created', async () => {
+ const service = new ProcessingStateService();
+ jest.spyOn(service, 'saveState').mockResolvedValue(undefined);
+ await service.initialize();
+
+ await service.createOrLoadOrganizeBatch('live', [{ source: '/c', destination: '/d' }]);
+ // Loading an existing entry does not make it a session batch.
+ await service.createOrLoadOrganizeBatch('from-disk', []);
+
+ expect(service.isSessionOrganizeBatch('live')).toBe(true);
+ expect(service.isSessionOrganizeBatch('from-disk')).toBe(false);
+ expect(
+ service
+ .getIncompleteOrganizeBatches()
+ .map((b) => b.id)
+ .sort()
+ ).toEqual(['from-disk', 'live']);
+ });
+});
diff --git a/test/QueryProcessor.spellCorrection.test.js b/test/QueryProcessor.spellCorrection.test.js
new file mode 100644
index 00000000..5e6c31c9
--- /dev/null
+++ b/test/QueryProcessor.spellCorrection.test.js
@@ -0,0 +1,127 @@
+/**
+ * Spell correction must not replace correctly spelled words.
+ *
+ * Uses the real wink-nlp English model (QueryProcessor.test.js mocks it) so
+ * the lexicon check runs against the shipped vocabulary.
+ */
+
+jest.mock('../src/shared/logger', () => {
+ const logger = {
+ setContext: jest.fn(),
+ info: jest.fn(),
+ debug: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn()
+ };
+ return { logger, createLogger: jest.fn(() => logger) };
+});
+
+const { QueryProcessor, resetInstance } = require('../src/main/services/QueryProcessor');
+
+describe('QueryProcessor spell correction keeps real words', () => {
+ let processor;
+
+ beforeEach(() => {
+ resetInstance();
+ processor = new QueryProcessor();
+ });
+
+ afterEach(() => {
+ processor.cleanup();
+ resetInstance();
+ });
+
+ test.each([
+ ['audit', 'audio'],
+ ['protect', 'project'],
+ ['personality', 'presentation']
+ ])('does not correct the English word "%s" to "%s"', (word) => {
+ expect(processor._correctSpelling(word)).toBe(word);
+ });
+
+ test('still corrects a real typo', () => {
+ expect(processor._correctSpelling('vacaton')).toBe('vacation');
+ });
+
+ test('a typo the model has already read is still a typo', async () => {
+ // Reading text adds its unknown words to wink's runtime lexicon; those
+ // must not count as English.
+ await processor._getSynonyms('vacaton');
+ expect(processor._correctSpelling('vacaton')).toBe('vacation');
+ });
+
+ test('a Soundex match alone does not correct a word', () => {
+ // Without the lexicon only the edit-distance gate is left: "personality"
+ // shares Soundex P625 with "presentation" but is far more than 2 edits away.
+ processor._getNlp = () => null;
+ expect(processor._soundex('personality')).toBe(processor._soundex('presentation'));
+ expect(processor._correctSpelling('personality')).toBe('personality');
+ });
+
+ test('a search for an English word sends it unchanged', async () => {
+ const result = await processor.processQuery('protect audit', {
+ expandSynonyms: false,
+ correctSpelling: true
+ });
+
+ expect(result.corrections).toEqual([]);
+ expect(result.corrected).toBe('protect audit');
+ expect(result.expanded.split(' ')).toEqual(['protect', 'audit']);
+ });
+
+ test('the keyword query keeps the typed term next to its correction', async () => {
+ const result = await processor.processQuery('vacaton', {
+ expandSynonyms: false,
+ correctSpelling: true
+ });
+
+ expect(result.corrected).toBe('vacation');
+ expect(result.expanded.split(' ')).toEqual(expect.arrayContaining(['vacaton', 'vacation']));
+ });
+});
+
+describe('QueryProcessor spell correction checks the indexed vocabulary', () => {
+ let processor;
+
+ beforeEach(() => {
+ resetInstance();
+ processor = new QueryProcessor();
+ });
+
+ afterEach(() => {
+ processor.cleanup();
+ resetInstance();
+ });
+
+ test('does not correct a word that occurs in the indexed files', async () => {
+ // "budgen" is one edit from the domain word "budget" and is not English,
+ // but here it is a surname in the user's files.
+ const isIndexedTerm = (word) => word === 'budgen';
+ expect(processor._correctSpelling('budgen', isIndexedTerm)).toBe('budgen');
+
+ const result = await processor.processQuery('Budgen projekt', {
+ expandSynonyms: false,
+ correctSpelling: true,
+ isIndexedTerm: (word) => word === 'budgen' || word === 'projekt'
+ });
+ expect(result.corrections).toEqual([]);
+ expect(result.corrected).toBe('Budgen projekt');
+ });
+
+ test('prefers a correction that occurs in the indexed files', () => {
+ processor.domainWords.add('marker');
+ processor.domainWords.add('market');
+
+ expect(processor._correctSpelling('markex')).toBe('marker');
+ expect(processor._correctSpelling('markex', (word) => word === 'market')).toBe('market');
+ });
+
+ test('keeps the index-free behavior when the index cannot answer', () => {
+ expect(processor._correctSpelling('budgen', () => null)).toBe('budget');
+ expect(
+ processor._correctSpelling('budgen', () => {
+ throw new Error('index not ready');
+ })
+ ).toBe('budget');
+ });
+});
diff --git a/test/RelationshipIndexService.pipeInPath.test.js b/test/RelationshipIndexService.pipeInPath.test.js
new file mode 100644
index 00000000..f42e22dc
--- /dev/null
+++ b/test/RelationshipIndexService.pipeInPath.test.js
@@ -0,0 +1,72 @@
+/**
+ * Edge keys used to be `${source}|${target}` and were split back on '|'. On
+ * macOS and Linux a file name may contain '|', so such a path was cut in two
+ * and the edge matched neither file: it vanished from getEdges and the Relate
+ * view.
+ */
+jest.mock('electron', () => jest.requireActual('./mocks/electron'));
+
+jest.mock('../src/shared/logger', () => ({
+ createLogger: jest.fn(() => ({
+ info: jest.fn(),
+ debug: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn()
+ }))
+}));
+
+jest.mock('fs', () => ({
+ promises: {
+ readFile: jest.fn(async () => {
+ const error = new Error('ENOENT');
+ // @ts-ignore
+ error.code = 'ENOENT';
+ throw error;
+ }),
+ writeFile: jest.fn(async () => {}),
+ rename: jest.fn(async () => {}),
+ unlink: jest.fn(async () => {})
+ }
+}));
+
+const RelationshipIndexService = require('../src/main/services/RelationshipIndexService');
+const { getSemanticFileId } = require('../src/shared/fileIdUtils');
+const { normalizePathForIndex } = require('../src/shared/pathSanitization');
+
+const idFor = (/** @type {string} */ p) => getSemanticFileId(normalizePathForIndex(p));
+
+function makeService(/** @type {Record} */ paths) {
+ const entries = Object.fromEntries(
+ Object.entries(paths).map(([id, originalPath]) => [
+ id,
+ { id, originalPath, analysis: { tags: ['finance', 'quarterly', 'report'] } }
+ ])
+ );
+ return new RelationshipIndexService({
+ analysisHistoryService: {
+ initialize: jest.fn(),
+ analysisHistory: { updatedAt: '2026-11-01T00:00:00.000Z', entries }
+ }
+ });
+}
+
+describe('RelationshipIndexService with "|" in a file path', () => {
+ test.each([
+ ['the piped path sorts second', '/files/Q1|Q2 report.pdf', '/files/A summary.pdf'],
+ ['the piped path sorts first', '/files/A|B report.pdf', '/files/Z summary.pdf']
+ ])('keeps both endpoints whole when %s', async (_label, pipedPath, otherPath) => {
+ const service = makeService({ doc1: pipedPath, doc2: otherPath });
+ const pipedId = idFor(pipedPath);
+ const otherId = idFor(otherPath);
+
+ const built = await service.buildIndex();
+ expect(built.success).toBe(true);
+ expect(built.edges).toHaveLength(1);
+ const [edge] = built.edges;
+ expect([edge.source, edge.target].sort()).toEqual([pipedId, otherId].sort());
+ expect(edge.id).toBe(`rel:${edge.source}->${edge.target}`);
+
+ const { edges } = await service.getEdges([pipedId, otherId]);
+ expect(edges).toHaveLength(1);
+ });
+});
diff --git a/test/SearchAutocomplete.recentSearchesSync.test.js b/test/SearchAutocomplete.recentSearchesSync.test.js
new file mode 100644
index 00000000..e77a1523
--- /dev/null
+++ b/test/SearchAutocomplete.recentSearchesSync.test.js
@@ -0,0 +1,72 @@
+/**
+ * @jest-environment jsdom
+ */
+
+// SearchAutocomplete used to load recent searches once on mount. Searches
+// recorded afterwards (useSearchTab calls addToRecentSearches) never showed in
+// its dropdown, and removing one entry wrote the stale mount-time list back,
+// erasing every search made since the component mounted.
+
+import React from 'react';
+import { render, screen, fireEvent, act } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import SearchAutocomplete, {
+ addToRecentSearches,
+ clearRecentSearches
+} from '../src/renderer/components/search/SearchAutocomplete';
+
+const KEY = 'stratosort-recent-searches';
+const stored = () => JSON.parse(window.localStorage.getItem(KEY) || '[]');
+
+beforeAll(() => {
+ Element.prototype.scrollIntoView = jest.fn();
+ window.electronAPI = { embeddings: { search: jest.fn() } };
+});
+
+beforeEach(() => {
+ window.localStorage.clear();
+});
+
+describe('SearchAutocomplete recent searches stay in sync with storage', () => {
+ test('removing an old entry keeps searches recorded after mount', () => {
+ window.localStorage.setItem(KEY, JSON.stringify(['taxes', 'budget']));
+ render();
+
+ act(() => {
+ addToRecentSearches('invoice');
+ addToRecentSearches('receipts');
+ });
+
+ fireEvent.click(screen.getByRole('combobox'));
+ const taxesRow = screen.getByText('taxes').closest('[role="option"]');
+ const removeButton = taxesRow.querySelector('[aria-label="Remove from history"]');
+ fireEvent.click(removeButton);
+
+ expect(stored()).toEqual(['receipts', 'invoice', 'budget']);
+ });
+
+ test('the dropdown shows searches recorded after mount', () => {
+ window.localStorage.setItem(KEY, JSON.stringify(['taxes']));
+ render();
+
+ act(() => {
+ addToRecentSearches('invoice');
+ });
+ fireEvent.click(screen.getByRole('combobox'));
+
+ expect(screen.getByText('invoice')).toBeInTheDocument();
+ expect(screen.getByText('taxes')).toBeInTheDocument();
+ });
+
+ test('clearing history elsewhere empties the dropdown', () => {
+ window.localStorage.setItem(KEY, JSON.stringify(['taxes']));
+ render();
+
+ act(() => {
+ clearRecentSearches();
+ });
+ fireEvent.click(screen.getByRole('combobox'));
+
+ expect(screen.queryByText('taxes')).not.toBeInTheDocument();
+ });
+});
diff --git a/test/SearchService.dimensionMismatch.test.js b/test/SearchService.dimensionMismatch.test.js
index 8fcd9c7b..db3f100b 100644
--- a/test/SearchService.dimensionMismatch.test.js
+++ b/test/SearchService.dimensionMismatch.test.js
@@ -83,7 +83,7 @@ describe('SearchService — dimension mismatch must surface, not silently degrad
const service = makeService();
await expect(service.vectorSearch('quarterly report', 5)).rejects.toMatchObject({
isDimensionMismatch: true,
- message: expect.stringContaining('rebuild your search index')
+ message: expect.stringMatching(/rebuild your search index/i)
});
});
@@ -119,7 +119,7 @@ describe('SearchService — dimension mismatch must surface, not silently degrad
expect.objectContaining({
type: 'VECTOR_DIMENSION_MISMATCH',
severity: 'high',
- message: expect.stringContaining('rebuild your search index')
+ message: expect.stringMatching(/rebuild your search index/i)
})
])
);
@@ -135,6 +135,6 @@ describe('SearchService — dimension mismatch must surface, not silently degrad
});
expect(result.success).toBe(false);
- expect(result.error).toContain('rebuild your search index');
+ expect(result.error).toMatch(/rebuild your search index/i);
});
});
diff --git a/test/SearchService.indexVocabulary.test.js b/test/SearchService.indexVocabulary.test.js
new file mode 100644
index 00000000..1de144e1
--- /dev/null
+++ b/test/SearchService.indexVocabulary.test.js
@@ -0,0 +1,100 @@
+/**
+ * Spell correction checks query words against the BM25 index vocabulary:
+ * a word the user's files contain (a surname, a project name) is never
+ * "corrected" away.
+ *
+ * Uses a real Orama index and the real QueryProcessor (with the shipped
+ * wink-nlp model) so the lookup runs against the same tokens BM25 matches.
+ */
+
+jest.mock('../src/shared/logger', () => {
+ const logger = {
+ setContext: jest.fn(),
+ info: jest.fn(),
+ debug: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn()
+ };
+ return { logger, createLogger: jest.fn(() => logger) };
+});
+
+const { SearchService } = require('../src/main/services/SearchService');
+const { QueryProcessor, resetInstance } = require('../src/main/services/QueryProcessor');
+
+function createService(queryProcessor) {
+ const analysisHistoryService = {
+ initialize: jest.fn().mockResolvedValue(undefined),
+ analysisHistory: {
+ metadata: { totalEntries: 1 },
+ entries: {
+ e1: {
+ id: 'e1',
+ originalPath: '/docs/letter.pdf',
+ fileName: 'letter.pdf',
+ timestamp: '2026-01-01T00:00:00.000Z',
+ analysis: {
+ subject: 'Letter from Budgen',
+ summary: 'Budgen asks about the Kubernetes rollout',
+ tags: ['correspondence'],
+ extractedText: 'Dear team, Budgen here about the Kubernetes rollout.'
+ }
+ }
+ }
+ }
+ };
+ const service = new SearchService({
+ vectorDbService: { getStats: jest.fn().mockResolvedValue({ files: 0, fileChunks: 0 }) },
+ analysisHistoryService,
+ parallelEmbeddingService: { embedText: jest.fn() },
+ queryProcessor
+ });
+ service._validateFileExistence = jest.fn(async (results) => ({
+ validResults: results,
+ ghostCount: 0
+ }));
+ return service;
+}
+
+describe('SearchService spell correction uses the index vocabulary', () => {
+ let processor;
+
+ beforeEach(() => {
+ resetInstance();
+ processor = new QueryProcessor();
+ });
+
+ afterEach(() => {
+ processor.cleanup();
+ resetInstance();
+ });
+
+ test('isIndexedTerm answers from the BM25 index and is null before it is built', async () => {
+ const service = createService(processor);
+ expect(service.isIndexedTerm('budgen')).toBeNull();
+
+ await service.buildBM25Index();
+
+ expect(service.isIndexedTerm('Budgen')).toBe(true);
+ expect(service.isIndexedTerm('kubernetes')).toBe(true);
+ expect(service.isIndexedTerm('budget')).toBe(false);
+ });
+
+ test('a word that occurs in the indexed files is not corrected', async () => {
+ const service = createService(processor);
+ await service.buildBM25Index();
+
+ // Without the index check "budgen" is corrected to the domain word "budget".
+ expect(processor._correctSpelling('budgen')).toBe('budget');
+
+ const result = await service.hybridSearch('budgen', {
+ mode: 'bm25',
+ correctSpelling: true,
+ expandSynonyms: false
+ });
+
+ expect(result.success).toBe(true);
+ expect(result.queryMeta.corrections).toEqual([]);
+ expect(result.queryMeta.corrected).toBe('budgen');
+ expect(result.results.map((r) => r.id)).toHaveLength(1);
+ });
+});
diff --git a/test/SettingsBackupService.preRestoreSnapshot.test.js b/test/SettingsBackupService.preRestoreSnapshot.test.js
index 14f3c3a8..312442f4 100644
--- a/test/SettingsBackupService.preRestoreSnapshot.test.js
+++ b/test/SettingsBackupService.preRestoreSnapshot.test.js
@@ -106,6 +106,29 @@ describe('SettingsBackupService pre-restore snapshot', () => {
expect(snapshot.settings.confidenceThreshold).toBe(0.6);
});
+ test('restoring the oldest automatic backup does not rotate it out', async () => {
+ const oldest = await writeUserBackup({ confidenceThreshold: 0.33 });
+ await new Promise((resolve) => setTimeout(resolve, 5));
+ await writeUserBackup({ confidenceThreshold: 0.4 });
+ await new Promise((resolve) => setTimeout(resolve, 5));
+
+ // Two kept: the snapshot taken before the restore would push the oldest out.
+ const service = new SettingsBackupService({
+ backupDir: BACKUP_DIR,
+ maxBackups: 2,
+ defaults: { confidenceThreshold: 0.75 },
+ loadSettings: async () => ({ confidenceThreshold: 0.6 })
+ });
+ const saveSettings = jest.fn().mockResolvedValue({ success: true });
+ const result = await service.restoreFromBackup(oldest, saveSettings);
+
+ expect(result.success).toBe(true);
+ expect(fsSync.existsSync(oldest)).toBe(true);
+ // Restoring it a second time still works.
+ const again = await service.restoreFromBackup(oldest, saveSettings);
+ expect(again.success).toBe(true);
+ });
+
test('preRestoreBackup: false restores without writing a snapshot', async () => {
const userBackup = await writeUserBackup({ confidenceThreshold: 0.33 });
const loadSettings = jest.fn(async () => ({ confidenceThreshold: 0.75 }));
diff --git a/test/SettingsService.restoreRuntimeDefaults.test.js b/test/SettingsService.restoreRuntimeDefaults.test.js
new file mode 100644
index 00000000..692aaafd
--- /dev/null
+++ b/test/SettingsService.restoreRuntimeDefaults.test.js
@@ -0,0 +1,160 @@
+/**
+ * Restoring a backup (from Settings, or by auto-recovery after a corrupt
+ * settings.json) writes the same on-disk shape as save(): the user's values
+ * only. The backup's settings come from load(), which fills in this
+ * machine's resolved Documents folder, so a restore used to persist that
+ * path as if the user had chosen it, and it outlived a Documents move.
+ * Auto-recovery wrote the full merged object, stamping every default.
+ */
+
+// The Documents folder in this platform's own form, as Electron reports it.
+// A Windows path on Linux is not an absolute path there, so the settings
+// sanitizer drops it and the recovered location comes back undefined.
+const mockDocumentsDir =
+ process.platform === 'win32' ? 'C:\\Users\\a-user\\Documents' : '/home/a-user/Documents';
+
+jest.mock('electron', () => ({
+ app: {
+ getPath: jest.fn((name) => (name === 'documents' ? mockDocumentsDir : 'C:\\user-data'))
+ }
+}));
+
+const mockFiles = new Map();
+jest.mock('fs', () => {
+ const notFound = (/** @type {string} */ p) =>
+ Object.assign(new Error(`ENOENT: ${p}`), { code: 'ENOENT' });
+ return {
+ promises: {
+ readFile: jest.fn(async (p) => {
+ if (!mockFiles.has(p)) throw notFound(p);
+ return mockFiles.get(p);
+ }),
+ writeFile: jest.fn(async (p, data) => {
+ mockFiles.set(p, String(data));
+ }),
+ mkdir: jest.fn().mockResolvedValue(undefined),
+ readdir: jest.fn().mockResolvedValue([]),
+ stat: jest.fn(),
+ lstat: jest.fn().mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' })),
+ unlink: jest.fn().mockResolvedValue(undefined),
+ rename: jest.fn().mockResolvedValue(undefined),
+ access: jest.fn().mockResolvedValue(undefined)
+ },
+ watch: jest.fn(),
+ existsSync: jest.fn(() => true)
+ };
+});
+
+jest.mock('../src/shared/atomicFileOperations', () => ({
+ backupAndReplace: jest.fn(async (p, data) => {
+ mockFiles.set(p, String(data));
+ return { success: true };
+ })
+}));
+
+jest.mock('../src/shared/logger', () => {
+ const l = () => ({
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn(),
+ setContext: jest.fn()
+ });
+ return { logger: l(), createLogger: l };
+});
+
+// What the backup service hands the apply callback: the backup's settings
+// merged over the full defaults, as the real SettingsBackupService does.
+let mockRestoredSettings = null;
+jest.mock('../src/main/services/SettingsBackupService', () => ({
+ SettingsBackupService: jest.fn().mockImplementation(() => ({
+ backupDir: 'C:\\user-data\\settings-backups',
+ createBackup: jest.fn().mockResolvedValue({ success: true }),
+ listBackups: jest
+ .fn()
+ .mockResolvedValue([
+ { filename: 'b1.json', path: 'C:\\user-data\\settings-backups\\b1.json' }
+ ]),
+ restoreFromBackup: jest.fn(async (_backupPath, apply) => {
+ try {
+ await apply(mockRestoredSettings);
+ return { success: true, settings: mockRestoredSettings };
+ } catch (err) {
+ return { success: false, error: err.message };
+ }
+ }),
+ deleteBackup: jest.fn()
+ }))
+}));
+
+jest.mock('../src/main/ipc/ipcWrappers', () => ({ safeSend: jest.fn() }));
+
+const path = require('path');
+const { DEFAULT_SETTINGS } = require('../src/shared/defaultSettings');
+
+function loadService() {
+ jest.resetModules();
+ const SettingsService = require('../src/main/services/SettingsService');
+ jest.spyOn(SettingsService.prototype, '_startFileWatcher').mockImplementation(() => {});
+ const service = new SettingsService();
+ service._migrationChecked = true;
+ return service;
+}
+
+const readPersisted = (service) => JSON.parse(mockFiles.get(service.settingsPath));
+
+describe('SettingsService restore writes user values only', () => {
+ beforeEach(() => {
+ mockFiles.clear();
+ });
+
+ test('restoreFromBackup does not persist the resolved Documents path', async () => {
+ const service = loadService();
+ const runtimeDocuments = service.defaults.defaultSmartFolderLocation;
+ // The resolved path, not the literal the shared strip knows about.
+ expect(runtimeDocuments).not.toBe(DEFAULT_SETTINGS.defaultSmartFolderLocation);
+ mockRestoredSettings = { ...service.defaults, confidenceThreshold: 0.9 };
+
+ const result = await service.restoreFromBackup(path.join(service.backupDir, 'b1.json'));
+
+ expect(result.success).toBe(true);
+ const persisted = readPersisted(service);
+ expect(persisted).not.toHaveProperty('defaultSmartFolderLocation');
+ expect(persisted.confidenceThreshold).toBe(0.9);
+ // The in-memory settings stay complete.
+ expect(service._cache.defaultSmartFolderLocation).toBe(runtimeDocuments);
+ });
+
+ test('restoreFromBackup keeps a location the user chose', async () => {
+ const service = loadService();
+ mockRestoredSettings = {
+ ...service.defaults,
+ defaultSmartFolderLocation: 'D:\\Sorted'
+ };
+
+ await service.restoreFromBackup(path.join(service.backupDir, 'b1.json'));
+
+ expect(readPersisted(service).defaultSmartFolderLocation).toBe('D:\\Sorted');
+ });
+
+ test('auto-recovery writes only user values and keeps the backup schema stamp', async () => {
+ const service = loadService();
+ mockRestoredSettings = {
+ ...service.defaults,
+ confidenceThreshold: 0.9,
+ // Restore sets an older stamp so migrations re-run; it must survive.
+ settingsSchemaVersion: 1
+ };
+
+ const recovered = await service._attemptAutoRecovery();
+
+ expect(recovered).toBeTruthy();
+ const persisted = readPersisted(service);
+ expect(persisted).not.toHaveProperty('defaultSmartFolderLocation');
+ expect(persisted).not.toHaveProperty('notifications');
+ expect(persisted).not.toHaveProperty('workflowRestoreMaxAge');
+ expect(persisted.confidenceThreshold).toBe(0.9);
+ expect(persisted.settingsSchemaVersion).toBe(1);
+ expect(recovered.defaultSmartFolderLocation).toBe(service.defaults.defaultSmartFolderLocation);
+ });
+});
diff --git a/test/SmartFolderWatcher.nestedFolderRemoval.test.js b/test/SmartFolderWatcher.nestedFolderRemoval.test.js
new file mode 100644
index 00000000..e6c124a3
--- /dev/null
+++ b/test/SmartFolderWatcher.nestedFolderRemoval.test.js
@@ -0,0 +1,144 @@
+/**
+ * @jest-environment node
+ *
+ * Smart Folders can nest. chokidar's unwatch() closes and ignores the whole
+ * subtree of the path it is given, and a later add() lifts that ignore only
+ * for the exact path added. Removing a nested Smart Folder used to unwatch it
+ * even though its parent was still watched, so new files there raised no
+ * events until a restart, and its queued analysis was dropped. Removing the
+ * outer folder blinded the inner one the same way.
+ */
+
+jest.mock('fs', () => jest.requireActual('fs'));
+jest.mock('fs/promises', () => jest.requireActual('fs/promises'));
+jest.mock('os', () => jest.requireActual('os'));
+jest.mock('chokidar', () => ({
+ watch: jest.fn(() => ({
+ on: jest.fn().mockReturnThis(),
+ once: jest.fn(),
+ close: jest.fn().mockResolvedValue()
+ }))
+}));
+jest.mock('../src/shared/logger', () => {
+ const logger = {
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn(),
+ setContext: jest.fn()
+ };
+ return { logger, createLogger: () => logger };
+});
+
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const SmartFolderWatcher = require('../src/main/services/SmartFolderWatcher');
+
+let base;
+let outer;
+let inner;
+let other;
+
+beforeEach(() => {
+ base = fs.mkdtempSync(path.join(os.tmpdir(), 'sfw-nested-'));
+ outer = path.join(base, 'Work');
+ inner = path.join(outer, 'Invoices');
+ other = path.join(base, 'Other');
+ fs.mkdirSync(inner, { recursive: true });
+ fs.mkdirSync(other);
+});
+
+afterEach(() => {
+ fs.rmSync(base, { recursive: true, force: true });
+});
+
+/** A running watcher over `watched` with a stand-in chokidar instance. */
+function makeWatcher(watched) {
+ const watcher = new SmartFolderWatcher({
+ getSmartFolders: () =>
+ watched.map((p, i) => ({ id: `f${i}`, name: path.basename(p), path: p })),
+ analysisHistoryService: {},
+ settingsService: { load: jest.fn().mockResolvedValue({}) },
+ analyzeDocumentFile: jest.fn(),
+ analyzeImageFile: jest.fn()
+ });
+ watcher.isRunning = true;
+ watcher.watcher = { add: jest.fn(), unwatch: jest.fn() };
+ watcher.watchedPaths = new Set(watched);
+ watcher.restart = jest.fn().mockResolvedValue(true);
+ return watcher;
+}
+
+const folders = (...paths) => paths.map((p, i) => ({ id: `f${i}`, path: p }));
+
+describe('SmartFolderWatcher.updateWatchedFolders with nested Smart Folders', () => {
+ test('removing a nested folder keeps watching it through its parent and keeps its work', async () => {
+ const watcher = makeWatcher([outer, inner]);
+ const queued = path.join(inner, 'invoice.pdf');
+ const timeout = setTimeout(() => {}, 60_000);
+ watcher.analysisQueue = [{ filePath: queued }];
+ watcher.pendingAnalysis.set(queued, { filePath: queued, timeout });
+
+ try {
+ await watcher.updateWatchedFolders(folders(outer));
+
+ expect(watcher.watcher.unwatch).not.toHaveBeenCalled();
+ expect(watcher.restart).not.toHaveBeenCalled();
+ expect([...watcher.watchedPaths]).toEqual([outer]);
+ expect(watcher.analysisQueue.map((i) => i.filePath)).toEqual([queued]);
+ expect(watcher.pendingAnalysis.has(queued)).toBe(true);
+ } finally {
+ clearTimeout(timeout);
+ }
+ });
+
+ test('removing the outer folder restarts instead of unwatching over the nested one', async () => {
+ const watcher = makeWatcher([outer, inner]);
+ const keep = path.join(inner, 'invoice.pdf');
+ const drop = path.join(outer, 'notes.pdf');
+ watcher.analysisQueue = [{ filePath: keep }, { filePath: drop }];
+
+ await watcher.updateWatchedFolders(folders(inner));
+
+ expect(watcher.watcher.unwatch).not.toHaveBeenCalled();
+ expect(watcher.restart).toHaveBeenCalledTimes(1);
+ expect([...watcher.watchedPaths]).toEqual([inner]);
+ // stop() persists what is left and start() restores it, so the purge
+ // must spare the nested folder's work.
+ expect(watcher.analysisQueue.map((i) => i.filePath)).toEqual([keep]);
+ });
+
+ test('a folder with no nesting is still unwatched in place', async () => {
+ const watcher = makeWatcher([outer, other]);
+ watcher.analysisQueue = [{ filePath: path.join(other, 'a.pdf') }];
+
+ await watcher.updateWatchedFolders(folders(outer));
+
+ expect(watcher.watcher.unwatch).toHaveBeenCalledWith(other);
+ expect(watcher.restart).not.toHaveBeenCalled();
+ expect(watcher.analysisQueue).toEqual([]);
+ });
+
+ test('adding a parent of a folder unwatched earlier restarts, since add() cannot lift that ignore', async () => {
+ const watcher = makeWatcher([inner, other]);
+
+ await watcher.updateWatchedFolders(folders(other));
+ expect(watcher.watcher.unwatch).toHaveBeenCalledWith(inner);
+ expect(watcher.restart).not.toHaveBeenCalled();
+
+ await watcher.updateWatchedFolders(folders(other, outer));
+ expect(watcher.watcher.add).toHaveBeenCalledWith(outer);
+ expect(watcher.restart).toHaveBeenCalledTimes(1);
+ });
+
+ test('re-adding the exact folder unwatched earlier does not restart', async () => {
+ const watcher = makeWatcher([inner, other]);
+
+ await watcher.updateWatchedFolders(folders(other));
+ await watcher.updateWatchedFolders(folders(other, inner));
+
+ expect(watcher.watcher.add).toHaveBeenCalledWith(inner);
+ expect(watcher.restart).not.toHaveBeenCalled();
+ });
+});
diff --git a/test/SmartFolderWatcher.scanDepth.test.js b/test/SmartFolderWatcher.scanDepth.test.js
new file mode 100644
index 00000000..03d8ccb0
--- /dev/null
+++ b/test/SmartFolderWatcher.scanDepth.test.js
@@ -0,0 +1,91 @@
+/**
+ * @jest-environment node
+ *
+ * The directory scan behind the startup delta scan, folder-add scans and
+ * "Reanalyze all" must reach the same directories as the live watcher.
+ * chokidar reads a directory whose depth is <= `depth` (the root is 0); the
+ * scan stopped one level short, so a file in the deepest directory chokidar
+ * watches was analyzed when dropped in live but never found by a scan.
+ */
+
+jest.mock('fs', () => jest.requireActual('fs'));
+jest.mock('fs/promises', () => jest.requireActual('fs/promises'));
+jest.mock('os', () => jest.requireActual('os'));
+jest.mock('chokidar', () => ({
+ watch: jest.fn(() => ({
+ on: jest.fn().mockReturnThis(),
+ once: jest.fn(),
+ close: jest.fn().mockResolvedValue()
+ }))
+}));
+jest.mock('../src/shared/logger', () => {
+ const logger = {
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn(),
+ setContext: jest.fn()
+ };
+ return { logger, createLogger: () => logger };
+});
+
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const SmartFolderWatcher = require('../src/main/services/SmartFolderWatcher');
+
+let root;
+
+beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'sfw-depth-'));
+});
+
+afterEach(() => {
+ fs.rmSync(root, { recursive: true, force: true });
+});
+
+function makeWatcher() {
+ return new SmartFolderWatcher({
+ getSmartFolders: () => [{ id: 'f1', name: 'Smart', path: root }],
+ analysisHistoryService: {},
+ settingsService: { load: jest.fn().mockResolvedValue({}) },
+ analyzeDocumentFile: jest.fn(),
+ analyzeImageFile: jest.fn()
+ });
+}
+
+/** Write report.pdf at root and in each of `levels` nested directories. */
+function buildTree(levels) {
+ const files = [path.join(root, 'report.pdf')];
+ fs.writeFileSync(files[0], 'synthetic');
+ let dir = root;
+ for (let i = 1; i <= levels; i++) {
+ dir = path.join(dir, `d${i}`);
+ fs.mkdirSync(dir);
+ const file = path.join(dir, 'report.pdf');
+ fs.writeFileSync(file, 'synthetic');
+ files.push(file);
+ }
+ return files;
+}
+
+describe('SmartFolderWatcher._scanDirectory depth', () => {
+ test('reads directories down to the watcher depth, like chokidar', async () => {
+ const files = buildTree(4);
+ const watcher = makeWatcher();
+ watcher.watcherDepth = 3;
+
+ const found = await watcher._scanDirectory(root);
+
+ // Depths 0..3 are read; the depth-4 directory is past the limit.
+ expect(found.sort()).toEqual(files.slice(0, 4).sort());
+ });
+
+ test('depth 0 still reads the folder itself', async () => {
+ const files = buildTree(1);
+ const watcher = makeWatcher();
+ watcher.watcherDepth = 0;
+
+ await expect(watcher._scanDirectory(root)).resolves.toEqual([files[0]]);
+ });
+});
diff --git a/test/SmartFolderWatcher.sweepTransientErrors.test.js b/test/SmartFolderWatcher.sweepTransientErrors.test.js
new file mode 100644
index 00000000..caca04d6
--- /dev/null
+++ b/test/SmartFolderWatcher.sweepTransientErrors.test.js
@@ -0,0 +1,170 @@
+/**
+ * @jest-environment node
+ *
+ * The startup reconcile and the orphan reaper delete a file's history,
+ * vectors and chunks once they decide the file is gone. They used to take any
+ * failure to reach the file as "gone", so a share that blipped or a folder
+ * that denied access wiped the analysis of files that still exist. Only a
+ * definite "not found", under a Smart Folder that can itself be reached,
+ * counts now.
+ */
+
+jest.mock('fs', () => jest.requireActual('fs'));
+jest.mock('fs/promises', () => jest.requireActual('fs/promises'));
+jest.mock('os', () => jest.requireActual('os'));
+jest.mock('chokidar', () => ({
+ watch: jest.fn(() => ({
+ on: jest.fn().mockReturnThis(),
+ once: jest.fn(),
+ close: jest.fn().mockResolvedValue()
+ }))
+}));
+jest.mock('../src/shared/logger', () => {
+ const logger = {
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn(),
+ setContext: jest.fn()
+ };
+ return { logger, createLogger: () => logger };
+});
+// The reconcile waits 5 s for startup to settle before sweeping.
+jest.mock('../src/shared/promiseUtils', () => ({
+ ...jest.requireActual('../src/shared/promiseUtils'),
+ delay: jest.fn().mockResolvedValue(undefined)
+}));
+
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const SmartFolderWatcher = require('../src/main/services/SmartFolderWatcher');
+
+let base;
+let root;
+
+beforeEach(() => {
+ base = fs.mkdtempSync(path.join(os.tmpdir(), 'sfw-sweep-'));
+ root = path.join(base, 'Share');
+ fs.mkdirSync(root);
+});
+
+afterEach(() => {
+ jest.restoreAllMocks();
+ fs.rmSync(base, { recursive: true, force: true });
+});
+
+function makeWatcher(filePaths) {
+ const entries = {};
+ filePaths.forEach((p, i) => {
+ entries[`e${i}`] = { originalPath: p };
+ });
+ const watcher = new SmartFolderWatcher({
+ getSmartFolders: () => [{ id: 'f1', name: 'Share', path: root }],
+ analysisHistoryService: { analysisHistory: { entries } },
+ settingsService: { load: jest.fn().mockResolvedValue({}) },
+ analyzeDocumentFile: jest.fn(),
+ analyzeImageFile: jest.fn()
+ });
+ watcher.isRunning = true;
+ watcher.watchedPaths = new Set([root]);
+ watcher.vectorDbService = {};
+ watcher._finalizeDeletion = jest.fn().mockResolvedValue(undefined);
+ return watcher;
+}
+
+/** Make fs.promises.stat fail with `code` for the given paths only. */
+function failStatFor(paths, code) {
+ const realStat = fs.promises.stat.bind(fs.promises);
+ jest.spyOn(fs.promises, 'stat').mockImplementation(async (p, ...rest) => {
+ if (paths.includes(p)) throw Object.assign(new Error(code), { code });
+ return realStat(p, ...rest);
+ });
+}
+
+const errnoError = (code) => Object.assign(new Error(code), { code });
+
+describe('startup reconcile', () => {
+ test('removes only files that are definitely not found', async () => {
+ const deleted = path.join(root, 'deleted.pdf');
+ const ioError = path.join(root, 'io-error.pdf');
+ const denied = path.join(root, 'denied.pdf');
+ fs.writeFileSync(ioError, 'synthetic');
+ fs.writeFileSync(denied, 'synthetic');
+ const watcher = makeWatcher([deleted, ioError, denied]);
+ // Fail every way of probing the file, so the test does not depend on
+ // which call the sweep uses.
+ for (const method of ['stat', 'access']) {
+ const real = fs.promises[method].bind(fs.promises);
+ jest.spyOn(fs.promises, method).mockImplementation(async (p, ...rest) => {
+ if (p === ioError) throw errnoError('EIO');
+ if (p === denied) throw errnoError('EACCES');
+ return real(p, ...rest);
+ });
+ }
+
+ await watcher._reconcileOrphanedEntries();
+
+ expect(watcher._finalizeDeletion).toHaveBeenCalledTimes(1);
+ expect(watcher._finalizeDeletion).toHaveBeenCalledWith(deleted);
+ });
+
+ test('a Smart Folder that cannot be reached removes nothing, even when its files read as not found', async () => {
+ const a = path.join(root, 'a.pdf');
+ const b = path.join(root, 'b.pdf');
+ const watcher = makeWatcher([a, b]);
+ // A dropped share: the files and the folder all fail to stat.
+ failStatFor([root], 'ETIMEDOUT');
+
+ await watcher._reconcileOrphanedEntries();
+
+ expect(watcher._finalizeDeletion).not.toHaveBeenCalled();
+ });
+});
+
+describe('orphan reaper', () => {
+ test('keeps an orphan whose file cannot be read, and skips one whose Smart Folder is unreachable', async () => {
+ const reachable = path.join(root, 'locked.pdf');
+ fs.writeFileSync(reachable, 'synthetic');
+ const watcher = makeWatcher([]);
+ watcher.vectorDbService = {
+ getOrphanedFileDocs: jest.fn().mockResolvedValue([{ id: 'file:1', path: reachable }])
+ };
+ failStatFor([reachable], 'EACCES');
+
+ await expect(watcher._reapStaleOrphans()).resolves.toEqual({
+ reaped: 0,
+ kept: 1,
+ skipped: 0
+ });
+
+ jest.restoreAllMocks();
+ const missing = path.join(root, 'missing.pdf');
+ watcher.vectorDbService.getOrphanedFileDocs.mockResolvedValue([
+ { id: 'file:2', path: missing }
+ ]);
+ failStatFor([root], 'EHOSTDOWN');
+
+ await expect(watcher._reapStaleOrphans()).resolves.toEqual({
+ reaped: 0,
+ kept: 0,
+ skipped: 1
+ });
+ expect(watcher._finalizeDeletion).not.toHaveBeenCalled();
+ });
+
+ test('reaps an orphan whose file is gone from a reachable Smart Folder', async () => {
+ const missing = path.join(root, 'missing.pdf');
+ const watcher = makeWatcher([]);
+ watcher.vectorDbService = {
+ getOrphanedFileDocs: jest.fn().mockResolvedValue([{ id: 'file:1', path: missing }])
+ };
+
+ await expect(watcher._reapStaleOrphans()).resolves.toEqual({
+ reaped: 1,
+ kept: 0,
+ skipped: 0
+ });
+ expect(watcher._finalizeDeletion).toHaveBeenCalledWith(missing);
+ });
+});
diff --git a/test/Toast.groupMergeMessage.test.js b/test/Toast.groupMergeMessage.test.js
new file mode 100644
index 00000000..009a4bc2
--- /dev/null
+++ b/test/Toast.groupMergeMessage.test.js
@@ -0,0 +1,76 @@
+/**
+ * @jest-environment jsdom
+ */
+
+// A grouped toast that escalates to a higher severity must show the text that
+// caused it. It used to keep the first message, so a warning or error arriving
+// in the same group within the merge window showed the earlier, milder text.
+
+import { act, renderHook } from '@testing-library/react';
+import { useToast } from '../src/renderer/components/Toast';
+
+describe('useToast group merge message', () => {
+ it('shows the incoming error text when an info toast escalates', () => {
+ const { result } = renderHook(() => useToast());
+ act(() => {
+ result.current.addToast('Analysis complete!', 'success', 3000, 'analysis-complete');
+ result.current.addToast('Analysis failed for all 3 files.', 'error', 0, 'analysis-complete', {
+ details: 'code: E_ANALYSIS'
+ });
+ });
+ expect(result.current.toasts).toHaveLength(1);
+ const [toast] = result.current.toasts;
+ expect(toast.severity).toBe('error');
+ expect(toast.message).toBe('Analysis failed for all 3 files.');
+ expect(toast.details).toBe('code: E_ANALYSIS');
+ expect(toast.mergeCount).toBe(2);
+ });
+
+ it('shows the newest text when both toasts share a severity', () => {
+ const { result } = renderHook(() => useToast());
+ act(() => {
+ result.current.addToast('Removed from queue: A.pdf', 'info', 3000, 'file-actions');
+ result.current.addToast('Removed from queue: B.pdf', 'info', 3000, 'file-actions');
+ });
+ expect(result.current.toasts[0].message).toBe('Removed from queue: B.pdf');
+ });
+
+ it('keeps the higher-severity text when a milder toast merges in', () => {
+ const { result } = renderHook(() => useToast());
+ act(() => {
+ result.current.addToast(
+ 'Removed from queue: B.pdf (cleanup incomplete)',
+ 'warning',
+ 3000,
+ 'file-actions',
+ { actionable: true, type: 'open-file', data: { path: 'B.pdf' }, details: 'EBUSY' }
+ );
+ result.current.addToast('Removed from queue: C.pdf', 'info', 3000, 'file-actions');
+ });
+ const [toast] = result.current.toasts;
+ expect(toast.severity).toBe('warning');
+ expect(toast.message).toBe('Removed from queue: B.pdf (cleanup incomplete)');
+ expect(toast.details).toBe('EBUSY');
+ expect(toast.actionable).toBe(true);
+ expect(toast.activationData).toEqual({ path: 'B.pdf' });
+ });
+
+ it('takes the click action of the message it shows', () => {
+ const { result } = renderHook(() => useToast());
+ act(() => {
+ result.current.addToast('First', 'info', 3000, 'g', {
+ actionable: true,
+ type: 'open-file',
+ data: { path: 'a' }
+ });
+ result.current.addToast('Second', 'warning', 3000, 'g', {
+ actionable: true,
+ type: 'open-file',
+ data: { path: 'b' }
+ });
+ });
+ const [toast] = result.current.toasts;
+ expect(toast.message).toBe('Second');
+ expect(toast.activationData).toEqual({ path: 'b' });
+ });
+});
diff --git a/test/TrashService.test.js b/test/TrashService.test.js
index 94bdf878..ff7ddf4a 100644
--- a/test/TrashService.test.js
+++ b/test/TrashService.test.js
@@ -197,3 +197,71 @@ describe('TrashService', () => {
expect(mockTrashItem).toHaveBeenCalledWith(file);
});
});
+
+// Windows keeps no Recycle Bin on a network share, so a file there must not
+// reach shell.trashItem: it is reported as left in place instead.
+describe('TrashService on a Windows network drive', () => {
+ const originalPlatform = process.platform;
+ let testDir;
+
+ beforeEach(async () => {
+ testDir = path.join(os.tmpdir(), `trash-net-test-${Date.now()}`);
+ await fs.mkdir(testDir, { recursive: true });
+ jest.resetModules();
+ mockTrashItem.mockReset();
+ Object.defineProperty(process, 'platform', { value: 'win32' });
+ });
+
+ afterEach(async () => {
+ Object.defineProperty(process, 'platform', { value: originalPlatform });
+ jest.restoreAllMocks();
+ await fs.rm(testDir, { recursive: true, force: true }).catch(() => {});
+ });
+
+ test('a file on a drive mapped to a share is left in place with a clear reason', async () => {
+ const file = path.join(testDir, 'shared-report.pdf');
+ await fs.writeFile(file, 'x');
+ // A mapped drive resolves to its \\server\share path.
+ jest
+ .spyOn(require('fs').promises, 'realpath')
+ .mockResolvedValue('\\\\fileserver\\team\\shared-report.pdf');
+ const { TrashService } = require('../src/main/services/TrashService');
+
+ const one = await new TrashService().trashOne(file);
+ const batch = await new TrashService().trashBatch([file]);
+
+ expect(one).toMatchObject({ success: false, code: 'NETWORK_NO_RECYCLE_BIN' });
+ expect(one.error).toMatch(/network drive/i);
+ expect(batch.trashed).toEqual([]);
+ expect(batch.failed[0].code).toBe('NETWORK_NO_RECYCLE_BIN');
+ expect(mockTrashItem).not.toHaveBeenCalled();
+ });
+
+ test('isWindowsNetworkPath tells shares from local and device paths', async () => {
+ const realpath = jest.spyOn(require('fs').promises, 'realpath');
+ const { isWindowsNetworkPath } = require('../src/main/services/TrashService');
+ const judge = async (p) => {
+ realpath.mockResolvedValueOnce(p);
+ return isWindowsNetworkPath(p);
+ };
+
+ expect(await judge('\\\\server\\share\\a.txt')).toBe(true);
+ expect(await judge('//server/share/a.txt')).toBe(true);
+ expect(await judge('\\\\?\\UNC\\server\\share\\a.txt')).toBe(true);
+ expect(await judge('C:\\Users\\alex\\a.txt')).toBe(false);
+ expect(await judge('\\\\?\\C:\\Users\\alex\\a.txt')).toBe(false);
+ expect(await judge('\\\\.\\PhysicalDrive0')).toBe(false);
+ });
+
+ test('a local file still goes to the Recycle Bin', async () => {
+ const file = path.join(testDir, 'local.txt');
+ await fs.writeFile(file, 'x');
+ mockTrashItem.mockResolvedValue(undefined);
+ const { TrashService } = require('../src/main/services/TrashService');
+
+ const result = await new TrashService().trashOne(file);
+
+ expect(result.success).toBe(true);
+ expect(mockTrashItem).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/test/UnifiedSearchModal.groupedKeyboardNav.test.js b/test/UnifiedSearchModal.groupedKeyboardNav.test.js
new file mode 100644
index 00000000..dd3b6cd6
--- /dev/null
+++ b/test/UnifiedSearchModal.groupedKeyboardNav.test.js
@@ -0,0 +1,126 @@
+/**
+ * @jest-environment jsdom
+ */
+
+// In "By Type" view the rows are ordered by category, so arrow keys must step
+// through that on-screen order. They used to step through the flat result
+// order: the highlight jumped between groups and scrollIntoView scrolled a
+// different row from the highlighted one.
+
+import React from 'react';
+import { screen, fireEvent, waitFor, act } from '@testing-library/react';
+import { mockElectronAPI, renderWithRedux } from './components/unifiedSearchModal.harness';
+import UnifiedSearchModal from '../src/renderer/components/search/UnifiedSearchModal';
+import { embeddingsIpc } from '../src/renderer/services/ipc/embeddingsIpc';
+import { registerOverlay, unregisterOverlay } from '../src/renderer/utils/overlayStack';
+
+const RESULTS = [
+ { id: 'a', metadata: { name: 'a.pdf', path: '/path/a.pdf' }, score: 0.9 },
+ { id: 'b', metadata: { name: 'b.jpg', path: '/path/b.jpg' }, score: 0.8 },
+ { id: 'c', metadata: { name: 'c.pdf', path: '/path/c.pdf' }, score: 0.7 },
+ { id: 'd', metadata: { name: 'd.pdf', path: '/path/d.pdf' }, score: 0.6 }
+];
+
+const rowName = (row) => row.textContent.match(/[a-d]\.(pdf|jpg)/)?.[0];
+const focusedRowName = (container) => {
+ const focused = Array.from(container.querySelectorAll('[data-result-item]')).find((row) =>
+ row.className.includes('border-stratosort-blue/35')
+ );
+ return focused ? rowName(focused) : null;
+};
+
+describe('UnifiedSearchModal grouped view keyboard navigation', () => {
+ let scrollSpy;
+ let originalScrollIntoView;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ jest.useFakeTimers();
+ embeddingsIpc.invalidateStatsCache();
+ window.ResizeObserver = jest.fn().mockImplementation(() => ({
+ observe: jest.fn(),
+ unobserve: jest.fn(),
+ disconnect: jest.fn()
+ }));
+ mockElectronAPI.embeddings.search.mockResolvedValue({
+ success: true,
+ results: RESULTS,
+ mode: 'hybrid'
+ });
+ mockElectronAPI.embeddings.getStats.mockResolvedValue({
+ success: true,
+ files: 10,
+ folders: 5
+ });
+ originalScrollIntoView = Element.prototype.scrollIntoView;
+ scrollSpy = jest.fn();
+ Element.prototype.scrollIntoView = scrollSpy;
+ // The real Modal registers the overlay; the mocked one does not, and the
+ // key handler only runs for the top overlay.
+ registerOverlay('knowledge-os-modal');
+ });
+
+ afterEach(() => {
+ unregisterOverlay('knowledge-os-modal');
+ Element.prototype.scrollIntoView = originalScrollIntoView;
+ delete window.ResizeObserver;
+ jest.useRealTimers();
+ });
+
+ const searchAndGroup = async () => {
+ const view = renderWithRedux();
+ fireEvent.change(screen.getByLabelText(/search query/i), { target: { value: 'files' } });
+ await act(async () => {
+ jest.advanceTimersByTime(400);
+ });
+ await waitFor(() => {
+ expect(view.container.querySelectorAll('[data-result-item]')).toHaveLength(4);
+ });
+ fireEvent.click(screen.getByRole('button', { name: /group results by type/i }));
+ // Documents (3) sort before Images (1).
+ await waitFor(() => {
+ const order = Array.from(view.container.querySelectorAll('[data-result-item]')).map(rowName);
+ expect(order).toEqual(['a.pdf', 'c.pdf', 'd.pdf', 'b.jpg']);
+ });
+ return view;
+ };
+
+ const press = async (key) => {
+ await act(async () => {
+ fireEvent.keyDown(document.body, { key });
+ });
+ };
+
+ test('ArrowDown follows the on-screen order and scrolls the highlighted row', async () => {
+ const { container } = await searchAndGroup();
+
+ await press('ArrowDown');
+ await waitFor(() => expect(focusedRowName(container)).toBe('a.pdf'));
+
+ await press('ArrowDown');
+ await waitFor(() => expect(focusedRowName(container)).toBe('c.pdf'));
+ const lastScrolled = scrollSpy.mock.instances[scrollSpy.mock.instances.length - 1];
+ expect(rowName(lastScrolled)).toBe('c.pdf');
+
+ await press('ArrowDown');
+ await waitFor(() => expect(focusedRowName(container)).toBe('d.pdf'));
+ await press('ArrowDown');
+ await waitFor(() => expect(focusedRowName(container)).toBe('b.jpg'));
+
+ await press('ArrowUp');
+ await waitFor(() => expect(focusedRowName(container)).toBe('d.pdf'));
+ });
+
+ test('Enter opens the highlighted row, not the flat result at that index', async () => {
+ mockElectronAPI.files.open.mockResolvedValue({ success: true });
+ const { container } = await searchAndGroup();
+
+ await press('ArrowDown');
+ await press('ArrowDown');
+ await waitFor(() => expect(focusedRowName(container)).toBe('c.pdf'));
+ await press('Enter');
+
+ expect(mockElectronAPI.files.open).toHaveBeenCalledWith('/path/c.pdf');
+ expect(mockElectronAPI.files.open).not.toHaveBeenCalledWith('/path/b.jpg');
+ });
+});
diff --git a/test/analysis-fallbackUtils.test.js b/test/analysis-fallbackUtils.test.js
index 1d6a8eae..f342b747 100644
--- a/test/analysis-fallbackUtils.test.js
+++ b/test/analysis-fallbackUtils.test.js
@@ -374,6 +374,13 @@ describe('Analysis Fallback Utils', () => {
expect(result).not.toContain('/');
expect(result).not.toContain('\\');
});
+
+ test('keeps a compound archive extension when given only its last part', () => {
+ // path.extname('server_logs.tar.gz') is '.gz'
+ expect(safeSuggestedName('server_logs.tar.gz', '.gz')).toBe('server_logs.tar.gz');
+ expect(safeSuggestedName('Backup.TAR.XZ', '.xz')).toBe('Backup.TAR.XZ');
+ expect(safeSuggestedName('notes.gz', '.gz')).toBe('notes.gz');
+ });
});
});
diff --git a/test/analysisHistory-indexManager.prototypeKeys.test.js b/test/analysisHistory-indexManager.prototypeKeys.test.js
new file mode 100644
index 00000000..2b26d137
--- /dev/null
+++ b/test/analysisHistory-indexManager.prototypeKeys.test.js
@@ -0,0 +1,110 @@
+/**
+ * Tag and category keys come from model keywords and user tags. The index maps
+ * are plain objects, so a key such as "constructor" used to resolve to an
+ * inherited Object.prototype member and `.push` / `.filter` / `.map` threw,
+ * leaving the entry half-indexed.
+ */
+const indexManager = require('../src/main/services/analysisHistory/indexManager');
+const queries = require('../src/main/services/analysisHistory/queries');
+
+const PROTOTYPE_KEYS = ['constructor', 'toString', 'valueOf', 'hasOwnProperty', '__proto__'];
+
+function makeEntry(id, tags, category) {
+ return {
+ id,
+ fileHash: `hash-${id}`,
+ originalPath: `/docs/${id}.js`,
+ timestamp: '2026-11-14T10:00:00.000Z',
+ fileSize: 2048,
+ analysis: { tags, category }
+ };
+}
+
+function freshIndex() {
+ // Same shape as an index loaded with JSON.parse: plain objects.
+ return JSON.parse(JSON.stringify(indexManager.createEmptyIndex('2.0')));
+}
+
+const hasOwn = (obj, key) => Object.prototype.hasOwnProperty.call(obj, key);
+
+describe('indexManager with Object.prototype key names', () => {
+ test('updateIndexes indexes prototype-named tags and categories', () => {
+ const index = freshIndex();
+ const entry = makeEntry('e1', ['class', ...PROTOTYPE_KEYS], 'constructor');
+
+ expect(() => indexManager.updateIndexes(index, entry)).not.toThrow();
+
+ for (const tag of PROTOTYPE_KEYS) {
+ expect(hasOwn(index.tagIndex, tag)).toBe(true);
+ expect(index.tagIndex[tag]).toEqual(['e1']);
+ }
+ expect(index.categoryIndex.constructor).toEqual(['e1']);
+ // The later indexes were still written (the throw used to stop before them).
+ expect(index.dateIndex['2026-11']).toEqual(['e1']);
+ expect(index.sizeIndex.small).toEqual(['e1']);
+ // A "__proto__" tag must not replace the map's prototype.
+ expect(Object.getPrototypeOf(index.tagIndex)).toBe(Object.prototype);
+ });
+
+ test('a second entry appends to the same prototype-named bucket', () => {
+ const index = freshIndex();
+ indexManager.updateIndexes(index, makeEntry('e1', ['constructor'], 'toString'));
+ indexManager.updateIndexes(index, makeEntry('e2', ['constructor'], 'toString'));
+
+ expect(index.tagIndex.constructor).toEqual(['e1', 'e2']);
+ expect(index.categoryIndex.toString).toEqual(['e1', 'e2']);
+ });
+
+ test('removeFromIndexes handles prototype-named keys, indexed or not', () => {
+ const index = freshIndex();
+ const indexed = makeEntry('e1', ['constructor', '__proto__'], 'valueOf');
+ indexManager.updateIndexes(index, indexed);
+
+ expect(() => indexManager.removeFromIndexes(index, indexed)).not.toThrow();
+ expect(hasOwn(index.tagIndex, 'constructor')).toBe(false);
+ expect(hasOwn(index.tagIndex, '__proto__')).toBe(false);
+ expect(hasOwn(index.categoryIndex, 'valueOf')).toBe(false);
+
+ // An entry whose tags were never indexed (e.g. a half-indexed row).
+ const neverIndexed = makeEntry('e2', ['toString'], 'hasOwnProperty');
+ expect(() => indexManager.removeFromIndexes(index, neverIndexed)).not.toThrow();
+ expect(Object.keys(index.tagIndex)).toEqual([]);
+ expect(Object.keys(index.categoryIndex)).toEqual([]);
+ });
+
+ test('removeFromIndexes keeps the other ids in a prototype-named bucket', () => {
+ const index = freshIndex();
+ const first = makeEntry('e1', ['constructor'], 'code');
+ indexManager.updateIndexes(index, first);
+ indexManager.updateIndexes(index, makeEntry('e2', ['constructor'], 'code'));
+
+ indexManager.removeFromIndexes(index, first);
+ expect(index.tagIndex.constructor).toEqual(['e2']);
+ });
+});
+
+describe('queries with Object.prototype key names', () => {
+ function makeCache() {
+ return { tagResults: new Map(), categoryResults: new Map() };
+ }
+
+ test('getAnalysisByTag returns the indexed entries for a prototype-named tag', () => {
+ const index = freshIndex();
+ const entry = makeEntry('e1', ['constructor'], 'code');
+ indexManager.updateIndexes(index, entry);
+ const history = { entries: { e1: entry } };
+
+ const result = queries.getAnalysisByTag(history, index, makeCache(), 1000, 'constructor');
+ expect(result.results.map((e) => e.id)).toEqual(['e1']);
+ });
+
+ test('tag and category queries return nothing for an unindexed prototype key', () => {
+ const index = freshIndex();
+ const history = { entries: {} };
+
+ for (const key of PROTOTYPE_KEYS) {
+ expect(queries.getAnalysisByTag(history, index, makeCache(), 1000, key).total).toBe(0);
+ expect(queries.getAnalysisByCategory(history, index, makeCache(), 1000, key).total).toBe(0);
+ }
+ });
+});
diff --git a/test/analysisHistoryFetch.oversize.test.js b/test/analysisHistoryFetch.oversize.test.js
new file mode 100644
index 00000000..1867c0ab
--- /dev/null
+++ b/test/analysisHistoryFetch.oversize.test.js
@@ -0,0 +1,121 @@
+/**
+ * @jest-environment jsdom
+ */
+
+import { fetchAnalysisHistoryPages } from '../src/renderer/utils/analysisHistoryFetch';
+import { createIpcValidator } from '../src/preload/ipcValidator';
+
+jest.mock('../src/shared/logger', () => ({
+ createLogger: () => ({
+ debug: jest.fn(),
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn()
+ })
+}));
+
+const TOO_LARGE = { success: false, error: 'too large', reason: 'payload-too-large' };
+
+describe('fetchAnalysisHistoryPages - page over the IPC size cap', () => {
+ afterEach(() => {
+ delete window.electronAPI;
+ });
+
+ test('retries the same offset with a smaller page instead of stopping', async () => {
+ const entries = Array.from({ length: 6 }, (_, i) => ({ id: i }));
+ // Any request for more than 2 entries is over the cap.
+ const get = jest.fn(async ({ limit, offset }) =>
+ limit > 2 ? TOO_LARGE : entries.slice(offset, offset + limit)
+ );
+ window.electronAPI = { analysisHistory: { get } };
+
+ const result = await fetchAnalysisHistoryPages({ pageSize: 8, maxEntries: 100 });
+
+ expect(result).toEqual(entries);
+ expect(get).toHaveBeenNthCalledWith(1, { limit: 8, offset: 0 });
+ expect(get).toHaveBeenNthCalledWith(2, { limit: 4, offset: 0 });
+ expect(get).toHaveBeenNthCalledWith(3, { limit: 2, offset: 0 });
+ });
+
+ test('skips a single entry that is over the cap on its own', async () => {
+ const entries = [{ id: 0 }, { id: 1 }, { id: 2 }];
+ const get = jest.fn(async ({ limit, offset }) =>
+ offset === 1 ? TOO_LARGE : entries.slice(offset, offset + limit)
+ );
+ window.electronAPI = { analysisHistory: { get } };
+
+ const result = await fetchAnalysisHistoryPages({ pageSize: 1, maxEntries: 100 });
+
+ expect(result).toEqual([{ id: 0 }, { id: 2 }]);
+ });
+
+ test('grows back to the full page size after skipping one oversized entry', async () => {
+ const entries = Array.from({ length: 20 }, (_, i) => ({ id: i }));
+ // Only entry 1 is over the cap, so any page that includes it is too.
+ const get = jest.fn(async ({ limit, offset }) =>
+ offset <= 1 && offset + limit > 1 ? TOO_LARGE : entries.slice(offset, offset + limit)
+ );
+ window.electronAPI = { analysisHistory: { get } };
+
+ const result = await fetchAnalysisHistoryPages({ pageSize: 4, maxEntries: 100 });
+
+ expect(result).toEqual(entries.filter((e) => e.id !== 1));
+ const calls = get.mock.calls.map(([args]) => args);
+ const afterSkip = calls.filter((c) => c.offset >= 2);
+ // Reads past the bad entry start small and double back to the original
+ // page size, not one entry per call.
+ expect(afterSkip.length).toBeGreaterThan(0);
+ expect(afterSkip[afterSkip.length - 1].limit).toBe(4);
+ expect(calls.length).toBeLessThan(12);
+ });
+
+ test('a run of oversized entries costs one call each, not a full-size retry each', async () => {
+ const entries = Array.from({ length: 30 }, (_, i) => ({ id: i }));
+ // Entries 2-21 are each over the cap on their own.
+ const isLarge = (e) => e.id >= 2 && e.id <= 21;
+ const get = jest.fn(async ({ limit, offset }) => {
+ const page = entries.slice(offset, offset + limit);
+ return page.some(isLarge) ? TOO_LARGE : page;
+ });
+ window.electronAPI = { analysisHistory: { get } };
+
+ const result = await fetchAnalysisHistoryPages({ pageSize: 64, maxEntries: 100 });
+
+ expect(result).toEqual(entries.filter((e) => !isLarge(e)));
+ // 20 skips at one call each plus the shrink and the regrowth; resetting
+ // to 64 after each skip would cost about 7 calls per skipped entry.
+ expect(get.mock.calls.length).toBeLessThan(40);
+ });
+
+ test('grows the page back after a run of large entries ends', async () => {
+ const entries = Array.from({ length: 40 }, (_, i) => ({ id: i }));
+ // Entries 0-3 are large: a page holding more than one of them is too big.
+ const get = jest.fn(async ({ limit, offset }) => {
+ const largeInPage = entries.slice(offset, offset + limit).filter((e) => e.id < 4).length;
+ return largeInPage > 1 ? TOO_LARGE : entries.slice(offset, offset + limit);
+ });
+ window.electronAPI = { analysisHistory: { get } };
+
+ const result = await fetchAnalysisHistoryPages({ pageSize: 8, maxEntries: 100 });
+
+ expect(result).toEqual(entries);
+ const limits = get.mock.calls.map(([args]) => args.limit);
+ expect(limits[limits.length - 1]).toBe(8);
+ });
+
+ test('recognizes the response the preload validator sends for an oversized page', async () => {
+ // Pins the reason string shared by the preload validator and this
+ // fetcher; the renderer cannot import the preload module at runtime.
+ const { validateResult } = createIpcValidator();
+ const hugeText = 'x'.repeat(600000);
+ const entries = [{ id: 0 }, { id: 1, analysis: { extractedText: hugeText } }, { id: 2 }];
+ const get = jest.fn(async ({ limit, offset }) =>
+ validateResult(entries.slice(offset, offset + limit), 'analysis-history:get')
+ );
+ window.electronAPI = { analysisHistory: { get } };
+
+ const result = await fetchAnalysisHistoryPages({ pageSize: 4, maxEntries: 100 });
+
+ expect(result).toEqual([{ id: 0 }, { id: 2 }]);
+ });
+});
diff --git a/test/analysisHistoryIpc.embeddingPolicyPath.test.js b/test/analysisHistoryIpc.embeddingPolicyPath.test.js
new file mode 100644
index 00000000..b1e36a18
--- /dev/null
+++ b/test/analysisHistoryIpc.embeddingPolicyPath.test.js
@@ -0,0 +1,70 @@
+/**
+ * SET_EMBEDDING_POLICY must hand the service the exact path it received and
+ * report a miss. The service matches entries by exact string, so a normalized
+ * path (double space collapsed, long path cut) never matches, and replying
+ * success for a miss made the renderer show a policy that was never stored.
+ */
+const { ipcMain } = require('./mocks/electron');
+
+jest.mock('../src/main/services/DegradedStateTracker', () => ({
+ getInstance: () => ({ raise: jest.fn(), clear: jest.fn() })
+}));
+
+describe('AnalysisHistory IPC SET_EMBEDDING_POLICY path handling', () => {
+ beforeEach(() => {
+ ipcMain._handlers.clear();
+ ipcMain.handle.mockClear();
+ jest.resetModules();
+ });
+
+ function register(service) {
+ const registerAnalysisHistoryIpc = require('../src/main/ipc/analysisHistory');
+ const { IPC_CHANNELS } = require('../src/shared/constants');
+ const logger = { error: jest.fn(), info: jest.fn(), warn: jest.fn(), debug: jest.fn() };
+ registerAnalysisHistoryIpc({
+ ipcMain,
+ IPC_CHANNELS,
+ logger,
+ getServiceIntegration: () => ({
+ analysisHistory: service,
+ container: { resolve: jest.fn() }
+ })
+ });
+ return ipcMain._handlers.get(IPC_CHANNELS.ANALYSIS_HISTORY.SET_EMBEDDING_POLICY);
+ }
+
+ test('passes a path with repeated spaces through unchanged', async () => {
+ const service = { setEmbeddingPolicyByPath: jest.fn(async () => ({ updated: 1 })) };
+ const handler = register(service);
+ const filePath = 'C:\\Docs\\Invoice 2024.pdf';
+
+ const result = await handler(null, { filePath, policy: 'skip' });
+
+ expect(service.setEmbeddingPolicyByPath).toHaveBeenCalledWith(filePath, 'skip');
+ expect(result).toEqual(expect.objectContaining({ success: true, updated: 1 }));
+ });
+
+ test('does not cut a path longer than 2000 characters', async () => {
+ const service = { setEmbeddingPolicyByPath: jest.fn(async () => ({ updated: 1 })) };
+ const handler = register(service);
+ const filePath = `/data/${'a'.repeat(2100)}/file.pdf`;
+
+ await handler(null, { filePath, policy: 'embed' });
+
+ expect(service.setEmbeddingPolicyByPath).toHaveBeenCalledWith(filePath, 'embed');
+ });
+
+ test('reports failure when no history entry matched', async () => {
+ const service = {
+ setEmbeddingPolicyByPath: jest.fn(async () => ({ updated: 0, notFound: 1 }))
+ };
+ const handler = register(service);
+
+ const result = await handler(null, { filePath: 'C:\\Docs\\missing.pdf', policy: 'skip' });
+
+ expect(result.success).toBe(false);
+ expect(result.notFound).toBe(true);
+ expect(result.updated).toBe(0);
+ expect(typeof result.error).toBe('string');
+ });
+});
diff --git a/test/atomicFileOperations.staleCleanup.test.js b/test/atomicFileOperations.staleCleanup.test.js
new file mode 100644
index 00000000..7fe78987
--- /dev/null
+++ b/test/atomicFileOperations.staleCleanup.test.js
@@ -0,0 +1,117 @@
+/**
+ * @jest-environment node
+ */
+/**
+ * cleanupStaleTransactions must not delete the backups and journal of a
+ * transaction whose rollback failed: the backup may be the only copy of the
+ * file that was being replaced, and recoverFromJournals needs both at the
+ * next startup.
+ */
+
+jest.unmock('fs');
+jest.unmock('fs/promises');
+jest.unmock('os');
+
+const path = jest.requireActual('path');
+const fs = require('fs').promises;
+const os = require('os');
+
+describe('AtomicFileOperations stale-transaction cleanup', () => {
+ let AtomicFileOperations;
+ let testDir;
+ let ops;
+
+ beforeEach(async () => {
+ testDir = await fs.mkdtemp(path.join(os.tmpdir(), 'atomic-stale-'));
+ jest.resetModules();
+ ({ AtomicFileOperations } = require('../src/shared/atomicFileOperations'));
+ ops = new AtomicFileOperations();
+ ops.journalBaseDirectory = path.join(testDir, 'journal-base');
+ ops.backupBaseDirectory = path.join(testDir, 'backup-base');
+ });
+
+ afterEach(async () => {
+ ops.shutdown();
+ await fs.rm(testDir, { recursive: true, force: true });
+ });
+
+ const exists = (p) =>
+ fs
+ .access(p)
+ .then(() => true)
+ .catch(() => false);
+
+ /** Begin a transaction holding one real backup, aged past maxAge. */
+ async function staleTransactionWithBackup(status) {
+ const source = path.join(testDir, 'settings.json');
+ await fs.writeFile(source, '{"theme":"dark"}');
+ const id = await ops.beginTransaction();
+ const backup = await ops.createBackup(source, id);
+ const tx = ops.activeTransactions.get(id);
+ tx.backups.push({ source, backup });
+ tx.status = status;
+ tx.startTime = Date.now() - 2 * 3600000;
+ await ops.writeJournal(id);
+ const journalPath = path.join(ops.journalDirectory, `${id}.journal`);
+ return { id, source, backup, journalPath };
+ }
+
+ test('keeps backups and journal of a rollback_failed transaction', async () => {
+ const { id, backup, journalPath } = await staleTransactionWithBackup('rollback_failed');
+
+ const count = await ops.cleanupStaleTransactions(3600000);
+
+ expect(count).toBe(1);
+ expect(ops.activeTransactions.has(id)).toBe(false);
+ expect(await exists(backup)).toBe(true);
+ expect(await exists(journalPath)).toBe(true);
+ });
+
+ test('a stale active transaction whose rollback fails keeps its rollback material', async () => {
+ const { id, backup, journalPath } = await staleTransactionWithBackup('active');
+ jest.spyOn(ops, 'rollbackTransaction').mockImplementation(async () => {
+ // Mirrors the real method: it flips status to rolled_back, then throws.
+ ops.activeTransactions.get(id).status = 'rolled_back';
+ throw new Error('restore failed');
+ });
+
+ await ops.cleanupStaleTransactions(3600000);
+
+ expect(ops.activeTransactions.has(id)).toBe(false);
+ expect(await exists(backup)).toBe(true);
+ const journal = JSON.parse(await fs.readFile(journalPath, 'utf8'));
+ // A non-terminal status makes recoverFromJournals restore from the backup.
+ expect(journal.status).toBe('rollback_failed');
+ });
+
+ test('a stale active transaction is rolled back and then cleaned up', async () => {
+ const { id, source, backup, journalPath } = await staleTransactionWithBackup('active');
+ await fs.unlink(source);
+
+ await ops.cleanupStaleTransactions(3600000);
+
+ expect(ops.activeTransactions.has(id)).toBe(false);
+ expect(await fs.readFile(source, 'utf8')).toBe('{"theme":"dark"}');
+ expect(await exists(backup)).toBe(false);
+ expect(await exists(journalPath)).toBe(false);
+ });
+
+ test('committed transactions still have their backups and journal removed', async () => {
+ const { id, backup, journalPath } = await staleTransactionWithBackup('committed');
+
+ await ops.cleanupStaleTransactions(3600000);
+
+ expect(ops.activeTransactions.has(id)).toBe(false);
+ expect(await exists(backup)).toBe(false);
+ expect(await exists(journalPath)).toBe(false);
+ });
+
+ test('leaves an in-flight rollback alone', async () => {
+ const { id, backup } = await staleTransactionWithBackup('rolling_back');
+
+ await ops.cleanupStaleTransactions(3600000);
+
+ expect(ops.activeTransactions.has(id)).toBe(true);
+ expect(await exists(backup)).toBe(true);
+ });
+});
diff --git a/test/autoUpdater.installOnExit.test.js b/test/autoUpdater.installOnExit.test.js
new file mode 100644
index 00000000..3540bdc9
--- /dev/null
+++ b/test/autoUpdater.installOnExit.test.js
@@ -0,0 +1,135 @@
+/**
+ * "Install now" on Windows must not start the NSIS installer before shutdown
+ * cleanup: in update mode the installer force-kills the running app about 2 s
+ * after launch, which cut off handleBeforeQuit (Orama final persist, hash-cache
+ * flush, lock release). quitAndInstall() now only quits; lifecycle starts the
+ * installer through runPendingInstallOnExit() at its exit site.
+ */
+
+const ORIGINAL_PLATFORM = process.platform;
+
+jest.mock('../src/shared/logger', () => {
+ const logger = {
+ info: jest.fn(),
+ debug: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn()
+ };
+ return { logger, createLogger: jest.fn(() => logger) };
+});
+
+const mockApp = { isPackaged: false, quit: jest.fn() };
+
+jest.mock('electron', () => ({
+ BrowserWindow: { getAllWindows: () => [] },
+ app: mockApp
+}));
+
+// Shape of electron-updater's BaseUpdater (NsisUpdater): install() and the
+// installerPath getter exist alongside quitAndInstall().
+const mockUpdater = {
+ on: jest.fn(),
+ removeListener: jest.fn(),
+ quitAndInstall: jest.fn(),
+ install: jest.fn(() => true),
+ installerPath: /** @type {string|null} */ ('C:\\updates\\installer.exe')
+};
+
+jest.mock('electron-updater', () => ({ autoUpdater: mockUpdater }));
+
+jest.mock('../src/main/ipc/ipcWrappers', () => ({ safeSend: jest.fn() }));
+
+const setPlatform = (value) =>
+ Object.defineProperty(process, 'platform', { value, configurable: true });
+
+const flushImmediate = () => new Promise((resolve) => setImmediate(resolve));
+
+describe('autoUpdater – install deferred to the exit site', () => {
+ beforeEach(() => {
+ jest.resetModules();
+ process.env.STRATOSORT_ENABLE_AUTO_UPDATES = 'true';
+ mockApp.quit.mockClear();
+ mockUpdater.quitAndInstall.mockClear();
+ mockUpdater.install.mockClear();
+ mockUpdater.install.mockImplementation(() => true);
+ mockUpdater.installerPath = 'C:\\updates\\installer.exe';
+ setPlatform('win32');
+ });
+
+ afterEach(() => {
+ setPlatform(ORIGINAL_PLATFORM);
+ delete process.env.STRATOSORT_ENABLE_AUTO_UPDATES;
+ });
+
+ test('on Windows, Install now quits without spawning the installer', async () => {
+ const { quitAndInstall } = require('../src/main/core/autoUpdater');
+
+ expect(quitAndInstall()).toEqual({ success: true });
+ await flushImmediate();
+
+ expect(mockApp.quit).toHaveBeenCalledTimes(1);
+ expect(mockUpdater.quitAndInstall).not.toHaveBeenCalled();
+ expect(mockUpdater.install).not.toHaveBeenCalled();
+ });
+
+ test('the exit site starts the visible, relaunching installer exactly once', async () => {
+ const { quitAndInstall, runPendingInstallOnExit } = require('../src/main/core/autoUpdater');
+
+ quitAndInstall();
+ await flushImmediate();
+
+ expect(runPendingInstallOnExit()).toBe(true);
+ expect(mockUpdater.install).toHaveBeenCalledTimes(1);
+ expect(mockUpdater.install).toHaveBeenCalledWith(false, true);
+
+ // A second exit-site call must not spawn a second installer.
+ expect(runPendingInstallOnExit()).toBe(false);
+ expect(mockUpdater.install).toHaveBeenCalledTimes(1);
+ });
+
+ test('an ordinary quit does not start the installer from the exit site', () => {
+ const { runPendingInstallOnExit } = require('../src/main/core/autoUpdater');
+
+ expect(runPendingInstallOnExit()).toBe(false);
+ expect(mockUpdater.install).not.toHaveBeenCalled();
+ });
+
+ test('with nothing downloaded, Install now reports an error and does not quit', async () => {
+ mockUpdater.installerPath = null;
+ const { quitAndInstall, runPendingInstallOnExit } = require('../src/main/core/autoUpdater');
+
+ expect(quitAndInstall()).toEqual({
+ success: false,
+ error: 'No downloaded update available yet. Check for updates and finish download first.'
+ });
+ await flushImmediate();
+
+ expect(mockApp.quit).not.toHaveBeenCalled();
+ expect(runPendingInstallOnExit()).toBe(false);
+ expect(mockUpdater.install).not.toHaveBeenCalled();
+ });
+
+ test('an installer that throws at the exit site does not block the exit', async () => {
+ mockUpdater.install.mockImplementation(() => {
+ throw new Error('spawn failed');
+ });
+ const { quitAndInstall, runPendingInstallOnExit } = require('../src/main/core/autoUpdater');
+
+ quitAndInstall();
+ await flushImmediate();
+
+ expect(runPendingInstallOnExit()).toBe(false);
+ });
+
+ test('macOS keeps electron-updater quitAndInstall (Squirrel installs after exit)', async () => {
+ setPlatform('darwin');
+ const { quitAndInstall, runPendingInstallOnExit } = require('../src/main/core/autoUpdater');
+
+ expect(quitAndInstall()).toEqual({ success: true });
+ await flushImmediate();
+
+ expect(mockUpdater.quitAndInstall).toHaveBeenCalledTimes(1);
+ expect(mockApp.quit).not.toHaveBeenCalled();
+ expect(runPendingInstallOnExit()).toBe(false);
+ });
+});
diff --git a/test/backgroundSetup.depsAutomation.test.js b/test/backgroundSetup.depsAutomation.test.js
index fbf8a645..9e11c564 100644
--- a/test/backgroundSetup.depsAutomation.test.js
+++ b/test/backgroundSetup.depsAutomation.test.js
@@ -184,6 +184,34 @@ describe('backgroundSetup automated dependencies', () => {
expect(downloadCalls).toEqual(['mmproj-model-f16.gguf']);
});
+ test('a failed background download also emits the terminal model-download-error event', async () => {
+ // Settings' "Add model" defers to this run on `alreadyInProgress` and only
+ // stops waiting on model-download-complete / model-download-error.
+ mockLlamaService.listModels.mockResolvedValueOnce([]);
+ mockDownloadManager.downloadModel.mockImplementation(async (modelName) => {
+ if (modelName === 'Mistral-7B-Instruct-v0.3-Q4_K_M.gguf') {
+ throw new Error('network reset');
+ }
+ if (modelName === 'nomic-embed-text-v1.5-Q8_0.gguf') {
+ throw new Error('Download already in progress');
+ }
+ return { success: true };
+ });
+
+ await runBackgroundSetup();
+
+ const terminalErrors = mockSendSpy.mock.calls
+ .map((call) => call.find((arg) => arg && typeof arg === 'object'))
+ .filter((arg) => arg?.type === 'model-download-error');
+ expect(terminalErrors).toEqual([
+ {
+ type: 'model-download-error',
+ model: 'Mistral-7B-Instruct-v0.3-Q4_K_M.gguf',
+ error: 'network reset'
+ }
+ ]);
+ });
+
test('companion projector download failure does not block the setup marker', async () => {
const fsPromises = require('fs').promises;
mockDownloadManager.downloadModel.mockImplementation(async (modelName) => {
diff --git a/test/cadDesignExtractors.aiThinText.test.js b/test/cadDesignExtractors.aiThinText.test.js
new file mode 100644
index 00000000..61b15a49
--- /dev/null
+++ b/test/cadDesignExtractors.aiThinText.test.js
@@ -0,0 +1,76 @@
+/**
+ * @jest-environment node
+ *
+ * A PDF-compatible .ai file whose type is outlined (a logo) has no or a thin
+ * text layer, and the PDF reader rejects it with PDF_NO_TEXT_CONTENT so OCR
+ * can run. Nothing runs OCR on the .ai route, so extractTextFromAi used to
+ * let the rejection escape and the file got a filename-only result. It now
+ * keeps the thin text the rejection carries, or falls back to the
+ * PostScript view. Fixtures live on the memfs-backed filesystem.
+ */
+
+const fs = require('fs');
+
+const { extractTextFromAi } = require('../src/main/analysis/extractors/cadDesignExtractors');
+
+const FIXTURE_DIR = '/fixtures-ai-thin';
+
+function writeFixture(name, data) {
+ fs.mkdirSync(FIXTURE_DIR, { recursive: true });
+ const filePath = `${FIXTURE_DIR}/${name}`;
+ fs.writeFileSync(filePath, data);
+ return filePath;
+}
+
+function noTextError(textLayer) {
+ const err = new Error('PDF has no text');
+ Object.assign(err, { code: 'PDF_NO_TEXT_CONTENT', metadata: { textLayer } });
+ return err;
+}
+
+const PDF_COMPATIBLE_AI = [
+ '%PDF-1.5',
+ '%%Creator: Adobe Illustrator(R) 24.0',
+ '%%Title: (acme-logo.ai)',
+ '%%BoundingBox: 0 0 200 100',
+ '1 0 obj << /Type /Catalog >> endobj',
+ ''
+].join('\n');
+
+describe('extractTextFromAi with a text-less PDF layer', () => {
+ test('returns the thin text layer the PDF reader rejected', async () => {
+ const filePath = writeFixture('thin.ai', PDF_COMPATIBLE_AI);
+ const extractTextFromPdf = jest.fn().mockRejectedValue(noTextError('ACME Corp'));
+ await expect(extractTextFromAi(filePath, { extractTextFromPdf })).resolves.toBe('ACME Corp');
+ });
+
+ test('falls back to the PostScript view when the PDF layer is empty', async () => {
+ const filePath = writeFixture('outlined.ai', PDF_COMPATIBLE_AI);
+ const extractTextFromPdf = jest.fn().mockRejectedValue(noTextError(''));
+ const text = await extractTextFromAi(filePath, { extractTextFromPdf });
+ expect(text.split('\n')[0]).toBe(
+ 'Adobe Illustrator document (PDF-compatible, PostScript view)'
+ );
+ expect(text).toContain('Title: acme-logo.ai');
+ });
+
+ test('falls back to the PostScript view when the PDF reader resolves blank', async () => {
+ const filePath = writeFixture('blank.ai', PDF_COMPATIBLE_AI);
+ const extractTextFromPdf = jest.fn().mockResolvedValue(' ');
+ const text = await extractTextFromAi(filePath, { extractTextFromPdf });
+ expect(text).toContain('Title: acme-logo.ai');
+ });
+
+ test('rethrows every other PDF error unchanged', async () => {
+ const filePath = writeFixture('locked.ai', PDF_COMPATIBLE_AI);
+ const encrypted = Object.assign(new Error('encrypted'), { code: 'PDF_ENCRYPTED' });
+ await expect(
+ extractTextFromAi(filePath, { extractTextFromPdf: jest.fn().mockRejectedValue(encrypted) })
+ ).rejects.toBe(encrypted);
+
+ const cancelled = Object.assign(new Error('cancelled'), { code: 'OPERATION_CANCELLED' });
+ await expect(
+ extractTextFromAi(filePath, { extractTextFromPdf: jest.fn().mockRejectedValue(cancelled) })
+ ).rejects.toBe(cancelled);
+ });
+});
diff --git a/test/components/AIProviderBadge.test.js b/test/components/AIProviderBadge.test.js
index 2f3e4bfc..4a5a0797 100644
--- a/test/components/AIProviderBadge.test.js
+++ b/test/components/AIProviderBadge.test.js
@@ -78,7 +78,7 @@ describe('AIProviderBadge', () => {
routing: { default: 'anthropic', perFolder: {} }
}
});
- const badge = screen.getByRole('status', { name: /cloud ai — anthropic claude/i });
+ const badge = screen.getByRole('status', { name: /cloud ai: anthropic claude/i });
expect(badge).toBeInTheDocument();
});
@@ -94,7 +94,7 @@ describe('AIProviderBadge', () => {
routing: { default: 'openaiCompatible', perFolder: {} }
}
});
- const badge = screen.getByRole('status', { name: /cloud ai — openai/i });
+ const badge = screen.getByRole('status', { name: /cloud ai: openai/i });
expect(badge).toBeInTheDocument();
});
diff --git a/test/components/AddSmartFolderModal.closeDuringGeneration.test.js b/test/components/AddSmartFolderModal.closeDuringGeneration.test.js
new file mode 100644
index 00000000..b249579c
--- /dev/null
+++ b/test/components/AddSmartFolderModal.closeDuringGeneration.test.js
@@ -0,0 +1,119 @@
+/**
+ * @jest-environment jsdom
+ *
+ * Closing the modal while "Generate with AI" is in flight must discard the
+ * late result. Callers keep the modal mounted while it is closed, so before
+ * the fix the old request's description landed in the next folder's form
+ * (with a "Description generated" toast) after the user reopened it.
+ */
+
+import React from 'react';
+import { render, screen, fireEvent, act } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import { Provider } from 'react-redux';
+import { configureStore, createSlice } from '@reduxjs/toolkit';
+
+const mockGetDocumentsPath = jest.fn();
+const mockSelectDirectory = jest.fn();
+const mockGenerateDescription = jest.fn();
+
+jest.mock('../../src/renderer/services/ipc', () => ({
+ filesIpc: {
+ getDocumentsPath: (...args) => mockGetDocumentsPath(...args),
+ selectDirectory: (...args) => mockSelectDirectory(...args)
+ },
+ smartFoldersIpc: {
+ generateDescription: (...args) => mockGenerateDescription(...args)
+ }
+}));
+
+jest.mock('../../src/shared/logger', () => ({
+ createLogger: () => ({
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn()
+ })
+}));
+
+import AddSmartFolderModal from '../../src/renderer/components/setup/AddSmartFolderModal';
+
+function makeStore() {
+ const system = createSlice({
+ name: 'system',
+ initialState: { redactPaths: false, redactPathsLoaded: true },
+ reducers: {}
+ });
+ return configureStore({ reducer: { system: system.reducer } });
+}
+
+describe('AddSmartFolderModal — closing during description generation', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ jest.useFakeTimers();
+ mockGetDocumentsPath.mockResolvedValue('C:/Users/Test/Documents');
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ test('a late result after close + reopen does not overwrite the new form', async () => {
+ let resolveGeneration;
+ mockGenerateDescription.mockReturnValueOnce(
+ new Promise((res) => {
+ resolveGeneration = res;
+ })
+ );
+
+ const store = makeStore();
+ const showNotification = jest.fn();
+ const onAdd = jest.fn().mockResolvedValue(true);
+ const onClose = jest.fn();
+ const ui = (isOpen) => (
+
+
+
+ );
+
+ const { rerender } = render(ui(true));
+ fireEvent.change(screen.getByLabelText(/Folder Name/i), { target: { value: 'Taxes' } });
+ fireEvent.click(screen.getByRole('button', { name: /Generate with AI/i }));
+ expect(screen.getByTitle(/Stop generating and write your own/i)).toBeInTheDocument();
+
+ // Close through the footer Cancel (the modal-level one, not the
+ // generation-specific button), then reopen the same mounted instance.
+ const footerCancel = screen
+ .getAllByRole('button', { name: /^Cancel$/i })
+ .find((btn) => !/Stop generating/i.test(btn.getAttribute('title') || ''));
+ fireEvent.click(footerCancel);
+ expect(onClose).toHaveBeenCalled();
+ rerender(ui(false));
+ rerender(ui(true));
+
+ // Fresh form: no stale spinner from the abandoned request.
+ expect(screen.queryByTitle(/Stop generating and write your own/i)).not.toBeInTheDocument();
+
+ fireEvent.change(screen.getByLabelText(/Folder Name/i), { target: { value: 'Photos' } });
+ const textarea = screen.getByPlaceholderText(/Describe what types of files/i);
+ fireEvent.change(textarea, { target: { value: 'Vacation photos' } });
+
+ await act(async () => {
+ resolveGeneration({ success: true, description: 'Tax returns and receipts.' });
+ });
+
+ expect(screen.getByPlaceholderText(/Describe what types of files/i).value).toBe(
+ 'Vacation photos'
+ );
+ expect(showNotification).not.toHaveBeenCalledWith('Description generated', 'success');
+ // Closing is not a user cancel of the generation, so no "cancelled" toast.
+ expect(showNotification).not.toHaveBeenCalledWith('Description generation cancelled', 'info');
+ });
+});
diff --git a/test/components/AddSmartFolderModal.generateDescription.test.js b/test/components/AddSmartFolderModal.generateDescription.test.js
index 14ddc56d..35f01d4a 100644
--- a/test/components/AddSmartFolderModal.generateDescription.test.js
+++ b/test/components/AddSmartFolderModal.generateDescription.test.js
@@ -204,7 +204,7 @@ describe('AddSmartFolderModal — Generate with AI feedback', () => {
test('timed-out response surfaces a hint asking the user to retry or type manually', async () => {
mockGenerateDescription.mockResolvedValueOnce({
success: false,
- error: 'Description generation timed out. Please try again.'
+ error: 'Description generation timed out. Try again.'
});
const { showNotification } = renderModal();
diff --git a/test/components/CompletePhase.everyFile.test.js b/test/components/CompletePhase.everyFile.test.js
index 12e5c06e..81c20b19 100644
--- a/test/components/CompletePhase.everyFile.test.js
+++ b/test/components/CompletePhase.everyFile.test.js
@@ -72,6 +72,11 @@ jest.mock('../../src/renderer/services/ipc', () => ({
}
}));
+// PhaseRenderer mounts the run provider above Complete.
+jest.mock('../../src/renderer/phases/discover/AnalysisRunProvider', () => ({
+ useAnalysisRun: () => ({ resetRun: jest.fn() })
+}));
+
import CompletePhase from '../../src/renderer/phases/CompletePhase';
const organized = (i, folder) => ({
diff --git a/test/components/CompletePhase.test.js b/test/components/CompletePhase.test.js
index f46c6c59..d5b19224 100644
--- a/test/components/CompletePhase.test.js
+++ b/test/components/CompletePhase.test.js
@@ -149,6 +149,11 @@ jest.mock('../../src/renderer/services/ipc', () => ({
}
}));
+// PhaseRenderer mounts the run provider above Complete.
+jest.mock('../../src/renderer/phases/discover/AnalysisRunProvider', () => ({
+ useAnalysisRun: () => ({ resetRun: jest.fn() })
+}));
+
import CompletePhase from '../../src/renderer/phases/CompletePhase';
describe('CompletePhase premium finish', () => {
diff --git a/test/components/DiscoverPhase.test.js b/test/components/DiscoverPhase.test.js
index 5b6bf2b8..28ed7c17 100644
--- a/test/components/DiscoverPhase.test.js
+++ b/test/components/DiscoverPhase.test.js
@@ -424,6 +424,33 @@ describe('DiscoverPhase premium guidance', () => {
useAnalysisRun.mockImplementation(originalAnalysisRun);
}
});
+
+ // Force reset goes through the run: the Redux-only reset cleared every
+ // finished result and left the run's lock held, so a retry was refused.
+ test('Force reset on a stuck run uses the run reset, not the Redux-only one', () => {
+ const { useDiscoverState, useAnalysisRun } = require('../../src/renderer/phases/discover');
+ const defaults = useDiscoverState();
+ const originalDiscoverState = useDiscoverState.getMockImplementation();
+ const originalAnalysisRun = useAnalysisRun.getMockImplementation();
+ const resetRun = jest.fn();
+ useDiscoverState.mockImplementation(() => ({
+ ...defaults,
+ isAnalyzing: true,
+ analysisProgress: { current: 1, total: 4, lastActivity: Date.now() - 10 * 60 * 1000 }
+ }));
+ useAnalysisRun.mockImplementation(() => ({ ...originalAnalysisRun(), resetRun }));
+
+ try {
+ render();
+ fireEvent.click(screen.getByRole('button', { name: 'Force reset' }));
+
+ expect(resetRun).toHaveBeenCalledWith('User forced reset');
+ expect(mockResetAnalysisState).not.toHaveBeenCalled();
+ } finally {
+ useDiscoverState.mockImplementation(originalDiscoverState);
+ useAnalysisRun.mockImplementation(originalAnalysisRun);
+ }
+ });
// A returning user with organized history may continue to Organize even
// with nothing ready in the queue, the same rule the Organize tab follows.
test('organized history lets Continue open Organize even when nothing is ready', () => {
diff --git a/test/components/DuplicateResolutionModal.lateGroups.test.js b/test/components/DuplicateResolutionModal.lateGroups.test.js
new file mode 100644
index 00000000..fabff053
--- /dev/null
+++ b/test/components/DuplicateResolutionModal.lateGroups.test.js
@@ -0,0 +1,164 @@
+/**
+ * @jest-environment jsdom
+ */
+/**
+ * The default keeper is pre-selected when the scan result arrives after the
+ * dialog is already open.
+ *
+ * Every caller opens the dialog and starts the scan in the same handler, so
+ * the first open render has no groups. Before the fix the defaults were set
+ * only on the closed-to-open transition, so the groups that arrived a moment
+ * later never got a keeper, and choices from an earlier session carried over.
+ */
+import React from 'react';
+import { render, screen, fireEvent } from '@testing-library/react';
+import '@testing-library/jest-dom';
+
+class ResizeObserverStub {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+globalThis.ResizeObserver = ResizeObserverStub;
+
+jest.mock('react-window', () => ({
+ List: ({ rowCount, rowComponent: RowComponent, rowProps, style }) => (
+
';
+ const result = await documentExtractors.extractPlainTextFromHtml(html);
+ expect(result).toBe('Hello World');
+ });
});
describe('checkFileSize', () => {
diff --git a/test/documentExtractors.pdfNoPin.test.js b/test/documentExtractors.pdfNoPin.test.js
new file mode 100644
index 00000000..cc43a283
--- /dev/null
+++ b/test/documentExtractors.pdfNoPin.test.js
@@ -0,0 +1,66 @@
+/**
+ * @jest-environment node
+ *
+ * extractTextFromPdf pins the file buffer for ocrPdfIfNeeded when the text
+ * layer is empty or thin. The .ai reader never runs OCR, so it passes
+ * pinForOcr: false; without it a batch of outlined-type Illustrator files
+ * stayed resident until the cache's TTL sweep. The thin text still rides on
+ * the rejection either way.
+ */
+
+const path = require('path');
+const fs = require('fs').promises;
+
+let mockNextText = '';
+
+jest.mock('unpdf', () => ({
+ getDocumentProxy: jest.fn(async () => ({ destroy: jest.fn(async () => undefined) })),
+ extractText: jest.fn(async () => ({ text: mockNextText, totalPages: 1 }))
+}));
+
+const {
+ extractTextFromPdf,
+ extractTextFromPdfRaw,
+ shutdownPdfBufferCache,
+ _pdfBufferCacheSizeForTests
+} = require('../src/main/analysis/documentExtractors');
+
+const TEST_DIR = '/tmp/pdf-no-pin-test';
+const AI_PATH = path.join(TEST_DIR, 'logo.ai');
+
+describe('extractTextFromPdf pinForOcr option', () => {
+ beforeEach(async () => {
+ mockNextText = '';
+ await fs.mkdir(TEST_DIR, { recursive: true });
+ await fs.writeFile(AI_PATH, Buffer.from('%PDF-1.5 fake illustrator content'));
+ });
+
+ afterEach(async () => {
+ await shutdownPdfBufferCache();
+ });
+
+ test('control: by default a text-less file is pinned for OCR', async () => {
+ await expect(extractTextFromPdfRaw(AI_PATH, 'logo.ai')).rejects.toMatchObject({
+ code: 'PDF_NO_TEXT_CONTENT'
+ });
+ expect(_pdfBufferCacheSizeForTests()).toBe(1);
+ });
+
+ test('pinForOcr: false leaves the cache empty', async () => {
+ await expect(
+ extractTextFromPdfRaw(AI_PATH, 'logo.ai', { pinForOcr: false })
+ ).rejects.toMatchObject({ code: 'PDF_NO_TEXT_CONTENT' });
+ expect(_pdfBufferCacheSizeForTests()).toBe(0);
+ });
+
+ test('the timeout wrapper passes pinForOcr through and the thin text survives', async () => {
+ mockNextText = 'ACME Corp';
+ await expect(
+ extractTextFromPdf(AI_PATH, 'logo.ai', { pinForOcr: false })
+ ).rejects.toMatchObject({
+ code: 'PDF_NO_TEXT_CONTENT',
+ metadata: expect.objectContaining({ textLayer: 'ACME Corp' })
+ });
+ expect(_pdfBufferCacheSizeForTests()).toBe(0);
+ });
+});
diff --git a/test/e2e/helpers/electronApp.js b/test/e2e/helpers/electronApp.js
index a39712df..817231ba 100644
--- a/test/e2e/helpers/electronApp.js
+++ b/test/e2e/helpers/electronApp.js
@@ -18,7 +18,7 @@ const { _electron: electron } = require('@playwright/test');
const path = require('path');
const fs = require('fs');
const os = require('os');
-const { execSync } = require('child_process');
+const { execFileSync } = require('child_process');
// Configuration
const APP_ROOT = path.resolve(__dirname, '../../..');
@@ -206,20 +206,30 @@ function killOrphanStratoSortElectronProcesses() {
// Match both the bundled (dist\main.js) and legacy (simple-main) entry
// args, scoped to electron.exe spawned from THIS repo's node_modules so
// unrelated Electron apps are never touched.
+ // Arguments go straight to the program, with no shell in between; the
+ // script uses single quotes only, so Node's argument quoting can't
+ // split it.
const repoMarker = APP_ROOT.replace(/'/g, "''");
- execSync(
- 'powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \\"Name = \'electron.exe\'\\" | ' +
- `Where-Object { $_.CommandLine -like '*${repoMarker}*' -and ($_.CommandLine -like '*dist*main.js*' -or $_.CommandLine -like '*simple-main*') } | ` +
- 'ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }"',
+ execFileSync(
+ 'powershell',
+ [
+ '-NoProfile',
+ '-Command',
+ "Get-CimInstance Win32_Process -Filter 'Name = ''electron.exe''' | " +
+ `Where-Object { $_.CommandLine -like '*${repoMarker}*' -and ($_.CommandLine -like '*dist*main.js*' -or $_.CommandLine -like '*simple-main*') } | ` +
+ 'ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }'
+ ],
{ stdio: 'ignore', timeout: 8000 }
);
} else {
- execSync(
- `pkill -f "electron.*(simple-main|${APP_ROOT.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}.*dist/main\\.js)" || true`,
- {
- stdio: 'ignore',
- timeout: 5000
- }
+ // pkill exits 1 when nothing matched, which lands in the catch below.
+ execFileSync(
+ 'pkill',
+ [
+ '-f',
+ `electron.*(simple-main|${APP_ROOT.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}.*dist/main\\.js)`
+ ],
+ { stdio: 'ignore', timeout: 5000 }
);
}
} catch {
diff --git a/test/e2e/settings/ai-provider.spec.js b/test/e2e/settings/ai-provider.spec.js
index 529ee0a0..b4b27d6e 100644
--- a/test/e2e/settings/ai-provider.spec.js
+++ b/test/e2e/settings/ai-provider.spec.js
@@ -208,7 +208,7 @@ test.describe('AI Provider — Settings UI', () => {
await window.waitForTimeout(200);
const hasBadge = await window.evaluate(() => {
- return Boolean(document.querySelector('[role="status"][aria-label^="Cloud AI —"]'));
+ return Boolean(document.querySelector('[role="status"][aria-label^="Cloud AI"]'));
});
expect(hasBadge).toBe(false);
});
diff --git a/test/embeddingQueue-modelChange.test.js b/test/embeddingQueue-modelChange.test.js
new file mode 100644
index 00000000..7ec99d7a
--- /dev/null
+++ b/test/embeddingQueue-modelChange.test.js
@@ -0,0 +1,147 @@
+/**
+ * Vectors waiting in the embedding queue (or its failed-items map and
+ * dead-letter queue) that a different embedding model produced must never be
+ * written into the index. With a different dimension they churned into the
+ * dead-letter queue; with the same dimension they were written silently and
+ * mixed two vector spaces in one index.
+ * Uses the real failed-item handler and parallel processor against a stub
+ * vector service; persistence is stubbed.
+ */
+
+jest.mock('electron', () => ({
+ app: { getPath: jest.fn(() => '/tmp/user-data') }
+}));
+
+jest.mock('../src/shared/logger', () => {
+ const logger = { info: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() };
+ return { logger, createLogger: () => logger };
+});
+
+jest.mock('../src/shared/config/index', () => ({
+ get: jest.fn((_key, fallback) => fallback)
+}));
+
+jest.mock('../src/shared/pathTraceLogger', () => ({
+ traceQueueUpdate: jest.fn()
+}));
+
+jest.mock('../src/main/analysis/embeddingQueue/persistence', () => ({
+ loadPersistedData: jest.fn().mockResolvedValue(undefined),
+ persistQueueData: jest.fn().mockResolvedValue(undefined),
+ persistFailedItems: jest.fn().mockResolvedValue(true),
+ persistDeadLetterQueue: jest.fn().mockResolvedValue(true),
+ SQLITE_KEYS: { queue: 'queue', failedItems: 'failedItems', deadLetter: 'deadLetter' }
+}));
+
+const mockContainer = { resolve: jest.fn() };
+
+jest.mock('../src/main/services/ServiceContainer', () => ({
+ container: mockContainer,
+ ServiceIds: {
+ ORAMA_VECTOR: 'ORAMA_VECTOR',
+ ANALYSIS_HISTORY: 'ANALYSIS_HISTORY',
+ PROCESSING_STATE: 'PROCESSING_STATE'
+ }
+}));
+
+const { logger: mockLogger } = require('../src/shared/logger');
+const EmbeddingQueue = require('../src/main/analysis/embeddingQueue/EmbeddingQueueCore');
+
+const OLD_MODEL = 'old-embed-v1-Q8_0.gguf';
+const NEW_MODEL = 'new-embed-v2-Q8_0.gguf';
+
+/** Both models are 2-dimensional here, so nothing but the model tells them apart. */
+function fileItem(name, model) {
+ const item = { id: `file:/docs/${name}`, vector: [0.1, 0.2], meta: { path: `/docs/${name}` } };
+ if (model) item.model = model;
+ return item;
+}
+
+function deadLetterEntry(item) {
+ return { item, itemId: item.id, error: 'dimension_mismatch', retryCount: 1 };
+}
+
+describe('EmbeddingQueue after an embedding-model change', () => {
+ let vectorDb;
+ let history;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ vectorDb = {
+ initialize: jest.fn().mockResolvedValue(undefined),
+ isOnline: true,
+ getEmbeddingModel: jest.fn(() => NEW_MODEL),
+ batchUpsertFiles: jest.fn(async (files) => ({ success: true, count: files.length }))
+ };
+ history = { updateEmbeddingStateByPath: jest.fn().mockResolvedValue(undefined) };
+ mockContainer.resolve.mockReset();
+ mockContainer.resolve.mockImplementation((id) => {
+ if (id === 'ORAMA_VECTOR') return vectorDb;
+ if (id === 'ANALYSIS_HISTORY') return history;
+ if (id === 'PROCESSING_STATE') return null;
+ throw new Error(`unexpected service ${id}`);
+ });
+ });
+
+ async function newQueue() {
+ const q = new EmbeddingQueue({ flushDelayMs: 0 });
+ // Persistence is stubbed, so this restores nothing.
+ await q.initialize();
+ // Keeps flush from arming retry and persist timers that outlive the test.
+ q._isShuttingDown = true;
+ return q;
+ }
+
+ test('flush never writes a vector from another model, even one of the same dimension', async () => {
+ const q = await newQueue();
+ const stale = fileItem('stale.pdf', OLD_MODEL);
+ const fresh = fileItem('fresh.pdf', NEW_MODEL);
+ // Another quantization of the index model embeds into the same space
+ // (the same-dimension fallback chain produces these).
+ const quantized = fileItem('quantized.pdf', 'new-embed-v2-Q4_K_M.gguf');
+ // No stamp: nothing says which model made it, so flush keeps it.
+ const unstamped = fileItem('unstamped.pdf');
+ q.queue = [stale, fresh, quantized, unstamped];
+
+ await q.flush();
+
+ expect(vectorDb.batchUpsertFiles).toHaveBeenCalledTimes(1);
+ const written = vectorDb.batchUpsertFiles.mock.calls[0][0].map((f) => f.id);
+ expect(written).toEqual([fresh.id, quantized.id, unstamped.id]);
+ expect(q.queue).toHaveLength(0);
+ // Dropped, not failed: it must not churn into the retry or dead-letter queues.
+ expect(q._failedItemHandler.failedItems.has(stale.id)).toBe(false);
+ expect(q._failedItemHandler.deadLetterQueue).toHaveLength(0);
+ // Nor be reported as embedded.
+ expect(history.updateEmbeddingStateByPath).not.toHaveBeenCalledWith('/docs/stale.pdf', {
+ status: 'done'
+ });
+ });
+
+ test('a model change drops queued, retrying and dead-lettered vectors not from the new model', async () => {
+ const q = await newQueue();
+ const fresh = fileItem('fresh.pdf', NEW_MODEL);
+ q.queue = [fileItem('stale.pdf', OLD_MODEL), fileItem('unstamped.pdf'), fresh];
+ const retrying = fileItem('retrying.pdf', OLD_MODEL);
+ q._failedItemHandler.failedItems.set(retrying.id, {
+ item: retrying,
+ retryCount: 1,
+ lastAttempt: Date.now(),
+ error: 'timeout'
+ });
+ const freshDead = deadLetterEntry(fileItem('fresh-dead.pdf', NEW_MODEL));
+ q._failedItemHandler.setDeadLetterQueue([
+ deadLetterEntry(fileItem('dead.pdf', OLD_MODEL)),
+ freshDead
+ ]);
+
+ const dropped = q.dropOtherModelEmbeddings(NEW_MODEL);
+
+ expect(dropped).toBe(4);
+ expect(q.queue).toEqual([fresh]);
+ expect(q._failedItemHandler.failedItems.size).toBe(0);
+ expect(q._failedItemHandler.deadLetterQueue).toEqual([freshDead]);
+ const dropLines = mockLogger.info.mock.calls.filter(([msg]) => /Dropped 4 /.test(msg));
+ expect(dropLines).toHaveLength(1);
+ });
+});
diff --git a/test/embeddingQueue-parallelProcessor.test.js b/test/embeddingQueue-parallelProcessor.test.js
index 7faf36be..22da2d6e 100644
--- a/test/embeddingQueue-parallelProcessor.test.js
+++ b/test/embeddingQueue-parallelProcessor.test.js
@@ -117,6 +117,45 @@ describe('embeddingQueue parallelProcessor', () => {
expect(failedItemIds.has('file:b')).toBe(true);
});
+ test('a batch where one item has the wrong dimension fails only that item', async () => {
+ const vectorDbService = {
+ batchUpsertFiles: jest.fn().mockResolvedValue({
+ success: false,
+ count: 2,
+ failed: [{ id: 'file:stale', error: 'dimension_mismatch', requiresRebuild: true }]
+ }),
+ upsertFile: jest.fn().mockResolvedValue({ success: true })
+ };
+ const onProgress = jest.fn();
+ const onItemFailed = jest.fn();
+ const failedItemIds = new Set();
+
+ const items = [
+ { id: 'file:a', vector: [1, 2, 3], meta: { path: 'a' } },
+ { id: 'file:stale', vector: [1, 2], meta: { path: 'stale' } },
+ { id: 'file:b', vector: [1, 2, 3], meta: { path: 'b' } }
+ ];
+
+ const processed = await processItemsInParallel({
+ items,
+ type: 'file',
+ vectorDbService,
+ failedItemIds,
+ startProcessedCount: 0,
+ totalBatchSize: 3,
+ concurrency: 2,
+ onProgress,
+ onItemFailed
+ });
+
+ expect(processed).toBe(2);
+ expect(onItemFailed).toHaveBeenCalledTimes(1);
+ expect(onItemFailed).toHaveBeenCalledWith(items[1], 'dimension_mismatch');
+ expect(Array.from(failedItemIds)).toEqual(['file:stale']);
+ // The written items are not upserted a second time through the fallback.
+ expect(vectorDbService.upsertFile).not.toHaveBeenCalled();
+ });
+
test('marks failed items when individual upsert returns success:false', async () => {
const vectorDbService = {
upsertFile: jest.fn().mockResolvedValueOnce({ success: false, error: 'bad_vector' })
diff --git a/test/errorMapping.circuitOpen.test.js b/test/errorMapping.circuitOpen.test.js
index 1c3974c0..9b91379a 100644
--- a/test/errorMapping.circuitOpen.test.js
+++ b/test/errorMapping.circuitOpen.test.js
@@ -10,7 +10,7 @@
const { mapErrorToNotification } = require('../src/renderer/utils/errorMapping');
describe('errorMapping: open circuit breaker', () => {
- const recovering = 'AI service is temporarily recovering. Please wait a moment and try again.';
+ const recovering = 'AI service is temporarily recovering. Wait a moment and try again.';
test('maps the breaker message that CircuitBreaker.execute actually throws', () => {
expect(
diff --git a/test/failedItemHandler.test.js b/test/failedItemHandler.test.js
index 36b2aa40..0958078b 100644
--- a/test/failedItemHandler.test.js
+++ b/test/failedItemHandler.test.js
@@ -111,6 +111,23 @@ describe('failedItemHandler', () => {
);
});
+ test('routes invalid vector values directly to dead letter (a retry re-queues the same NaN vector)', () => {
+ const item = { id: 'file:nan.txt', vector: [1, Number.NaN, 2] };
+
+ handler.trackFailedItem(item, 'invalid_vector_values');
+
+ expect(handler.failedItems.size).toBe(0);
+ expect(handler.getItemsToRetry(Date.now() + 60_000)).toEqual([]);
+ expect(handler.deadLetterQueue).toHaveLength(1);
+ expect(handler.deadLetterQueue[0]).toEqual(
+ expect.objectContaining({
+ itemId: item.id,
+ requiresRebuild: false,
+ errorCode: 'invalid_vector_values'
+ })
+ );
+ });
+
test('persists failed items to disk', () => {
const item = { id: 'file:test.txt', vector: [0.1, 0.2] };
diff --git a/test/fileDedup.emptyFile.test.js b/test/fileDedup.emptyFile.test.js
new file mode 100644
index 00000000..3fec5649
--- /dev/null
+++ b/test/fileDedup.emptyFile.test.js
@@ -0,0 +1,100 @@
+/**
+ * @jest-environment node
+ */
+/**
+ * Every empty file has the same size and hash, so two unrelated 0-byte files
+ * looked like duplicates and the source being organized was trashed instead
+ * of moved. An empty source is never deduplicated.
+ */
+
+jest.unmock('fs');
+jest.unmock('fs/promises');
+jest.unmock('os');
+
+const path = require('path');
+const fs = require('fs').promises;
+const os = require('os');
+
+const { handleDuplicateMove, findDuplicateForDestination } = require('../src/main/utils/fileDedup');
+
+describe('fileDedup empty source', () => {
+ let testDir;
+ let sourceDir;
+ let destDir;
+
+ beforeEach(async () => {
+ testDir = await fs.mkdtemp(path.join(os.tmpdir(), 'dedup-empty-'));
+ sourceDir = path.join(testDir, 'incoming');
+ destDir = path.join(testDir, 'target');
+ await fs.mkdir(sourceDir);
+ await fs.mkdir(destDir);
+ });
+
+ afterEach(async () => {
+ try {
+ await fs.rm(testDir, { recursive: true, force: true });
+ } catch {
+ // best-effort tmp cleanup
+ }
+ });
+
+ test('an empty file already at the exact destination is not a duplicate', async () => {
+ const source = path.join(sourceDir, 'notes.txt');
+ const destination = path.join(destDir, 'notes.txt');
+ await fs.writeFile(source, '');
+ await fs.writeFile(destination, '');
+
+ expect(
+ await findDuplicateForDestination({ sourcePath: source, destinationPath: destination })
+ ).toBeNull();
+
+ const unlinkFn = jest.fn();
+ const result = await handleDuplicateMove({
+ sourcePath: source,
+ destinationPath: destination,
+ unlinkFn,
+ logger: null
+ });
+ expect(result).toBeNull();
+ expect(unlinkFn).not.toHaveBeenCalled();
+ await expect(fs.access(source)).resolves.toBeUndefined();
+ });
+
+ test('an unrelated empty file in the destination folder is not a duplicate', async () => {
+ const source = path.join(sourceDir, 'placeholder.md');
+ await fs.writeFile(source, '');
+ await fs.writeFile(path.join(destDir, 'other-empty.log'), '');
+
+ const unlinkFn = jest.fn();
+ const result = await handleDuplicateMove({
+ sourcePath: source,
+ destinationPath: path.join(destDir, 'placeholder.md'),
+ unlinkFn,
+ logger: null
+ });
+ expect(result).toBeNull();
+ expect(unlinkFn).not.toHaveBeenCalled();
+ await expect(fs.access(source)).resolves.toBeUndefined();
+ });
+
+ test('a non-empty identical file in the destination folder still dedupes', async () => {
+ const source = path.join(sourceDir, 'report.pdf');
+ await fs.writeFile(source, 'same-bytes');
+ await fs.writeFile(path.join(destDir, 'report-copy.pdf'), 'same-bytes');
+
+ const unlinkFn = jest.fn().mockResolvedValue(undefined);
+ const result = await handleDuplicateMove({
+ sourcePath: source,
+ destinationPath: path.join(destDir, 'report.pdf'),
+ unlinkFn,
+ logger: null
+ });
+ expect(result).toEqual(
+ expect.objectContaining({
+ skipped: true,
+ destination: path.join(destDir, 'report-copy.pdf')
+ })
+ );
+ expect(unlinkFn).toHaveBeenCalledWith(source);
+ });
+});
diff --git a/test/fileOperationHandlers.batchMoveThrow.test.js b/test/fileOperationHandlers.batchMoveThrow.test.js
new file mode 100644
index 00000000..89811e82
--- /dev/null
+++ b/test/fileOperationHandlers.batchMoveThrow.test.js
@@ -0,0 +1,237 @@
+/**
+ * @jest-environment node
+ */
+const { IPC_CHANNELS } = require('../src/shared/constants');
+
+// Mock dependencies
+jest.mock('fs', () => ({
+ promises: {
+ stat: jest.fn().mockResolvedValue({ size: 100 }),
+ access: jest.fn().mockResolvedValue(),
+ rename: jest.fn().mockResolvedValue(),
+ copyFile: jest.fn().mockResolvedValue(),
+ unlink: jest.fn().mockResolvedValue(),
+ mkdir: jest.fn().mockResolvedValue()
+ },
+ constants: { COPYFILE_EXCL: 1 }
+}));
+
+jest.mock('../src/shared/logger', () => {
+ const logger = {
+ info: jest.fn(),
+ warn: jest.fn(),
+ error: jest.fn(),
+ debug: jest.fn(),
+ setContext: jest.fn()
+ };
+ return { createLogger: jest.fn(() => logger), logger };
+});
+
+jest.mock('../src/main/ipc/ipcWrappers', () => ({
+ createHandler: jest.fn(({ handler }) => handler),
+ safeHandle: jest.fn(),
+ withErrorLogging: jest.fn((logger, handler) => handler),
+ withValidation: jest.fn((logger, schema, handler) => handler),
+ safeSend: jest.fn()
+}));
+
+jest.mock('../src/main/ipc/files/batchOrganizeHandler', () => ({
+ handleBatchOrganize: jest.fn().mockResolvedValue({ success: true, count: 1 })
+}));
+
+jest.mock('../src/shared/pathSanitization', () => ({
+ validateFileOperationPath: jest.fn((p) => ({ valid: true, normalizedPath: p }))
+}));
+
+jest.mock('../src/shared/pathTraceLogger', () => ({
+ traceMoveStart: jest.fn(),
+ traceMoveComplete: jest.fn(),
+ traceCopyStart: jest.fn(),
+ traceCopyComplete: jest.fn(),
+ traceDeleteStart: jest.fn(),
+ traceDeleteComplete: jest.fn(),
+ traceDbUpdate: jest.fn(),
+ PathChangeReason: { USER_MOVE: 'user_move' }
+}));
+
+jest.mock('../src/main/services/organization/learningFeedback', () => ({
+ getInstance: jest.fn(),
+ FEEDBACK_SOURCES: { MANUAL_MOVE: 'manual_move' }
+}));
+
+jest.mock('../src/main/ipc/files/embeddingSync', () => ({
+ syncEmbeddingForMove: jest.fn().mockResolvedValue()
+}));
+
+jest.mock('../src/shared/promiseUtils', () => ({
+ withTimeout: jest.fn((p) => p),
+ createBackgroundWorkTracker: jest.fn(() => ({
+ track: jest.fn((p) => p),
+ drain: jest.fn(),
+ get size() {
+ return 0;
+ }
+ })),
+ createInitGuard: jest.fn(() => ({
+ isInitialized: () => false,
+ initialize: jest.fn(async (fn) => fn()),
+ reset: jest.fn(),
+ requireInitialized: jest.fn()
+ }))
+}));
+
+jest.mock('../src/shared/atomicFileOperations', () => ({
+ crossDeviceMove: jest.fn(),
+ // Delegate to the suite's fs.rename mock; tests drive occupied-destination
+ // behavior by seeding renameNoReplace rejections. Real no-replace semantics
+ // are covered by atomicFileOperations.test.js.
+ renameNoReplace: jest.fn((src, dest) => require('fs').promises.rename(src, dest))
+}));
+
+jest.mock('../src/main/utils/fileDedup', () => ({
+ handleDuplicateMove: jest.fn().mockResolvedValue(null)
+}));
+
+jest.mock('../src/main/ipc/semantic', () => ({
+ getSearchServiceInstance: jest.fn(),
+ getClusteringServiceInstance: jest.fn()
+}));
+
+jest.mock('../src/main/services/ServiceContainer', () => ({
+ container: {
+ has: jest.fn(),
+ resolve: jest.fn()
+ },
+ ServiceIds: {
+ FILE_PATH_COORDINATOR: 'filePathCoordinator',
+ ANALYSIS_HISTORY: 'analysisHistory'
+ }
+}));
+
+// Mock validation schemas to avoid Zod issues
+jest.mock('../src/main/ipc/validationSchemas', () => ({
+ z: {},
+ schemas: {}
+}));
+
+// Destination policy: real module, with the decision points wrapped so one
+// test can refuse a destination. Elsewhere the global electron mock's dialog
+// approves, as it does for every pre-existing test here.
+jest.mock('../src/main/ipc/files/destinationPolicy', () => {
+ const actual = jest.requireActual('../src/main/ipc/files/destinationPolicy');
+ return {
+ ...actual,
+ authorizeDestination: jest.fn(actual.authorizeDestination),
+ authorizeDestinations: jest.fn(actual.authorizeDestinations)
+ };
+});
+
+// batch_move: a move that THROWS (EBUSY/EPERM on a locked file, a failed
+// cross-device copy) must not abort the whole selection. Before the fix the
+// throw escaped the loop: the earlier moves stayed at their new paths with no
+// MOVE_BATCH undo entry, later files were never tried, and no `results` came
+// back, so the renderer counted every file as failed.
+describe('batch_move when one move throws', () => {
+ let fs;
+ let safeHandle;
+ let mockServiceIntegration;
+ let mockFilePathCoordinator;
+
+ beforeEach(() => {
+ jest.clearAllMocks();
+ jest.resetModules();
+
+ fs = require('fs').promises;
+ safeHandle = require('../src/main/ipc/ipcWrappers').safeHandle;
+ const mockLogger = require('../src/shared/logger').logger;
+ require('../src/main/utils/fileDedup').handleDuplicateMove.mockResolvedValue(null);
+
+ mockServiceIntegration = {
+ undoRedo: { recordAction: jest.fn(), recordBatch: jest.fn() }
+ };
+ require('../src/main/ipc/semantic').getSearchServiceInstance.mockReturnValue({
+ invalidateAndRebuild: jest.fn().mockResolvedValue()
+ });
+ require('../src/main/ipc/semantic').getClusteringServiceInstance.mockReturnValue({
+ invalidateClusters: jest.fn()
+ });
+ mockFilePathCoordinator = {
+ atomicPathUpdate: jest.fn().mockResolvedValue({ success: true }),
+ handleFileCopy: jest.fn().mockResolvedValue({ success: true }),
+ handleFileDeletion: jest.fn().mockResolvedValue({ success: true })
+ };
+ const { container } = require('../src/main/services/ServiceContainer');
+ container.has.mockReturnValue(true);
+ container.resolve.mockReturnValue(mockFilePathCoordinator);
+
+ const { IpcServiceContext } = require('../src/main/ipc/IpcServiceContext');
+ const context = new IpcServiceContext();
+ context.setCore({ ipcMain: { handle: jest.fn() }, IPC_CHANNELS, logger: mockLogger });
+ context.setElectron({
+ getMainWindow: () => ({ isDestroyed: () => false, webContents: { send: jest.fn() } })
+ });
+ context.setServiceIntegration(() => mockServiceIntegration);
+
+ require('../src/main/ipc/files/fileOperationHandlers').registerFileOperationHandlers(context);
+ });
+
+ function getPerformHandler() {
+ const call = safeHandle.mock.calls.find((c) => c[1] === IPC_CHANNELS.FILES.PERFORM_OPERATION);
+ if (!call) throw new Error('PERFORM_OPERATION handler not registered');
+ return call[2];
+ }
+
+ const operations = [
+ { source: '/src/a.pdf', destination: '/dest/a.pdf' },
+ { source: '/src/locked.pdf', destination: '/dest/locked.pdf' },
+ { source: '/src/c.pdf', destination: '/dest/c.pdf' }
+ ];
+
+ test('keeps going, returns per-file results and records the moves that happened', async () => {
+ fs.rename.mockImplementation(async (src) => {
+ if (src === '/src/locked.pdf') {
+ throw Object.assign(new Error('operation not permitted'), { code: 'EPERM' });
+ }
+ });
+
+ const result = await getPerformHandler()({}, { type: 'batch_move', operations });
+
+ expect(result.success).toBe(false);
+ expect(result.moved).toBe(2);
+ expect(result.failed).toBe(1);
+ expect(result.results).toHaveLength(3);
+ expect(result.results[1]).toEqual(
+ expect.objectContaining({
+ success: false,
+ source: '/src/locked.pdf',
+ destination: '/dest/locked.pdf',
+ errorCode: 'EPERM',
+ error: 'operation not permitted'
+ })
+ );
+ // The file after the failing one was still attempted.
+ expect(fs.rename).toHaveBeenCalledWith('/src/c.pdf', '/dest/c.pdf');
+ expect(mockServiceIntegration.undoRedo.recordBatch).toHaveBeenCalledTimes(1);
+ expect(mockServiceIntegration.undoRedo.recordBatch).toHaveBeenCalledWith(
+ 'MOVE_BATCH',
+ [
+ { type: 'move', originalPath: '/src/a.pdf', newPath: '/dest/a.pdf' },
+ { type: 'move', originalPath: '/src/c.pdf', newPath: '/dest/c.pdf' }
+ ],
+ { summary: { label: 'Move files', source: 'manual_batch_move' } }
+ );
+ });
+
+ test('a thrown error without a code is reported as MOVE_FAILED', async () => {
+ fs.rename.mockImplementation(async (src) => {
+ if (src === '/src/locked.pdf') throw new Error('boom');
+ });
+
+ const result = await getPerformHandler()({}, { type: 'batch_move', operations });
+
+ expect(result.moved).toBe(2);
+ expect(result.results[1]).toEqual(
+ expect.objectContaining({ success: false, errorCode: 'MOVE_FAILED', error: 'boom' })
+ );
+ });
+});
diff --git a/test/fileThunks.test.js b/test/fileThunks.test.js
index acb30ff8..f6e39b49 100644
--- a/test/fileThunks.test.js
+++ b/test/fileThunks.test.js
@@ -211,12 +211,43 @@ describe('fileThunks', () => {
);
});
- test('does not dispatch when API returns failure', async () => {
+ test('warns instead of updating state when API returns failure', async () => {
mockSetEmbeddingPolicy.mockResolvedValue({ success: false });
await setEmbeddingPolicyForFile('/file.pdf', 'embed')(dispatch, getState);
- expect(dispatch).not.toHaveBeenCalled();
+ expect(updateEmbeddingState).not.toHaveBeenCalled();
+ expect(dispatch).toHaveBeenCalledTimes(1);
+ expect(dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'system/addNotification',
+ payload: expect.objectContaining({
+ severity: 'warning',
+ message: expect.stringContaining('could not be changed')
+ })
+ })
+ );
+ });
+
+ test('tells the user to analyze first when main reports notFound', async () => {
+ mockSetEmbeddingPolicy.mockResolvedValue({
+ success: false,
+ notFound: true,
+ error: 'No analysis history entry for this path'
+ });
+
+ await setEmbeddingPolicyForFile('/file.pdf', 'skip')(dispatch, getState);
+
+ expect(updateEmbeddingState).not.toHaveBeenCalled();
+ expect(dispatch).toHaveBeenCalledWith(
+ expect.objectContaining({
+ type: 'system/addNotification',
+ payload: expect.objectContaining({
+ severity: 'warning',
+ message: expect.stringContaining('no saved analysis yet')
+ })
+ })
+ );
});
test('handles null result from API', async () => {
diff --git a/test/folderRenamePathChanges.unicodeCase.test.js b/test/folderRenamePathChanges.unicodeCase.test.js
new file mode 100644
index 00000000..798598fc
--- /dev/null
+++ b/test/folderRenamePathChanges.unicodeCase.test.js
@@ -0,0 +1,73 @@
+/**
+ * The relative part of each history path must come from the case-preserved
+ * path. toLowerCase() is not length-preserving ('İ' U+0130 becomes two UTF-16
+ * units), so slicing the original path by the folded key's length used to
+ * drop the first characters of every file name ("report.pdf" -> "eport.pdf").
+ */
+const { buildFolderRenamePathChanges } = require('../src/main/utils/folderRenamePathChanges');
+
+describe('buildFolderRenamePathChanges with length-changing case folds', () => {
+ test("win32: 'İ' in the renamed folder keeps file names intact", () => {
+ const entries = [{ originalPath: 'C:\\Users\\a\\İzmir\\report.pdf' }];
+ expect(
+ buildFolderRenamePathChanges(entries, 'C:/Users/a/İzmir', 'C:/Users/a/Trips', {
+ platform: 'win32'
+ })
+ ).toEqual([
+ { oldPath: 'C:\\Users\\a\\İzmir\\report.pdf', newPath: 'C:\\Users\\a\\Trips\\report.pdf' }
+ ]);
+ });
+
+ test("win32: 'İ' in a parent folder and a nested file", () => {
+ const entries = [{ originalPath: 'C:\\Users\\İuser\\Docs\\Old\\sub\\notes.txt' }];
+ expect(
+ buildFolderRenamePathChanges(
+ entries,
+ 'C:\\Users\\İuser\\Docs\\Old',
+ 'C:\\Users\\İuser\\Docs\\New',
+ { platform: 'win32' }
+ )
+ ).toEqual([
+ {
+ oldPath: 'C:\\Users\\İuser\\Docs\\Old\\sub\\notes.txt',
+ newPath: 'C:\\Users\\İuser\\Docs\\New\\sub\\notes.txt'
+ }
+ ]);
+ });
+
+ test("darwin: 'İ' in parent and renamed folder, history path cased differently", () => {
+ const entries = [
+ { originalPath: '/Users/İuser/İzmir/report.pdf' },
+ // 'İ'.toLowerCase() is 'i' + U+0307, so this matches the folder on a
+ // case-insensitive volume while being a different length.
+ { originalPath: '/users/i\u0307user/i\u0307zmir/Photos/beach.jpg' }
+ ];
+ expect(
+ buildFolderRenamePathChanges(entries, '/Users/İuser/İzmir', '/Users/İuser/Trips', {
+ platform: 'darwin'
+ })
+ ).toEqual([
+ { oldPath: '/Users/İuser/İzmir/report.pdf', newPath: '/Users/İuser/Trips/report.pdf' },
+ {
+ oldPath: '/users/i\u0307user/i\u0307zmir/Photos/beach.jpg',
+ newPath: '/Users/İuser/Trips/Photos/beach.jpg'
+ }
+ ]);
+ });
+
+ test('win32: UNC roots still map by segment', () => {
+ const entries = [{ originalPath: '\\\\server\\share\\İzmir\\a.txt' }];
+ expect(
+ buildFolderRenamePathChanges(
+ entries,
+ '\\\\server\\share\\İzmir',
+ '\\\\server\\share\\Trips',
+ {
+ platform: 'win32'
+ }
+ )
+ ).toEqual([
+ { oldPath: '\\\\server\\share\\İzmir\\a.txt', newPath: '\\\\server\\share\\Trips\\a.txt' }
+ ]);
+ });
+});
diff --git a/test/htmlEntities.prototypeKeys.test.js b/test/htmlEntities.prototypeKeys.test.js
new file mode 100644
index 00000000..e2c91bfb
--- /dev/null
+++ b/test/htmlEntities.prototypeKeys.test.js
@@ -0,0 +1,49 @@
+/**
+ * @jest-environment node
+ *
+ * The named-entity tables are plain objects keyed by names taken from the
+ * document. '&constructor;' or '&toString;' used to resolve to the
+ * Object.prototype function and put "function Object() { [native code] }"
+ * into the analyzed text. Unknown names must stay as written.
+ */
+
+const AdmZip = require('adm-zip');
+
+const { decodeHtmlEntities } = require('../src/main/analysis/extractors/htmlEntities');
+const { readEpubStructure } = require('../src/main/analysis/extractors/epubStructure');
+
+describe('decodeHtmlEntities with Object.prototype names', () => {
+ test('leaves prototype-member names as written', () => {
+ expect(decodeHtmlEntities('a &constructor; b &toString; c &hasOwnProperty; d')).toBe(
+ 'a &constructor; b &toString; c &hasOwnProperty; d'
+ );
+ });
+
+ test('still decodes real entities, including the case-folded XML five', () => {
+ expect(decodeHtmlEntities('& & ≪ é')).toBe('& & < é');
+ });
+});
+
+describe('EPUB metadata entity decoding with Object.prototype names', () => {
+ test('a title with &constructor; keeps it as written', () => {
+ const zip = new AdmZip();
+ zip.addFile('mimetype', Buffer.from('application/epub+zip'));
+ zip.addFile(
+ 'META-INF/container.xml',
+ Buffer.from(
+ ''
+ )
+ );
+ zip.addFile(
+ 'content.opf',
+ Buffer.from(
+ 'The &constructor; & Notes'
+ )
+ );
+ zip.addFile('c1.xhtml', Buffer.from('
x
'));
+
+ const structure = readEpubStructure(zip);
+ expect(structure).not.toBeNull();
+ expect(structure.title).toBe('The &constructor; & Notes');
+ });
+});
diff --git a/test/ipcInvokeTimeout.whisper.test.js b/test/ipcInvokeTimeout.whisper.test.js
new file mode 100644
index 00000000..610d34c8
--- /dev/null
+++ b/test/ipcInvokeTimeout.whisper.test.js
@@ -0,0 +1,31 @@
+/**
+ * @jest-environment node
+ */
+const { IPC_CHANNELS } = require('../src/shared/constants');
+const {
+ getIpcInvokeTimeout,
+ WHISPER_MODEL_INSTALL_INVOKE_TIMEOUT_MS
+} = require('../src/shared/ipcInvokeTimeout');
+
+// The whisper model install answers only after the whole download. The 330 s
+// default cut off slow links: the banner said the install failed while the
+// download carried on and succeeded. Only its 60 s stall timeout ends it.
+describe('getIpcInvokeTimeout - whisper model install', () => {
+ test('gives the install the longest timer budget', () => {
+ expect(getIpcInvokeTimeout(IPC_CHANNELS.WHISPER.INSTALL_MODEL)).toBe(
+ WHISPER_MODEL_INSTALL_INVOKE_TIMEOUT_MS
+ );
+ expect(WHISPER_MODEL_INSTALL_INVOKE_TIMEOUT_MS).toBe(2 ** 31 - 1);
+ });
+
+ test('outlasts a 148 MB download at 1 Mbit/s', () => {
+ const downloadMs = ((148 * 1024 * 1024 * 8) / 1e6) * 1000;
+ expect(getIpcInvokeTimeout(IPC_CHANNELS.WHISPER.INSTALL_MODEL)).toBeGreaterThan(downloadMs);
+ });
+
+ test('install status probe keeps the default budget', () => {
+ expect(getIpcInvokeTimeout(IPC_CHANNELS.WHISPER.GET_INSTALL_STATUS)).toBe(
+ getIpcInvokeTimeout('some:unknown-channel')
+ );
+ });
+});
diff --git a/test/ipcRegistry.test.js b/test/ipcRegistry.test.js
index 98c04cf5..15887d4b 100644
--- a/test/ipcRegistry.test.js
+++ b/test/ipcRegistry.test.js
@@ -463,6 +463,23 @@ describe('ipcRegistry', () => {
ipcRegistry.setShuttingDown(false);
});
+ test('system:log still reaches its handler during shutdown', async () => {
+ // lifecycle keeps system:log registered past IPC cleanup for late
+ // renderer logs; the gate must not reject it as APP_SHUTTING_DOWN.
+ const handler = jest.fn().mockResolvedValue({ success: true });
+ ipcRegistry.registerHandler(mockIpcMain, 'system:log', handler);
+ const wrappedHandler = mockIpcMain.handle.mock.calls[0][1];
+
+ ipcRegistry.setShuttingDown(true);
+ try {
+ const result = await wrappedHandler({ sender: {} }, { level: 'info', message: 'late' });
+ expect(handler).toHaveBeenCalledTimes(1);
+ expect(result).toEqual({ success: true });
+ } finally {
+ ipcRegistry.setShuttingDown(false);
+ }
+ });
+
test('wrapped handler calls original handler when not shutting down', async () => {
const handler = jest.fn().mockResolvedValue({ success: true, data: 'test' });
ipcRegistry.registerHandler(mockIpcMain, 'normal-channel', handler);
diff --git a/test/ipcSanitizer.settingsProse.test.js b/test/ipcSanitizer.settingsProse.test.js
new file mode 100644
index 00000000..15f1ebd1
--- /dev/null
+++ b/test/ipcSanitizer.settingsProse.test.js
@@ -0,0 +1,74 @@
+/**
+ * @jest-environment node
+ */
+const { createIpcSanitizer } = require('../src/preload/ipcSanitizer');
+
+// Settings prose and exclusion globs are not paths. The path heuristic used to
+// blank them on Windows when they held a `\` plus `?`, `*` or `..`, which
+// erased guidance, dropped a custom persona in main, and made every settings
+// save fail once a backslash glob was added (schema requires min length 1).
+describe('ipcSanitizer - settings prose and exclusion globs', () => {
+ const realPlatform = Object.getOwnPropertyDescriptor(process, 'platform');
+
+ beforeEach(() => {
+ Object.defineProperty(process, 'platform', { ...realPlatform, value: 'win32' });
+ });
+
+ afterEach(() => {
+ Object.defineProperty(process, 'platform', realPlatform);
+ });
+
+ const make = () => {
+ const log = { warn: jest.fn() };
+ return { log, ...createIpcSanitizer({ log }) };
+ };
+
+ test('keeps guidance text that mentions a Windows path with ? and *', () => {
+ const { sanitizeArguments, log } = make();
+ const settings = {
+ organizationCustomGuidance: 'Put tax PDFs in D:\\Finance\\Taxes. Should W-2s go there too?',
+ chatPersonaCustomGuidance: 'Search D:\\Docs first; ignore *.tmp and ..\\old',
+ customChatPersonas: [
+ {
+ id: 'custom:docs',
+ label: 'D:\\Docs helper?',
+ guidance: 'Search D:\\Docs first; ignore *.tmp',
+ description: 'Looks in D:\\Docs?'
+ }
+ ]
+ };
+
+ const [out] = sanitizeArguments([settings]);
+
+ expect(out).toEqual(settings);
+ expect(log.warn).not.toHaveBeenCalled();
+ });
+
+ test('keeps backslash exclusion globs in settings and triage payloads', () => {
+ const { sanitizeArguments } = make();
+ const globs = ['*.iso', '**\\archived\\**', 'C:\\Users\\a-user\\Downloads\\*.iso'];
+
+ const [settings] = sanitizeArguments([{ downloadsTriageExclusions: globs }]);
+ const [triage] = sanitizeArguments([{ exclusionGlobs: globs }]);
+
+ expect(settings.downloadsTriageExclusions).toEqual(globs);
+ expect(triage.exclusionGlobs).toEqual(globs);
+ });
+
+ test('other keys keep the path checks', () => {
+ const { sanitizeArguments } = make();
+ const [out] = sanitizeArguments([
+ { defaultSmartFolderLocation: 'D:\\a\\..\\b', lastBrowsedPath: 'D:\\a?\\b' }
+ ]);
+ expect(out.defaultSmartFolderLocation).toBe('');
+ expect(out.lastBrowsedPath).toBe('');
+ });
+
+ test('free-text keys still strip script elements and control characters', () => {
+ const { sanitizeArguments } = make();
+ const [out] = sanitizeArguments([
+ { organizationCustomGuidance: 'a\u0007b D:\\X?' }
+ ]);
+ expect(out.organizationCustomGuidance).toBe('ab D:\\X?');
+ });
+});
diff --git a/test/ipcSanitizer.test.js b/test/ipcSanitizer.test.js
index 6c550848..236282cf 100644
--- a/test/ipcSanitizer.test.js
+++ b/test/ipcSanitizer.test.js
@@ -104,6 +104,24 @@ describe('ipcSanitizer', () => {
expect(sanitized.query).toBe('What is in D:\\Docs?');
});
+ test.each([
+ ['a closing tag with a space', 'Hi there', 'Hi there'],
+ ['a closing tag with junk', 'Hi there', 'Hi there'],
+ [
+ 'a tag rebuilt by stripping another',
+ 'Hi ipt>alert(1)!',
+ 'Hi !'
+ ],
+ ['an iframe with a spaced closing tag', 'ab', 'ab'],
+ ['an unclosed style', 'a
After
';
+ const out = runTextExtraction({ type: 'html', payload: { text: html } });
+ expect(out).toBe('Before After');
+ });
+
+ test('a script end tag needs a word boundary, so does not end it', () => {
+ const html = '
A
B
';
+ const out = runTextExtraction({ type: 'html', payload: { text: html } });
+ expect(out).toBe('A B');
+ });
+
test('returns input verbatim on catastrophic HTML (falls through try/catch)', () => {
// The worker's try/catch guarantees we always return a string even if
// the input would otherwise blow up downstream regex engines.