From 5312c58d7541cc15d6f84d51fc004c9202659dc4 Mon Sep 17 00:00:00 2001 From: Levy Tate <78818969+iLevyTate@users.noreply.github.com> Date: Sat, 14 Nov 2026 13:47:41 -0500 Subject: [PATCH 1/6] test: use a neutral placeholder user instead of a tester's name Test comments now describe the reported problem without naming the person who reported it, and example paths use /Users/alex/ and C:\Users\Alex\. No assertion changes. --- ...onSuggestionServiceCore.labelScore.test.js | 2 +- test/canonicalPath.folderKeys.test.js | 20 +++++----- .../AnalysisResultsList.searchLabel.test.js | 2 +- .../CompletePhase.everyFile.test.js | 20 +++++----- .../McpServerSection.plainWords.test.js | 2 +- .../ReadyFileItem.learningNote.test.js | 2 +- .../destinationPolicy.smartFolderRoot.test.js | 18 ++++----- test/fileOperationTracker.test.js | 10 ++--- ...learning.correctionSurvivesRestart.test.js | 2 +- test/learning.llmModeCorrection.test.js | 4 +- test/learningFeedback.catchAll.test.js | 14 +++---- ...persistenceMiddleware.slimSnapshot.test.js | 12 +++--- test/promptFolders.test.js | 2 +- test/smartFolders.sanitizeFolderPath.test.js | 2 +- test/useOrganization.inPlaceMoves.test.js | 38 +++++++++---------- test/useOrganization.preview.test.js | 26 ++++++------- 16 files changed, 88 insertions(+), 88 deletions(-) diff --git a/test/OrganizationSuggestionServiceCore.labelScore.test.js b/test/OrganizationSuggestionServiceCore.labelScore.test.js index 03d0ebd..db3963d 100644 --- a/test/OrganizationSuggestionServiceCore.labelScore.test.js +++ b/test/OrganizationSuggestionServiceCore.labelScore.test.js @@ -1,5 +1,5 @@ /** - * Nearly every file showed exactly 60% (Hans, retest item 7). The date-based + * Nearly every file showed exactly 60% (retest item 7). The date-based * strategy template scored 0.3 for a date plus 0.3 for the analysis label * and named its folder after that label, so the label reached the ranking at * 0.6 even in embedding mode, where the label is deliberately left out. diff --git a/test/canonicalPath.folderKeys.test.js b/test/canonicalPath.folderKeys.test.js index f9d0e67..63bfccc 100644 --- a/test/canonicalPath.folderKeys.test.js +++ b/test/canonicalPath.folderKeys.test.js @@ -8,10 +8,10 @@ import { toFolderKey, toParentFolderKey } from '../src/renderer/utils/canonicalP describe('toFolderKey', () => { test('one Windows folder has one key however it is spelled', () => { - const key = toFolderKey('C:\\Users\\Hans\\Strato Input'); - expect(key).toBe('c:/users/hans/strato input'); - expect(toFolderKey('c:/users/hans/strato input/')).toBe(key); - expect(toFolderKey('C:\\Users\\Hans\\\\Strato Input\\')).toBe(key); + const key = toFolderKey('C:\\Users\\Alex\\Strato Input'); + expect(key).toBe('c:/users/alex/strato input'); + expect(toFolderKey('c:/users/alex/strato input/')).toBe(key); + expect(toFolderKey('C:\\Users\\Alex\\\\Strato Input\\')).toBe(key); }); test('a POSIX folder keeps its case and loses a trailing slash', () => { @@ -22,8 +22,8 @@ describe('toFolderKey', () => { }); test('a name macOS lists decomposed matches the composed spelling', () => { - const composed = '/Users/hans/Caf\u00e9'; - const decomposed = '/Users/hans/Cafe\u0301'; + const composed = '/Users/alex/Caf\u00e9'; + const decomposed = '/Users/alex/Cafe\u0301'; expect(decomposed).not.toBe(composed); expect(toFolderKey(decomposed)).toBe(toFolderKey(composed)); }); @@ -42,8 +42,8 @@ describe('toFolderKey', () => { describe('toParentFolderKey', () => { test('is the key of the folder that holds the file', () => { - expect(toParentFolderKey('C:\\Users\\Hans\\Strato Input\\report.csv')).toBe( - toFolderKey('C:\\Users\\Hans\\Strato Input') + expect(toParentFolderKey('C:\\Users\\Alex\\Strato Input\\report.csv')).toBe( + toFolderKey('C:\\Users\\Alex\\Strato Input') ); expect(toParentFolderKey('/Volumes/SSD/Strato Input/report.csv')).toBe( toFolderKey('/Volumes/SSD/Strato Input/') @@ -66,8 +66,8 @@ describe('toParentFolderKey', () => { }); test('a decomposed folder name matches the composed folder', () => { - expect(toParentFolderKey('/Users/hans/Cafe\u0301/menu.pdf')).toBe( - toFolderKey('/Users/hans/Caf\u00e9') + expect(toParentFolderKey('/Users/alex/Cafe\u0301/menu.pdf')).toBe( + toFolderKey('/Users/alex/Caf\u00e9') ); }); diff --git a/test/components/AnalysisResultsList.searchLabel.test.js b/test/components/AnalysisResultsList.searchLabel.test.js index 7452f64..71bdad2 100644 --- a/test/components/AnalysisResultsList.searchLabel.test.js +++ b/test/components/AnalysisResultsList.searchLabel.test.js @@ -64,7 +64,7 @@ jest.mock('lucide-react', () => ({ import AnalysisResultsList from '../../src/renderer/components/discover/AnalysisResultsList'; -// Hans could not tell what "Embed: Local" on every Discover card meant. The +// A tester could not tell what "Embed: Local" on every Discover card meant. The // card now says how search can find the file, in plain words; the // hover title keeps the full setting name. describe('AnalysisResultsList search label', () => { diff --git a/test/components/CompletePhase.everyFile.test.js b/test/components/CompletePhase.everyFile.test.js index 34d936b..12e5c06 100644 --- a/test/components/CompletePhase.everyFile.test.js +++ b/test/components/CompletePhase.everyFile.test.js @@ -75,9 +75,9 @@ jest.mock('../../src/renderer/services/ipc', () => ({ import CompletePhase from '../../src/renderer/phases/CompletePhase'; const organized = (i, folder) => ({ - originalPath: `C:\\Users\\Hans\\Downloads\\export-${i}.xlsx`, + originalPath: `C:\\Users\\Alex\\Downloads\\export-${i}.xlsx`, originalName: `export-${i}.xlsx`, - path: `C:\\Users\\Hans\\SEO\\${folder}\\export-${i}.xlsx`, + path: `C:\\Users\\Alex\\SEO\\${folder}\\export-${i}.xlsx`, smartFolder: folder }); @@ -97,22 +97,22 @@ describe('Complete screen: every file of the session', () => { } expect(screen.queryByText(/^\+\d+ more files?$/)).not.toBeInTheDocument(); expect( - screen.getByText('Now at C:\\Users\\Hans\\SEO\\Bing\\export-19.xlsx') + screen.getByText('Now at C:\\Users\\Alex\\SEO\\Bing\\export-19.xlsx') ).toBeInTheDocument(); - expect(screen.getAllByText('From C:\\Users\\Hans\\Downloads')).toHaveLength(20); + expect(screen.getAllByText('From C:\\Users\\Alex\\Downloads')).toHaveLength(20); }); test('says how many files went to each folder, and opens one', async () => { render(); const where = screen.getByRole('region', { name: 'Where files went' }); - expect(within(where).getByText('C:\\Users\\Hans\\SEO\\Search Console')).toBeInTheDocument(); + expect(within(where).getByText('C:\\Users\\Alex\\SEO\\Search Console')).toBeInTheDocument(); expect(within(where).getByText('15 files')).toBeInTheDocument(); expect(within(where).getByText('5 files')).toBeInTheDocument(); await act(async () => { fireEvent.click(within(where).getByRole('button', { name: 'Open Bing' })); }); - expect(mockOpenFolder).toHaveBeenCalledWith('C:\\Users\\Hans\\SEO\\Bing'); + expect(mockOpenFolder).toHaveBeenCalledWith('C:\\Users\\Alex\\SEO\\Bing'); }); test('every row can be shown in its folder', () => { @@ -121,13 +121,13 @@ describe('Complete screen: every file of the session', () => { const reveal = screen.getAllByRole('button', { name: /^Show export-\d+\.xlsx in its folder$/ }); expect(reveal).toHaveLength(20); fireEvent.click(reveal[19]); - expect(mockRevealFile).toHaveBeenCalledWith('C:\\Users\\Hans\\SEO\\Bing\\export-19.xlsx'); + expect(mockRevealFile).toHaveBeenCalledWith('C:\\Users\\Alex\\SEO\\Bing\\export-19.xlsx'); }); test('Save list as CSV sends every file and says where the list went', async () => { mockExport.mockResolvedValue({ success: true, - filePath: 'C:\\Users\\Hans\\Documents\\organize.csv', + filePath: 'C:\\Users\\Alex\\Documents\\organize.csv', rowCount: 20 }); render(); @@ -140,8 +140,8 @@ describe('Complete screen: every file of the session', () => { expect(sent[0]).toEqual( expect.objectContaining({ name: 'export-0.xlsx', - originalPath: 'C:\\Users\\Hans\\Downloads\\export-0.xlsx', - finalPath: 'C:\\Users\\Hans\\SEO\\Search Console\\export-0.xlsx', + originalPath: 'C:\\Users\\Alex\\Downloads\\export-0.xlsx', + finalPath: 'C:\\Users\\Alex\\SEO\\Search Console\\export-0.xlsx', outcome: 'moved' }) ); diff --git a/test/components/McpServerSection.plainWords.test.js b/test/components/McpServerSection.plainWords.test.js index 63ee534..db224ec 100644 --- a/test/components/McpServerSection.plainWords.test.js +++ b/test/components/McpServerSection.plainWords.test.js @@ -74,7 +74,7 @@ const renderSection = (preloaded) => { ); }; -describe('McpServerSection plain words (Hans retest)', () => { +describe('McpServerSection plain words (tester retest)', () => { test('says the server starts with StratoSort while the box is ticked', () => { renderSection({ enabled: false, status: 'stopped', port: null }); expect( diff --git a/test/components/ReadyFileItem.learningNote.test.js b/test/components/ReadyFileItem.learningNote.test.js index 372e17e..eff7d15 100644 --- a/test/components/ReadyFileItem.learningNote.test.js +++ b/test/components/ReadyFileItem.learningNote.test.js @@ -1,7 +1,7 @@ /** * @jest-environment jsdom * - * Hans could not tell whether changing a folder teaches StratoSort anything, + * A tester could not tell whether changing a folder teaches StratoSort anything, * and every card showed the same 60%. A user's change says what it teaches; * a score is shown only when it measures how well the folder matches. */ diff --git a/test/destinationPolicy.smartFolderRoot.test.js b/test/destinationPolicy.smartFolderRoot.test.js index c9f22af..32c18e2 100644 --- a/test/destinationPolicy.smartFolderRoot.test.js +++ b/test/destinationPolicy.smartFolderRoot.test.js @@ -159,22 +159,22 @@ describe('user-chosen locations with accented names', () => { }); test('on macOS the composed match also ignores case', () => { - rememberUserChosenLocation('/Users/hans/Vertra\u0308ge', 'darwin'); - expect(isUserChosenLocation('/users/hans/VERTR\u00c4GE', 'darwin')).toBe(true); + rememberUserChosenLocation('/Users/alex/Vertra\u0308ge', 'darwin'); + expect(isUserChosenLocation('/users/alex/VERTR\u00c4GE', 'darwin')).toBe(true); }); // NTFS keeps decomposed and composed spellings as two different folders, // so approving one must not approve the other. test('on Windows only case is ignored, not accent encoding', () => { - rememberUserChosenLocation('C:\\Users\\hans\\Vertra\u0308ge', 'win32'); - expect(isUserChosenLocation('c:\\users\\hans\\VERTRA\u0308GE', 'win32')).toBe(true); - expect(isUserChosenLocation('C:\\Users\\hans\\Vertr\u00e4ge', 'win32')).toBe(false); + rememberUserChosenLocation('C:\\Users\\alex\\Vertra\u0308ge', 'win32'); + expect(isUserChosenLocation('c:\\users\\alex\\VERTRA\u0308GE', 'win32')).toBe(true); + expect(isUserChosenLocation('C:\\Users\\alex\\Vertr\u00e4ge', 'win32')).toBe(false); }); test('on Linux neither case nor accent encoding is folded', () => { - rememberUserChosenLocation('/home/hans/Vertra\u0308ge', 'linux'); - expect(isUserChosenLocation('/home/hans/Vertra\u0308ge', 'linux')).toBe(true); - expect(isUserChosenLocation('/home/hans/Vertr\u00e4ge', 'linux')).toBe(false); - expect(isUserChosenLocation('/home/hans/vertra\u0308ge', 'linux')).toBe(false); + rememberUserChosenLocation('/home/alex/Vertra\u0308ge', 'linux'); + expect(isUserChosenLocation('/home/alex/Vertra\u0308ge', 'linux')).toBe(true); + expect(isUserChosenLocation('/home/alex/Vertr\u00e4ge', 'linux')).toBe(false); + expect(isUserChosenLocation('/home/alex/vertra\u0308ge', 'linux')).toBe(false); }); }); diff --git a/test/fileOperationTracker.test.js b/test/fileOperationTracker.test.js index 068a92a..6cb348b 100644 --- a/test/fileOperationTracker.test.js +++ b/test/fileOperationTracker.test.js @@ -121,8 +121,8 @@ describe('FileOperationTracker accent spellings on macOS', () => { const tracker = new FileOperationTracker({ cooldownMs: 60000 }); // The organizer records the composed name; the watcher sees decomposed. - tracker.recordOperation('/Users/hans/Vertr\u00e4ge/M\u00e4rz.pdf', 'move', 'organize'); - expect(tracker.wasRecentlyOperated('/Users/hans/Vertra\u0308ge/Ma\u0308rz.pdf')).toBe(true); + tracker.recordOperation('/Users/alex/Vertr\u00e4ge/M\u00e4rz.pdf', 'move', 'organize'); + expect(tracker.wasRecentlyOperated('/Users/alex/Vertra\u0308ge/Ma\u0308rz.pdf')).toBe(true); tracker.shutdown?.(); }); }); @@ -139,9 +139,9 @@ describe('FileOperationTracker accent spellings on Windows', () => { Object.defineProperty(process, 'platform', { value: 'win32' }); const tracker = new FileOperationTracker({ cooldownMs: 60000 }); - tracker.recordOperation('/Users/hans/Vertr\u00e4ge/M\u00e4rz.pdf', 'move', 'organize'); - expect(tracker.wasRecentlyOperated('/Users/hans/Vertra\u0308ge/Ma\u0308rz.pdf')).toBe(false); - expect(tracker.wasRecentlyOperated('/users/hans/VERTR\u00c4GE/m\u00e4rz.pdf')).toBe(true); + tracker.recordOperation('/Users/alex/Vertr\u00e4ge/M\u00e4rz.pdf', 'move', 'organize'); + expect(tracker.wasRecentlyOperated('/Users/alex/Vertra\u0308ge/Ma\u0308rz.pdf')).toBe(false); + expect(tracker.wasRecentlyOperated('/users/alex/VERTR\u00c4GE/m\u00e4rz.pdf')).toBe(true); tracker.shutdown?.(); }); }); diff --git a/test/learning.correctionSurvivesRestart.test.js b/test/learning.correctionSurvivesRestart.test.js index c8a4708..6ca71cb 100644 --- a/test/learning.correctionSurvivesRestart.test.js +++ b/test/learning.correctionSurvivesRestart.test.js @@ -3,7 +3,7 @@ */ /** * "If I correct it, does it learn, or will it make the same mistakes next - * time?" (Hans, retest item 16). + * time?" (retest item 16). * * Runs the real learning path against a temp userData dir: corrections are * recorded through LearningFeedbackService, the suggestion service shuts down diff --git a/test/learning.llmModeCorrection.test.js b/test/learning.llmModeCorrection.test.js index d18f316..16ef8e9 100644 --- a/test/learning.llmModeCorrection.test.js +++ b/test/learning.llmModeCorrection.test.js @@ -2,8 +2,8 @@ * @jest-environment node */ /** - * "If I correct it, does it learn?" in LLM-only and Hybrid routing (Hans, - * retest item 16). + * "If I correct it, does it learn?" in LLM-only and Hybrid routing (retest + * item 16). * * In those modes the analysis label that names a folder is lifted to at least * 0.95 and weighted x1.5, and the correction penalty needs embeddings, so no diff --git a/test/learningFeedback.catchAll.test.js b/test/learningFeedback.catchAll.test.js index 17cb241..970b922 100644 --- a/test/learningFeedback.catchAll.test.js +++ b/test/learningFeedback.catchAll.test.js @@ -1,8 +1,8 @@ /** * A file sitting in the catch-all folder ("Uncategorized", or whatever the - * user renamed it to) means "fit nowhere", not "belongs here". Hans pointed - * the catch-all at his input folder; every unsorted file there taught the app - * to suggest his input folder. Only a user's own move into it is learned. + * user renamed it to) means "fit nowhere", not "belongs here". A tester + * pointed the catch-all at their input folder; every unsorted file there taught + * the app to suggest that input folder. Only a user's own move into it is learned. */ jest.mock('../src/main/services/ServiceContainer', () => ({ @@ -18,26 +18,26 @@ const { const CATCH_ALL = { id: 'default-uncategorized-1', name: 'Strato test Data', - path: '/Users/hans/Strato test Data', + path: '/Users/alex/Strato test Data', category: 'uncategorized', isDefault: true }; const PLAIN_UNCATEGORIZED = { id: 'u2', name: 'Uncategorized', - path: '/Users/hans/Uncategorized' + path: '/Users/alex/Uncategorized' }; const GSC = { id: 'gsc', name: 'GSC', - path: '/Users/hans/GSC', + path: '/Users/alex/GSC', category: 'general' }; // A seeded default folder that is not the catch-all. const ARCHIVES = { id: 'default-archives-1', name: 'Archives', - path: '/Users/hans/Archives', + path: '/Users/alex/Archives', category: 'archives', isDefault: true }; diff --git a/test/persistenceMiddleware.slimSnapshot.test.js b/test/persistenceMiddleware.slimSnapshot.test.js index 6d9284e..006f753 100644 --- a/test/persistenceMiddleware.slimSnapshot.test.js +++ b/test/persistenceMiddleware.slimSnapshot.test.js @@ -1,7 +1,7 @@ /** * What the saved session costs per file, and how many files it keeps. * - * Hans queued 275 Search Console and SEO-tool exports. Each analysis result in + * A tester queued 275 Search Console and SEO-tool exports. Each analysis result in * the renderer carries the file's full extracted text (up to ~64,000 * characters, see analysisTextUtils.getMaxChunkableTextLength), so 200 of * them were far over the 4 MB save budget: the save fell back to 100, then @@ -30,7 +30,7 @@ function realisticResult(i) { const name = `https___www.example-shop.com_-Performance-on-Search-2026-10-${i}.xlsx`; return { name, - path: `/Users/hans/Downloads/GSC exports/${name}`, + path: `/Users/alex/Downloads/GSC exports/${name}`, extension: '.xlsx', size: 48213 + i, isDirectory: false, @@ -80,8 +80,8 @@ function selectedFile(i) { function organizedEntry(i) { return { - originalPath: `/Users/hans/Downloads/GSC exports/file-${i}.xlsx`, - path: `/Users/hans/Documents/SEO Reports/search-console-performance-2026-10-${i}.xlsx`, + originalPath: `/Users/alex/Downloads/GSC exports/file-${i}.xlsx`, + path: `/Users/alex/Documents/SEO Reports/search-console-performance-2026-10-${i}.xlsx`, originalName: `file-${i}.xlsx`, newName: `search-console-performance-2026-10-${i}.xlsx`, smartFolder: 'SEO Reports', @@ -103,7 +103,7 @@ function stateWith({ files = 0, organized = 0 } = {}) { selectedFiles: Array.from({ length: files }, (_, i) => selectedFile(i)), organizedFiles: Array.from({ length: organized }, (_, i) => organizedEntry(i)), organizedPathIndex: [], - smartFolders: [{ id: '1', name: 'SEO Reports', path: '/Users/hans/Documents/SEO Reports' }], + smartFolders: [{ id: '1', name: 'SEO Reports', path: '/Users/alex/Documents/SEO Reports' }], namingConvention: null, lastOrganizeRun: null, fileStates: {} @@ -207,7 +207,7 @@ describe('persisted session size', () => { expect(buildStateSnapshot(state).analysis.results).toEqual(state.analysis.results); }); - test("Hans' 275-file batch is saved whole, within the budget", () => { + test('a 275-file batch is saved whole, within the budget', () => { const snapshot = buildStateSnapshot(stateWith({ files: 275, organized: 275 })); expect(snapshot.files.selectedFiles).toHaveLength(275); diff --git a/test/promptFolders.test.js b/test/promptFolders.test.js index 011a5ba..e5dacd3 100644 --- a/test/promptFolders.test.js +++ b/test/promptFolders.test.js @@ -2,7 +2,7 @@ * @jest-environment node * * selectPromptFolders decides which Smart Folders the analysis prompt lists. - * Hans added his own folders after the 8 defaults; a plain slice(0, 10) left + * A tester added their own folders after the 8 defaults; a plain slice(0, 10) left * them out of the prompt, so the AI never saw them. */ diff --git a/test/smartFolders.sanitizeFolderPath.test.js b/test/smartFolders.sanitizeFolderPath.test.js index 838a52d..633bd9d 100644 --- a/test/smartFolders.sanitizeFolderPath.test.js +++ b/test/smartFolders.sanitizeFolderPath.test.js @@ -75,7 +75,7 @@ describe('sanitizeFolderPath', () => { } ); - posixOnly.each(['/Volumes/Samsung T7/Sorted', '/media/hans/SSD/Sorted', '/mnt/data/Sorted'])( + posixOnly.each(['/Volumes/Samsung T7/Sorted', '/media/alex/SSD/Sorted', '/mnt/data/Sorted'])( 'a folder on a mounted volume: %s', async (input) => { await expect(sanitizeFolderPath(input)).resolves.toBe(input); diff --git a/test/useOrganization.inPlaceMoves.test.js b/test/useOrganization.inPlaceMoves.test.js index fdf0398..e2acb81 100644 --- a/test/useOrganization.inPlaceMoves.test.js +++ b/test/useOrganization.inPlaceMoves.test.js @@ -36,8 +36,8 @@ const { } = require('../src/renderer/phases/organize/useOrganization'); const { toCanonicalPath } = require('../src/renderer/utils/canonicalPath'); -const INPUT = { id: 'in', name: 'Strato Input', path: '/Users/hans/Strato Input' }; -const BING = { id: 'bing', name: 'Bing data', path: '/Users/hans/Sorted/Bing data' }; +const INPUT = { id: 'in', name: 'Strato Input', path: '/Users/alex/Strato Input' }; +const BING = { id: 'bing', name: 'Bing data', path: '/Users/alex/Sorted/Bing data' }; const file = (path, category, suggestedName) => { const name = path.split(/[\\/]/).pop(); @@ -55,7 +55,7 @@ function plan(files, { smartFolders = [INPUT, BING], editingFiles = {}, ...rest smartFolders.find((folder) => folder.name.toLowerCase() === String(label).toLowerCase()) || null ), - defaultLocation: '/Users/hans/Documents', + defaultLocation: '/Users/alex/Documents', smartFolders, ...rest }; @@ -68,8 +68,8 @@ describe('findInPlaceMoves', () => { }); test('lists a file sent to the folder it is in, and says whether it gets a new name', () => { - const renamed = file('/Users/hans/Strato Input/a.csv', 'Strato Input', 'Keywords 2025.csv'); - const untouched = file('/Users/hans/Strato Input/b.csv', 'Strato Input'); + const renamed = file('/Users/alex/Strato Input/a.csv', 'Strato Input', 'Keywords 2025.csv'); + const untouched = file('/Users/alex/Strato Input/b.csv', 'Strato Input'); expect(findInPlaceMoves(plan([renamed, untouched]))).toEqual([ { sourcePath: renamed.path, fileName: 'a.csv', folderName: 'Strato Input', renamed: true }, @@ -78,12 +78,12 @@ describe('findInPlaceMoves', () => { }); test('leaves out a file that is sent to another folder', () => { - const leaving = file('/Users/hans/Strato Input/bing.csv', 'Bing data'); + const leaving = file('/Users/alex/Strato Input/bing.csv', 'Bing data'); expect(findInPlaceMoves(plan([leaving]))).toEqual([]); }); test('a file drops out once the user picks another folder on its card', () => { - const picked = file('/Users/hans/Strato Input/a.csv', 'Strato Input'); + const picked = file('/Users/alex/Strato Input/a.csv', 'Strato Input'); const editingFiles = { [toCanonicalPath(picked.path)]: { category: 'Bing data' } }; expect(findInPlaceMoves(plan([picked]))).toHaveLength(1); @@ -91,12 +91,12 @@ describe('findInPlaceMoves', () => { }); test('a file in a subfolder of a smart folder is moved, so it is not listed', () => { - const nested = file('/Users/hans/Strato Input/2025/a.csv', 'Strato Input'); + const nested = file('/Users/alex/Strato Input/2025/a.csv', 'Strato Input'); expect(findInPlaceMoves(plan([nested]))).toEqual([]); }); test('does not work out a destination for files outside every smart folder', () => { - const inputs = plan([file('/Users/hans/Downloads/a.csv', 'Strato Input')]); + const inputs = plan([file('/Users/alex/Downloads/a.csv', 'Strato Input')]); expect(findInPlaceMoves(inputs)).toEqual([]); expect(inputs.getFileWithEdits).not.toHaveBeenCalled(); @@ -105,7 +105,7 @@ describe('findInPlaceMoves', () => { test('a smart folder without a path lives under the default location', () => { const reports = { id: 'r', name: 'Reports' }; - const filed = file('/Users/hans/Documents/Reports/q3.pdf', 'Reports'); + const filed = file('/Users/alex/Documents/Reports/q3.pdf', 'Reports'); expect(findInPlaceMoves(plan([filed], { smartFolders: [reports] }))).toEqual([ { sourcePath: filed.path, fileName: 'q3.pdf', folderName: 'Reports', renamed: false } @@ -113,7 +113,7 @@ describe('findInPlaceMoves', () => { }); test('a file already in Uncategorized that matches no folder stays there', () => { - const stray = file('/Users/hans/Documents/Uncategorized/notes.txt', 'Recipes'); + const stray = file('/Users/alex/Documents/Uncategorized/notes.txt', 'Recipes'); expect(findInPlaceMoves(plan([stray]))).toEqual([ { sourcePath: stray.path, fileName: 'notes.txt', folderName: 'Uncategorized', renamed: false } @@ -121,12 +121,12 @@ describe('findInPlaceMoves', () => { }); test('Windows spellings of one folder match', () => { - const smartFolders = [{ id: 'in', name: 'Strato Input', path: 'c:/users/hans/strato input/' }]; - const filed = file('C:\\Users\\Hans\\Strato Input\\a.csv', 'Strato Input'); + const smartFolders = [{ id: 'in', name: 'Strato Input', path: 'c:/users/alex/strato input/' }]; + const filed = file('C:\\Users\\Alex\\Strato Input\\a.csv', 'Strato Input'); expect( findInPlaceMoves( - plan([filed], { smartFolders, defaultLocation: 'C:\\Users\\Hans\\Documents' }) + plan([filed], { smartFolders, defaultLocation: 'C:\\Users\\Alex\\Documents' }) ) ).toEqual([ { sourcePath: filed.path, fileName: 'a.csv', folderName: 'Strato Input', renamed: false } @@ -134,7 +134,7 @@ describe('findInPlaceMoves', () => { }); test('nothing to list without files or a default location', () => { - const filed = file('/Users/hans/Strato Input/a.csv', 'Strato Input'); + const filed = file('/Users/alex/Strato Input/a.csv', 'Strato Input'); expect(findInPlaceMoves(plan(undefined))).toEqual([]); expect(findInPlaceMoves(plan([null, {}, { path: 42 }]))).toEqual([]); @@ -172,9 +172,9 @@ describe('useOrganization: inPlaceMoves', () => { }); test('covers every ready file in the queue, and only ready files', () => { - const ready = file('/Users/hans/Strato Input/a.csv', 'Strato Input'); - const notAnalyzed = { path: '/Users/hans/Strato Input/b.csv', name: 'b.csv' }; - const leaving = file('/Users/hans/Strato Input/bing.csv', 'Bing data'); + const ready = file('/Users/alex/Strato Input/a.csv', 'Strato Input'); + const notAnalyzed = { path: '/Users/alex/Strato Input/b.csv', name: 'b.csv' }; + const leaving = file('/Users/alex/Strato Input/bing.csv', 'Bing data'); const options = hookOptions([ready, notAnalyzed, leaving]); const { result } = renderHook(() => useOrganization(options)); @@ -185,7 +185,7 @@ describe('useOrganization: inPlaceMoves', () => { }); test('is empty when no file stays where it is', () => { - const options = hookOptions([file('/Users/hans/Downloads/a.csv', 'Bing data')]); + const options = hookOptions([file('/Users/alex/Downloads/a.csv', 'Bing data')]); const { result } = renderHook(() => useOrganization(options)); expect(result.current.inPlaceMoves).toEqual([]); diff --git a/test/useOrganization.preview.test.js b/test/useOrganization.preview.test.js index 8a78041..8493a93 100644 --- a/test/useOrganization.preview.test.js +++ b/test/useOrganization.preview.test.js @@ -34,7 +34,7 @@ jest.mock('../src/renderer/components/UndoRedoSystem', () => ({ const { previewBatchOrganize } = require('../src/renderer/components/UndoRedoSystem'); const { useOrganization } = require('../src/renderer/phases/organize/useOrganization'); -const FINANCE = { id: 'fin', name: 'Finance', path: '/Users/hans/Sorted/Finance' }; +const FINANCE = { id: 'fin', name: 'Finance', path: '/Users/alex/Sorted/Finance' }; const file = (path, category, suggestedName) => { const name = path.split(/[\\/]/).pop(); @@ -47,7 +47,7 @@ const hookOptions = (unprocessedFiles) => ({ getFileWithEdits: (f) => f, findSmartFolderForCategory: (label) => String(label).toLowerCase() === FINANCE.name.toLowerCase() ? FINANCE : null, - defaultLocation: '/Users/hans/Documents', + defaultLocation: '/Users/alex/Documents', smartFolders: [FINANCE], analysisResults: [], markFilesAsProcessed: jest.fn(), @@ -83,9 +83,9 @@ describe('useOrganization: handlePreviewOrganize', () => { }); test('sends the operations a Move would send and returns the plan', async () => { - const invoice = file('/Users/hans/Downloads/scan.pdf', 'Finance', 'Invoice March.pdf'); + const invoice = file('/Users/alex/Downloads/scan.pdf', 'Finance', 'Invoice March.pdf'); const moved = [ - { source: invoice.path, destination: '/Users/hans/Sorted/Finance/Invoice March.pdf' } + { source: invoice.path, destination: '/Users/alex/Sorted/Finance/Invoice March.pdf' } ]; previewBatchOrganize.mockResolvedValue(dryRunPlan(moved)); @@ -96,7 +96,7 @@ describe('useOrganization: handlePreviewOrganize', () => { expect.objectContaining({ type: 'move', source: invoice.path, - destination: '/Users/hans/Sorted/Finance/Invoice March.pdf' + destination: '/Users/alex/Sorted/Finance/Invoice March.pdf' }) ]); expect(plan.wouldMove).toEqual(moved); @@ -104,9 +104,9 @@ describe('useOrganization: handlePreviewOrganize', () => { }); test('lists the files this batch sends to one name', async () => { - const first = file('/Users/hans/Downloads/scan 1.pdf', 'Finance', 'Invoice.pdf'); - const second = file('/Users/hans/Downloads/scan 2.pdf', 'Finance', 'Invoice.pdf'); - const other = file('/Users/hans/Downloads/budget.xlsx', 'Finance'); + const first = file('/Users/alex/Downloads/scan 1.pdf', 'Finance', 'Invoice.pdf'); + const second = file('/Users/alex/Downloads/scan 2.pdf', 'Finance', 'Invoice.pdf'); + const other = file('/Users/alex/Downloads/budget.xlsx', 'Finance'); previewBatchOrganize.mockResolvedValue(dryRunPlan([])); const { result } = renderHook(() => useOrganization(hookOptions([first, second, other]))); @@ -114,7 +114,7 @@ describe('useOrganization: handlePreviewOrganize', () => { expect(plan.sameDestination).toEqual([ { - destination: '/Users/hans/Sorted/Finance/Invoice.pdf', + destination: '/Users/alex/Sorted/Finance/Invoice.pdf', files: [ { fileName: 'Invoice.pdf', sourcePath: first.path }, { fileName: 'Invoice.pdf', sourcePath: second.path } @@ -124,8 +124,8 @@ describe('useOrganization: handlePreviewOrganize', () => { }); test('previews only the files it is given', async () => { - const picked = file('/Users/hans/Downloads/a.pdf', 'Finance'); - const left = file('/Users/hans/Downloads/b.pdf', 'Finance'); + const picked = file('/Users/alex/Downloads/a.pdf', 'Finance'); + const left = file('/Users/alex/Downloads/b.pdf', 'Finance'); previewBatchOrganize.mockResolvedValue(dryRunPlan([])); const { result } = renderHook(() => useOrganization(hookOptions([picked, left]))); @@ -142,7 +142,7 @@ describe('useOrganization: handlePreviewOrganize', () => { }); const { result } = renderHook(() => - useOrganization(hookOptions([file('/Users/hans/Downloads/a.pdf', 'Finance')])) + useOrganization(hookOptions([file('/Users/alex/Downloads/a.pdf', 'Finance')])) ); await expect(result.current.handlePreviewOrganize()).rejects.toThrow( @@ -154,7 +154,7 @@ describe('useOrganization: handlePreviewOrganize', () => { previewBatchOrganize.mockRejectedValue(new Error('File operations API not available')); const { result } = renderHook(() => - useOrganization(hookOptions([file('/Users/hans/Downloads/a.pdf', 'Finance')])) + useOrganization(hookOptions([file('/Users/alex/Downloads/a.pdf', 'Finance')])) ); await expect(result.current.handlePreviewOrganize()).rejects.toThrow( From b5fc3e75cf2fcb718203cc94fc4723073f737e1c Mon Sep 17 00:00:00 2001 From: Levy Tate <78818969+iLevyTate@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:13:23 -0500 Subject: [PATCH 2/6] fix(organize): files given the same new name are numbered apart instead of stopping the Move MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two files of one batch that the naming convention gives the same name in the same folder (two exports of one day) made Organize refuse the whole run. The second and later files now get main's numbered name (_1, _2), Preview marks them "Name taken — number added", and a file already at its destination keeps its name. A refused batch (another run in progress, too large) now shows main's reason instead of "Check the logs" and no longer lists every file as interrupted. A card whose folder the user changed no longer shows a confidence score for it. --- src/main/ipc/files/batchOrganizeHandler.js | 26 +- src/main/ipc/validationSchemas.js | 6 +- .../organize/OrganizePreviewModal.jsx | 7 +- .../components/organize/ReadyFileItem.jsx | 4 +- src/renderer/phases/OrganizePhase.jsx | 9 +- .../phases/organize/useOrganization.js | 189 +++++++--- ...tchOrganizeHandler.labelCorrection.test.js | 341 ++++++++++++++++++ test/components/OrganizePhase.test.js | 40 ++ .../ReadyFileItem.learningNote.test.js | 10 + test/components/ReadyFileItem.routing.test.js | 5 +- test/useOrganization.preview.test.js | 101 +++++- test/useOrganization.runFiles.test.js | 93 ++++- test/useOrganization.test.js | 4 +- test/validationSchemas.test.js | 17 + 14 files changed, 778 insertions(+), 74 deletions(-) create mode 100644 test/batchOrganizeHandler.labelCorrection.test.js diff --git a/src/main/ipc/files/batchOrganizeHandler.js b/src/main/ipc/files/batchOrganizeHandler.js index 7815d66..db77488 100644 --- a/src/main/ipc/files/batchOrganizeHandler.js +++ b/src/main/ipc/files/batchOrganizeHandler.js @@ -62,6 +62,8 @@ const { * @property {{ similarFile: string, similarity: number }} [_semanticDuplicate] * @property {{ folder: string, path?: string, source?: string }} [suggestion] - What the * app suggested before the user confirmed; a different landing folder is a correction + * @property {string} [analysisLabel] - The label the analysis gave the file, which a + * correction is recorded under when the history holds no different one */ /** @@ -2322,14 +2324,21 @@ async function recordUndoAndUpdateDatabase( const divergencesByPath = new Map( (coordinatorResult?.divergences || []).map((d) => [d.filePath, d]) ); - // What the app suggested for each file (Organize sends it per op). - // Keyed by where the file landed, like the divergences above. + // What the app suggested for each file, and the label the analysis + // gave it (Organize sends both per op). Keyed by where the file + // landed, like the divergences above. /** @type {Map} */ const suggestionsByNewPath = new Map(); + /** @type {Map} */ + const labelsByNewPath = new Map(); for (const c of Array.isArray(completedOperations) ? completedOperations : []) { - const suggested = batch?.operations?.[c?.index]?.suggestion; - if (typeof c?.destination === 'string' && typeof suggested?.folder === 'string') { - suggestionsByNewPath.set(c.destination, suggested); + if (typeof c?.destination !== 'string') continue; + const op = batch?.operations?.[c?.index]; + if (typeof op?.suggestion?.folder === 'string') { + suggestionsByNewPath.set(c.destination, op.suggestion); + } + if (typeof op?.analysisLabel === 'string' && op.analysisLabel.trim()) { + labelsByNewPath.set(c.destination, op.analysisLabel); } } let learned = 0; @@ -2386,11 +2395,16 @@ async function recordUndoAndUpdateDatabase( !isDefaultCategoryName(wrongFolder) && wrongFolder.toLowerCase() !== String(change.newSmartFolder).toLowerCase() ) { + // The correction is counted under the analysis label + // (findLearnedCorrection). With no divergence the history + // label already named this folder, while the engine ranked + // another first, so the label the op carries is used. const didCorrect = await learningService.recordCorrection({ filePath: change.newPath, wrongFolder, correctFolder: change.newSmartFolder, - oldCategory: divergence?.oldCategory || null + oldCategory: + divergence?.oldCategory || labelsByNewPath.get(change.newPath) || null }); if (didCorrect) corrected++; } diff --git a/src/main/ipc/validationSchemas.js b/src/main/ipc/validationSchemas.js index 4836d62..46a392c 100644 --- a/src/main/ipc/validationSchemas.js +++ b/src/main/ipc/validationSchemas.js @@ -799,7 +799,11 @@ if (!z) { source: fileOpPathSchema, destination: fileOpPathSchema, type: z.string().optional(), - suggestion: organizeSuggestionSchema + suggestion: organizeSuggestionSchema, + // The label the analysis gave the file; a correction is recorded under + // it. Listed for the same reason as `suggestion`. Organize leaves off a + // label longer than this rather than have the whole batch refused. + analysisLabel: z.string().max(255).optional() }); const fileOperationSchema = z diff --git a/src/renderer/components/organize/OrganizePreviewModal.jsx b/src/renderer/components/organize/OrganizePreviewModal.jsx index ad8b1ca..c25f5ad 100644 --- a/src/renderer/components/organize/OrganizePreviewModal.jsx +++ b/src/renderer/components/organize/OrganizePreviewModal.jsx @@ -24,9 +24,10 @@ function splitPath(p) { * Shows the dry-run plan from previewBatchOrganize before anything moves: * every file grouped under the folder it will land in, its new name when the * move renames it, folders that will be created, name clashes the move will - * resolve with a numeric suffix, files that are already in the folder - * chosen for them and so do not change folder, and files this batch sends to - * one name, which the move refuses to start with. + * resolve with a numeric suffix (a name taken on disk, or one another file + * of this batch gets first), files that are already in the folder chosen for + * them and so do not change folder, and files this batch still sends to one + * name after numbering, which the move refuses to start with. */ function OrganizePreviewModal({ isOpen, plan, onClose, onConfirm, redactPaths, isOrganizing }) { const { groups, newFolders, sameNameCount } = useMemo(() => { diff --git a/src/renderer/components/organize/ReadyFileItem.jsx b/src/renderer/components/organize/ReadyFileItem.jsx index 736e8cb..9598d49 100644 --- a/src/renderer/components/organize/ReadyFileItem.jsx +++ b/src/renderer/components/organize/ReadyFileItem.jsx @@ -142,10 +142,12 @@ function ReadyFileItem({ return `StratoSort remembers this after the move. Once a few ${similar} go to ${chosen}, it suggests ${chosen} for them too.`; }, [routing, engine, file?.name]); // A percentage only where it measures how well the folder fits: not the - // label's self-rating behind a name match, not the catch-all fallback. + // label's self-rating behind a name match or the user's own pick (it says + // nothing about the folder they chose), not the catch-all fallback. const showConfidence = computedConfidence !== null && routing?.source !== 'name' && + routing?.source !== 'user' && !(routedByEngine && engine?.source === 'default'); const fileKey = toCanonicalPath(file?.path) || file?.path || ''; const handleToggle = useCallback(() => onToggleSelected(fileKey), [onToggleSelected, fileKey]); diff --git a/src/renderer/phases/OrganizePhase.jsx b/src/renderer/phases/OrganizePhase.jsx index e0cce0f..0f3f08c 100644 --- a/src/renderer/phases/OrganizePhase.jsx +++ b/src/renderer/phases/OrganizePhase.jsx @@ -866,7 +866,14 @@ function OrganizePhase() { > • - {conflict.files.map((f) => f.fileName).join(', ')} + {/* The files' own names, so the user can find the + cards to rename: the new name is the same for + all of them and follows the arrow. */} + + {conflict.files + .map((f) => f.sourcePath?.split(/[\\/]/).pop() || f.fileName) + .join(', ')} + {' → '} {conflict.destination.split(/[\\/]/).pop()} diff --git a/src/renderer/phases/organize/useOrganization.js b/src/renderer/phases/organize/useOrganization.js index 99650ad..5d82888 100644 --- a/src/renderer/phases/organize/useOrganization.js +++ b/src/renderer/phases/organize/useOrganization.js @@ -667,11 +667,87 @@ export function findInPlaceMoves({ files, smartFolders = [], defaultLocation, .. } /** - * Build file operations for organization - * @param {Object} params - Parameters - * @returns {Object} Object with operations array and categoryChanges array + * The Nth numbered form of a destination, in the shape main gives a name + * that is taken (formatNumberedCollisionCandidate in batchOrganizeHandler.js): + * `_N` before the last extension, so report.pdf becomes report_1.pdf. A name + * numbered here is the one the move uses, and the one Preview shows. + * @param {string} destination + * @param {number} counter - 1-based + * @returns {string} + */ +function numberedDestination(destination, counter) { + const nameStart = Math.max(destination.lastIndexOf('/'), destination.lastIndexOf('\\')) + 1; + const dot = destination.lastIndexOf('.'); + // Like path.extname: a leading dot (.env) starts the name, not an extension. + const ext = dot > nameStart ? destination.slice(dot) : ''; + return `${destination.slice(0, destination.length - ext.length)}_${counter}${ext}`; +} + +/** + * Every file's planned move. Files of this batch that would get the same name + * in the same folder (the naming convention gives two exports of one day the + * same name) are numbered apart instead of stopping the whole move: the first + * keeps the name, the others get the next free number. A file already at its + * destination keeps its name, so the run does not rename a file that was + * filed. A number never lands on a name another file of the batch is headed + * for. Names are compared the way the file system does (see + * normalizeForComparison). + * @param {Omit & { filesToProcess: any[] }} params + */ +function planBatchDestinations({ filesToProcess, ...planParams }) { + const planned = filesToProcess.map((/** @type {any} */ file) => ({ + file, + ...processFileForOrganization({ ...planParams, file }), + renumbered: false + })); + const taken = new Set(planned.map((entry) => normalizeForComparison(entry.normalized))); + const claimed = new Set(); + /** @param {(typeof planned)[number]} entry */ + const isInPlace = (entry) => + normalizeForComparison(entry.file?.path) === normalizeForComparison(entry.normalized); + for (const entry of [...planned.filter(isInPlace), ...planned.filter((e) => !isInPlace(e))]) { + const key = normalizeForComparison(entry.normalized); + if (!claimed.has(key)) { + claimed.add(key); + continue; + } + // `taken` holds every name the batch is headed for, so a numbered name is + // never one another file keeps or claims later. + let counter = 1; + while (taken.has(normalizeForComparison(numberedDestination(entry.normalized, counter)))) { + counter += 1; + } + const numbered = numberedDestination(entry.normalized, counter); + taken.add(normalizeForComparison(numbered)); + entry.normalized = numbered; + entry.newName = numbered.split(/[\\/]/).pop() || entry.newName; + entry.renumbered = true; + } + return planned; +} + +/** + * The label the analysis gave a file, sent with its move so main can record + * a correction under it when the history has no different label to offer. + * A folder change on the card is written to `analysis.category` too, so after + * one this is the user's choice; main prefers the history's label whenever + * the two differ. Over 255 characters it is left off: the IPC schema would + * refuse the whole batch. + * @param {any} file + * @returns {string | undefined} + */ +function analysisLabelOf(file) { + const label = file?.analysis?.category; + return typeof label === 'string' && label.trim() && label.length <= 255 ? label : undefined; +} + +/** + * Build file operations for organization: the operations, the category + * changes to report, and the source paths of the files numbered apart from + * another file of the batch. + * @param {any} params + * @returns {{ operations: any[], categoryChanges: any[], renumberedSources: Set }} */ -/** @param {any} params */ function buildOperations({ filesToProcess, unprocessedFiles: _unprocessedFiles, @@ -685,18 +761,20 @@ function buildOperations({ }) { /** @type {any[]} */ const categoryChanges = []; - const operations = filesToProcess.map((/** @type {any} */ file) => { - const { normalized, categoryChanged, originalCategory, finalCategory, suggestion } = - processFileForOrganization({ - file, - editingFiles, - getFileWithEdits, - findSmartFolderForCategory, - findSmartFolderForFile, - defaultLocation, - smartFolders, - suggestionsByPath - }); + const planned = planBatchDestinations({ + filesToProcess, + editingFiles, + getFileWithEdits, + findSmartFolderForCategory, + findSmartFolderForFile, + defaultLocation, + smartFolders, + suggestionsByPath + }); + const operations = planned.map((entry) => { + const { file, normalized, categoryChanged, originalCategory, finalCategory, suggestion } = + entry; + const analysisLabel = analysisLabelOf(file); if (categoryChanged) { categoryChanges.push({ @@ -710,11 +788,15 @@ function buildOperations({ type: 'move', source: file.path, destination: normalized, - ...(suggestion ? { suggestion } : {}) + ...(suggestion ? { suggestion } : {}), + ...(analysisLabel ? { analysisLabel } : {}) }; }); + const renumberedSources = new Set( + planned.filter((entry) => entry.renumbered).map((entry) => entry.file.path) + ); - return { operations, categoryChanges }; + return { operations, categoryChanges, renumberedSources }; } /** @@ -733,19 +815,23 @@ function buildPreview({ smartFolders = [], suggestionsByPath = null }) { - const preview = filesToProcess.map((/** @type {any} */ file) => { - const { newName, normalized } = processFileForOrganization({ - file, - editingFiles, - getFileWithEdits, - findSmartFolderForCategory, - findSmartFolderForFile, - defaultLocation, - smartFolders, - suggestionsByPath - }); - return { fileName: newName, destination: normalized, sourcePath: file.path }; - }); + // The same plan the move sends, numbered names included, so a conflict + // here is one that numbering could not settle. + const preview = planBatchDestinations({ + filesToProcess, + editingFiles, + getFileWithEdits, + findSmartFolderForCategory, + findSmartFolderForFile, + defaultLocation, + smartFolders, + suggestionsByPath + }).map(({ file, newName, normalized, renumbered }) => ({ + fileName: newName, + destination: normalized, + sourcePath: file.path, + ...(renumbered ? { renumbered: true } : {}) + })); const destinationMap = new Map(); preview.forEach((/** @type {any} */ item) => { @@ -771,7 +857,8 @@ function buildPreview({ // NOTE: External file collision checking requires an async check (e.g. IPC to main process) // which is generally handled during the actual batch processor execution (makeUniqueFileName). - // This sync function only detects *internal* batch conflicts where two files want the *same* new name. + // This sync function only detects *internal* batch conflicts: two files of the batch still + // headed for the *same* name after planBatchDestinations numbered them apart. return { preview, conflicts }; } @@ -971,7 +1058,7 @@ export function useOrganization({ // - file.analysis.category/suggestedName // - any user edits in editingFiles const { operations, categoryChanges } = resumeInfo - ? { operations: resumeInfo.operations, categoryChanges: [] } + ? { operations: resumeInfo.operations, categoryChanges: /** @type {any[]} */ ([]) } : buildOperations({ filesToProcess, unprocessedFiles, @@ -1103,10 +1190,21 @@ export function useOrganization({ } // Every file of the run and what became of it, for "See every - // file", the Complete screen and the CSV export. - const batchError = result?.partialFailure - ? String(result.error || 'The batch stopped early') - : undefined; + // file", the Complete screen and the CSV export. A batch main + // refused outright (another run holds the lock, too many files, + // an error before any file) has an error and no rows: its reason + // is the run's summary and each file's, since none was tried. + const refusedBatch = + result?.success === false && + !result?.rolledBack && + !result?.paused && + !result?.cancelled && + typeof result?.error === 'string' && + result.error.trim() !== ''; + const batchError = + result?.partialFailure || refusedBatch + ? String(result.error || 'The batch stopped early') + : undefined; const runRows = buildRunResultRows({ operations, rows: resArray, batchError }); setLastOrganizeRunFiles(runRows); runFilesStored = true; @@ -1668,8 +1766,9 @@ export function useOrganization({ * before any disk write. * * Returns the main-process plan plus `sameDestination`, the files this - * batch sends to one name (the move refuses to start while any exist), or - * null when no file has a destination to preview. Throws when the request + * batch still sends to one name after numbering (the move refuses to start + * while any exist; numbering leaves none), or null when no file has a + * destination to preview. Throws when the request * fails or is refused, so the caller can say why instead of reporting an * empty preview. Caller decides how to surface (notification, modal, * etc.) — this hook intentionally doesn't push UI side-effects so @@ -1694,7 +1793,7 @@ export function useOrganization({ smartFolders, suggestionsByPath }; - const { operations } = buildOperations(planInputs); + const { operations, renumberedSources } = buildOperations(planInputs); const validOps = operations.filter((/** @type {any} */ op) => op?.source && op?.destination); if (validOps.length === 0) return null; @@ -1704,7 +1803,15 @@ export function useOrganization({ if (!plan || plan.success === false) { throw new Error(plan?.error || 'The preview request was refused'); } - return { ...plan, sameDestination: buildPreview(planInputs).conflicts }; + // Main sees the numbered name as free, so it only marks names taken + // on disk; a file numbered apart from another file of the batch is + // marked here, like one whose name was taken. + const wouldMove = Array.isArray(plan.wouldMove) + ? plan.wouldMove.map((/** @type {any} */ item) => + renumberedSources.has(item?.source) ? { ...item, collision: true } : item + ) + : plan.wouldMove; + return { ...plan, wouldMove, sameDestination: buildPreview(planInputs).conflicts }; } catch (error) { logger.warn('[ORGANIZE] Preview failed', { error: error?.message }); throw error; diff --git a/test/batchOrganizeHandler.labelCorrection.test.js b/test/batchOrganizeHandler.labelCorrection.test.js new file mode 100644 index 0000000..255cce8 --- /dev/null +++ b/test/batchOrganizeHandler.labelCorrection.test.js @@ -0,0 +1,341 @@ +/** + * @jest-environment node + * + * A correction is counted under the label the analysis gave the file + * (findLearnedCorrection). When the label already named the folder the user + * chose but the engine ranked another first, the history records no + * divergence, so the label has to come with the op: without it the + * correction was stored with no label and never counted. + */ +const { handleBatchOrganize } = require('../src/main/ipc/files/batchOrganizeHandler'); + +// Mock all dependencies +jest.mock('fs', () => ({ + promises: { + access: jest.fn().mockResolvedValue(), + rename: jest.fn().mockResolvedValue(), + mkdir: jest.fn().mockResolvedValue(), + unlink: jest.fn().mockResolvedValue(), + stat: jest.fn().mockResolvedValue({ size: 100 }) + } +})); + +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: logger + }; +}); + +jest.mock('../src/main/ipc/files/batchLockManager', () => ({ + acquireBatchLock: jest.fn().mockResolvedValue(true), + renewBatchLock: jest.fn().mockReturnValue(true), + releaseBatchLock: jest.fn() +})); + +// FilePathCoordinator drives `pathIndexUpdated`; per-op persistence is only +// journaled when the coordinator reports success, so give the handler a +// controllable one instead of the real container (which has none in tests). +const mockCoordinator = { + batchPathUpdate: jest.fn().mockResolvedValue({ success: true, summary: {} }) +}; +jest.mock('../src/main/services/ServiceContainer', () => ({ + container: { + has: jest.fn((id) => id === 'filePathCoordinator'), + resolve: jest.fn(() => mockCoordinator), + tryResolve: jest.fn(() => null) + }, + ServiceIds: { + FILE_PATH_COORDINATOR: 'filePathCoordinator', + LEARNING_FEEDBACK: 'learningFeedback' + } +})); + +// The learning block requires FolderMatchingService lazily; the real module +// cannot load under this suite's fs mock, which made that block fail silently. +jest.mock('../src/main/services/FolderMatchingService', () => ({ + matchCategoryToFolder: jest.fn(() => null) +})); + +jest.mock('../src/main/ipc/files/batchValidator', () => ({ + validateBatchOperation: jest.fn(() => null), // Returns null on success + MAX_BATCH_SIZE: 1000 +})); + +jest.mock('../src/main/ipc/files/batchRollback', () => ({ + executeRollback: jest.fn().mockResolvedValue({ success: false, rolledBack: true }) +})); + +jest.mock('../src/main/ipc/files/batchProgressReporter', () => ({ + sendFileOperationBatchComplete: jest.fn(), + sendOperationProgress: jest.fn(), + sendChunkedResults: jest.fn().mockResolvedValue({ sent: true }) +})); + +jest.mock('../src/shared/fileOperationTracker', () => ({ + getInstance: jest.fn(() => ({ + recordOperation: jest.fn() + })) +})); + +jest.mock('../src/main/ipc/files/embeddingSync', () => ({ + syncEmbeddingForMove: jest.fn(), + removeEmbeddingsForPathBestEffort: jest.fn() +})); + +jest.mock('../src/main/utils/fileDedup', () => ({ + computeFileChecksum: jest.fn().mockResolvedValue('checksum123'), + handleDuplicateMove: jest.fn().mockResolvedValue(null) // Return null means no duplicate handled, proceed with move +})); + +jest.mock('../src/shared/atomicFileOperations', () => ({ + crossDeviceMove: jest.fn(), + // Delegate to the suite's fs.rename mock so tests keep driving collision + // behavior by seeding fs.rename rejections. Real no-replace semantics + // (occupancy preflight -> synthetic EEXIST) are covered by + // atomicFileOperations.test.js and analyzeNameOrganize.e2e.test.js. + renameNoReplace: jest.fn((src, dest) => require('fs').promises.rename(src, dest)) +})); + +jest.mock('../src/shared/pathSanitization', () => ({ + validateFileOperationPath: jest.fn((p) => ({ valid: true, normalizedPath: p })), + // Reached by the smart-folder lookup once a batch has smart folders. + normalizePathForIndex: jest.fn((p) => String(p).replace(/\\/g, '/')) +})); + +jest.mock('../src/shared/promiseUtils', () => { + // Minimal Semaphore for tests. Like the real one, a waiter given a queue + // timeout is rejected when it runs out, so a batch that queued its moves + // behind one again would fail the long-batch test below. + class MockSemaphore { + constructor(max, _maxQueue, queueTimeoutMs) { + this.max = max; + this.queueTimeoutMs = queueTimeoutMs; + this.active = 0; + this.queue = []; + } + async acquire() { + if (this.active < this.max) { + this.active++; + return; + } + await new Promise((resolve, reject) => { + const waiter = { resolve, timeout: undefined }; + if (this.queueTimeoutMs > 0) { + waiter.timeout = setTimeout(() => { + this.queue.splice(this.queue.indexOf(waiter), 1); + reject(new Error('Request queue timeout')); + }, this.queueTimeoutMs); + } + this.queue.push(waiter); + }); + } + release() { + if (this.queue.length > 0) { + const waiter = this.queue.shift(); + clearTimeout(waiter.timeout); + waiter.resolve(); + } else if (this.active > 0) { + this.active--; + } + } + } + return { + withTimeout: jest.fn((promise) => promise), + batchProcess: jest.fn().mockResolvedValue(), + withAbortableTimeout: jest.fn((fn) => fn({ signal: {} })), + delay: jest.fn().mockResolvedValue(), + Semaphore: MockSemaphore, + 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/correlationId', () => ({ + withCorrelationId: jest.fn((fn) => fn()) +})); + +// Mock semantic service (needed for rebuild check) +// Destination policy: real module with the decision points wrapped so one +// test can refuse a landing folder; otherwise 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) + }; +}); + +jest.mock('../src/main/ipc/semantic', () => ({ + getSearchServiceInstance: jest.fn(() => ({ + invalidateAndRebuild: jest.fn().mockResolvedValue() + })) +})); + +describe('organize corrections carry the analysis label', () => { + const learning = require('../src/main/services/organization/learningFeedback'); + const { + findLearnedCorrection + } = require('../src/main/services/organization/feedbackMemoryUtils'); + const { container } = require('../src/main/services/ServiceContainer'); + const FOLDERS = [ + { id: 'gsc', name: 'GSC exports', path: '/dest/GSC exports' }, + { id: 'bing', name: 'Bing exports', path: '/dest/Bing exports' } + ]; + let params; + let memories; + let learner; + let restore; + + beforeEach(() => { + jest.clearAllMocks(); + const fs = require('fs').promises; + fs.access.mockImplementation(async (p) => { + if (p.includes('dest')) return; + if (p.includes('src')) throw { code: 'ENOENT' }; + return; + }); + fs.stat.mockReset().mockResolvedValue({ size: 100 }); + // The history label equals the destination: no divergence. + mockCoordinator.batchPathUpdate.mockReset().mockResolvedValue({ success: true, summary: {} }); + + // The real learning service, with the memory store reduced to a list + // shaped like the one recordFeedbackNote writes. + memories = []; + learner = new learning.LearningFeedbackService({ + suggestionService: { + recordFeedbackNote: jest.fn(async (_file, suggestion, accepted, note, extra) => { + const entry = { + text: note, + source: accepted ? 'feedback_accept' : 'feedback_reject', + targetFolder: suggestion?.folder || null, + ...(extra?.filePath ? { filePath: extra.filePath } : {}), + ...(extra?.correction ? { correction: extra.correction } : {}) + }; + memories.push(entry); + return entry; + }) + }, + getSmartFolders: () => FOLDERS + }); + jest.spyOn(learner, 'recordFileMove').mockResolvedValue(true); + jest.spyOn(learner, 'recordCorrection'); + + const hasImpl = container.has.getMockImplementation(); + const resolveImpl = container.resolve.getMockImplementation(); + container.has.mockImplementation( + (id) => id === 'filePathCoordinator' || id === 'learningFeedback' + ); + container.resolve.mockImplementation((id) => + id === 'learningFeedback' ? learner : mockCoordinator + ); + const spy = jest.spyOn(learning, 'getInstance').mockReturnValue(learner); + restore = () => { + spy.mockRestore(); + container.has.mockImplementation(hasImpl); + container.resolve.mockImplementation(resolveImpl); + }; + + const mockLogger = require('../src/shared/logger').logger; + params = { + operation: { operations: [] }, + logger: mockLogger, + getServiceIntegration: jest.fn(() => ({ + processingState: { + createOrLoadOrganizeBatch: jest.fn((id, ops) => ({ operations: ops })), + markOrganizeOpStarted: jest.fn(), + markOrganizeOpDone: jest.fn(), + markOrganizeOpError: jest.fn(), + completeOrganizeBatch: jest.fn() + }, + undoRedo: { recordAction: jest.fn() } + })), + getMainWindow: jest.fn() + }; + }); + afterEach(() => restore()); + + /** The card suggested Bing exports; the user sent the file to GSC exports. */ + async function moveToGscOverBing(name, extra = {}) { + params.operation.operations = [ + { + source: `/src/${name}`, + destination: `/dest/GSC exports/${name}`, + type: 'move', + suggestion: { folder: 'Bing exports', source: 'engine' }, + ...extra + } + ]; + const result = await handleBatchOrganize(params); + expect(result.success).toBe(true); + } + + test('with no divergence the correction is stored under the label the op carries', async () => { + await moveToGscOverBing('queries.xlsx', { analysisLabel: 'GSC exports' }); + + expect(learner.recordCorrection).toHaveBeenCalledWith( + expect.objectContaining({ + wrongFolder: 'Bing exports', + correctFolder: 'GSC exports', + oldCategory: 'GSC exports' + }) + ); + expect(memories).toHaveLength(1); + expect(memories[0].correction).toEqual( + expect.objectContaining({ extension: 'xlsx', category: 'gsc exports' }) + ); + }); + + test('two different files corrected that way make the corrected folder the learned one', async () => { + await moveToGscOverBing('pages.xlsx', { analysisLabel: 'GSC exports' }); + await moveToGscOverBing('queries.xlsx', { analysisLabel: 'GSC exports' }); + + const learned = findLearnedCorrection({ + memories, + extension: 'xlsx', + category: 'GSC exports', + fromFolder: 'Bing exports', + smartFolders: FOLDERS + }); + expect(learned).toEqual({ folder: FOLDERS[0], files: 2 }); + }); + + test("a divergence's label still wins over the op's", async () => { + mockCoordinator.batchPathUpdate.mockResolvedValue({ + success: true, + summary: {}, + divergences: [ + { + filePath: '/dest/GSC exports/sheet.xlsx', + oldCategory: 'Reports', + newCategory: 'GSC exports' + } + ] + }); + await moveToGscOverBing('sheet.xlsx', { analysisLabel: 'GSC exports' }); + + expect(learner.recordCorrection).toHaveBeenCalledWith( + expect.objectContaining({ oldCategory: 'Reports' }) + ); + }); +}); diff --git a/test/components/OrganizePhase.test.js b/test/components/OrganizePhase.test.js index d26075d..e797583 100644 --- a/test/components/OrganizePhase.test.js +++ b/test/components/OrganizePhase.test.js @@ -368,6 +368,46 @@ describe('OrganizePhase premium preflight copy', () => { expect(await screen.findByText('ORGANIZE_PROGRESS')).toBeInTheDocument(); }); + test('a destination conflict names the files by their own names, not the shared new one', () => { + const { useOrganization } = require('../../src/renderer/phases/organize/useOrganization'); + useOrganization.mockReturnValue({ + isOrganizing: false, + isPaused: false, + batchProgress: null, + organizePreview: [], + handleOrganizeFiles: jest.fn(), + organizeConflicts: [ + { + destination: '/Users/alex/Exports/search-performance-2026-09-03.xlsx', + files: [ + { + fileName: 'search-performance-2026-09-03.xlsx', + sourcePath: '/Users/alex/Inbox/export (1).xlsx' + }, + { + fileName: 'search-performance-2026-09-03.xlsx', + sourcePath: '/Users/alex/Inbox/export (2).xlsx' + } + ] + } + ] + }); + + render(); + + expect(screen.getByText('export (1).xlsx, export (2).xlsx')).toBeInTheDocument(); + expect( + screen.queryByText(/search-performance-2026-09-03\.xlsx, search-performance/) + ).not.toBeInTheDocument(); + useOrganization.mockReturnValue({ + isOrganizing: false, + batchProgress: null, + organizePreview: [], + handleOrganizeFiles: jest.fn(), + organizeConflicts: [] + }); + }); + test('shows how the last run ended, and lets the user dismiss it', () => { const { useLastOrganizeRun } = require('../../src/renderer/hooks/useLastOrganizeRun'); const { useOrganization } = require('../../src/renderer/phases/organize/useOrganization'); diff --git a/test/components/ReadyFileItem.learningNote.test.js b/test/components/ReadyFileItem.learningNote.test.js index eff7d15..b39d564 100644 --- a/test/components/ReadyFileItem.learningNote.test.js +++ b/test/components/ReadyFileItem.learningNote.test.js @@ -117,6 +117,16 @@ describe('the score on the card', () => { expect(screen.queryByText(/% confidence/)).not.toBeInTheDocument(); }); + test('a folder the user picked shows no score', () => { + // The label's 60% rates the label, not the folder the user chose. + renderItem({ + category: 'GSC', + routing: { folder: FOLDERS[0], source: 'user', engine: ENGINE } + }); + expect(screen.getByTestId('organize-routing-note')).toHaveTextContent('Your choice'); + expect(screen.queryByText(/% confidence/)).not.toBeInTheDocument(); + }); + test('a content match still shows its score', () => { renderItem({ routing: { folder: FOLDERS[1], source: 'engine', engine: ENGINE } }); expect(screen.getByText('62% confidence')).toBeInTheDocument(); diff --git a/test/components/ReadyFileItem.routing.test.js b/test/components/ReadyFileItem.routing.test.js index f11f898..bb4d305 100644 --- a/test/components/ReadyFileItem.routing.test.js +++ b/test/components/ReadyFileItem.routing.test.js @@ -84,8 +84,9 @@ test('a user choice says so and names the suggestion it overrode', () => { expect(screen.getByTestId('organize-routing-note')).toHaveTextContent( 'Your choice (suggested: Finance)' ); - // Not an engine placement: the confidence falls back to the label's. - expect(screen.getByText('95% confidence')).toBeInTheDocument(); + // The label's 95% and the engine's 64% both rate other folders, not the + // one the user picked: show no percentage. + expect(screen.queryByText(/% confidence/)).not.toBeInTheDocument(); }); test('a name match says so and keeps the plain folder list', () => { diff --git a/test/useOrganization.preview.test.js b/test/useOrganization.preview.test.js index 8493a93..1e20b5c 100644 --- a/test/useOrganization.preview.test.js +++ b/test/useOrganization.preview.test.js @@ -1,9 +1,10 @@ /** * The Organize "Preview" asks the main process for a dry-run plan of the * same operations a Move would send. `handlePreviewOrganize` returns that - * plan, adds the files this batch sends to one name (the Move refuses to - * start while any exist), and throws when the request fails or is refused, - * so the screen can say why instead of showing an empty preview. + * plan, numbers apart the files this batch would give one name (marked + * like a name taken on disk), lists any it still sends to one name (the Move + * refuses to start while any exist), and throws when the request fails or is + * refused, so the screen can say why instead of showing an empty preview. */ import { renderHook } from '@testing-library/react'; @@ -103,24 +104,98 @@ describe('useOrganization: handlePreviewOrganize', () => { expect(plan.sameDestination).toEqual([]); }); - test('lists the files this batch sends to one name', async () => { + test('numbers apart files this batch would give one name, and marks them', async () => { const first = file('/Users/alex/Downloads/scan 1.pdf', 'Finance', 'Invoice.pdf'); const second = file('/Users/alex/Downloads/scan 2.pdf', 'Finance', 'Invoice.pdf'); + const third = file('/Users/alex/Downloads/scan 3.pdf', 'Finance', 'Invoice.pdf'); const other = file('/Users/alex/Downloads/budget.xlsx', 'Finance'); + // Main echoes what it was sent: the numbered names are free on disk. + previewBatchOrganize.mockImplementation(async (ops) => + dryRunPlan(ops.map((op) => ({ source: op.source, destination: op.destination }))) + ); + + const { result } = renderHook(() => + useOrganization(hookOptions([first, second, third, other])) + ); + const plan = await result.current.handlePreviewOrganize(); + + // The shape main gives a taken name (formatNumberedCollisionCandidate). + expect(previewBatchOrganize.mock.calls[0][0].map((op) => op.destination)).toEqual([ + '/Users/alex/Sorted/Finance/Invoice.pdf', + '/Users/alex/Sorted/Finance/Invoice_1.pdf', + '/Users/alex/Sorted/Finance/Invoice_2.pdf', + '/Users/alex/Sorted/Finance/budget.xlsx' + ]); + expect(plan.wouldMove.map((item) => Boolean(item.collision))).toEqual([ + false, + true, + true, + false + ]); + // Nothing left that would stop the move. + expect(plan.sameDestination).toEqual([]); + }); + + test('a number never lands on the name another file of the batch is headed for', async () => { + const first = file('/Users/alex/Downloads/a.pdf', 'Finance', 'Invoice.pdf'); + const second = file('/Users/alex/Downloads/b.pdf', 'Finance', 'Invoice.pdf'); + const named = file('/Users/alex/Downloads/c.pdf', 'Finance', 'Invoice_1.pdf'); + previewBatchOrganize.mockResolvedValue(dryRunPlan([])); + + const { result } = renderHook(() => useOrganization(hookOptions([first, second, named]))); + const plan = await result.current.handlePreviewOrganize(); + + expect(previewBatchOrganize.mock.calls[0][0].map((op) => op.destination)).toEqual([ + '/Users/alex/Sorted/Finance/Invoice.pdf', + '/Users/alex/Sorted/Finance/Invoice_2.pdf', + '/Users/alex/Sorted/Finance/Invoice_1.pdf' + ]); + expect(plan.sameDestination).toEqual([]); + }); + + test('a file already filed under the name keeps it; the newcomer is numbered', async () => { + const incoming = file('/Users/alex/Downloads/scan.pdf', 'Finance', 'Invoice.pdf'); + const filed = file('/Users/alex/Sorted/Finance/Invoice.pdf', 'Finance', 'Invoice.pdf'); + previewBatchOrganize.mockResolvedValue(dryRunPlan([])); + + const { result } = renderHook(() => useOrganization(hookOptions([incoming, filed]))); + await result.current.handlePreviewOrganize(); + + expect(previewBatchOrganize.mock.calls[0][0]).toEqual([ + expect.objectContaining({ + source: incoming.path, + destination: '/Users/alex/Sorted/Finance/Invoice_1.pdf' + }), + expect.objectContaining({ + source: filed.path, + destination: '/Users/alex/Sorted/Finance/Invoice.pdf' + }) + ]); + }); + + test('names that differ only in case or accent encoding are numbered apart on Windows', async () => { + const win = (...parts) => ['C:', 'Users', 'alex', ...parts].join('\\'); + const folder = { id: 'fin', name: 'Finance', path: win('Sorted', 'Finance') }; + // Decomposed accents (as macOS returns them) and composed upper case. + const first = file(win('Downloads', '1.pdf'), 'Finance', 'Résumé.pdf'); + const second = file(win('Downloads', '2.pdf'), 'Finance', 'RÉSUMÉ.PDF'); previewBatchOrganize.mockResolvedValue(dryRunPlan([])); - const { result } = renderHook(() => useOrganization(hookOptions([first, second, other]))); + const { result } = renderHook(() => + useOrganization({ + ...hookOptions([first, second]), + defaultLocation: win('Documents'), + findSmartFolderForCategory: () => folder, + smartFolders: [folder] + }) + ); const plan = await result.current.handlePreviewOrganize(); - expect(plan.sameDestination).toEqual([ - { - destination: '/Users/alex/Sorted/Finance/Invoice.pdf', - files: [ - { fileName: 'Invoice.pdf', sourcePath: first.path }, - { fileName: 'Invoice.pdf', sourcePath: second.path } - ] - } + expect(previewBatchOrganize.mock.calls[0][0].map((op) => op.destination)).toEqual([ + win('Sorted', 'Finance', 'Résumé.pdf'), + win('Sorted', 'Finance', 'RÉSUMÉ_1.PDF') ]); + expect(plan.sameDestination).toEqual([]); }); test('previews only the files it is given', async () => { diff --git a/test/useOrganization.runFiles.test.js b/test/useOrganization.runFiles.test.js index 015d725..e125446 100644 --- a/test/useOrganization.runFiles.test.js +++ b/test/useOrganization.runFiles.test.js @@ -252,21 +252,104 @@ describe('useOrganization: the per-file record of a run', () => { }, { path: '/in/2.pdf', name: '2.pdf', analysis: { category: 'x', suggestedName: 'report.pdf' } } ]; + const sentDestinations = (options) => + options.executeAction.mock.calls[0][0].operations.map((op) => op.destination); - test('are one destination on a Mac', async () => { + test('are one destination on a Mac, so the second is numbered and the move runs', async () => { mockIsMac = true; - const { options, hook } = await run(null, { unprocessedFiles: twins }); - expect(hook.current.organizeConflicts).toHaveLength(1); - expect(options.executeAction).not.toHaveBeenCalled(); + const { options, hook } = await run( + { success: true, successCount: 2, results: [] }, + { unprocessedFiles: twins } + ); + expect(hook.current.organizeConflicts).toHaveLength(0); + expect(sentDestinations(options)).toEqual([ + '/Documents/Uncategorized/Report.pdf', + '/Documents/Uncategorized/report_1.pdf' + ]); }); test('are two destinations on Linux', async () => { mockIsMac = false; - const { hook } = await run( + const { options, hook } = await run( { success: true, successCount: 2, results: [] }, { unprocessedFiles: twins } ); expect(hook.current.organizeConflicts).toHaveLength(0); + expect(sentDestinations(options)).toEqual([ + '/Documents/Uncategorized/Report.pdf', + '/Documents/Uncategorized/report.pdf' + ]); + }); + }); + + test('two exports given the same name both move: the second is numbered, nothing blocks', async () => { + const exports = [ + 'search-performance-2026-09-03.xlsx', + 'search-performance-2026-09-03_2.xlsx' + ].map((name) => ({ + path: `/Users/alex/Downloads/${name}`, + name, + analysis: { category: 'GSC exports', suggestedName: 'search-performance-2026-09-03.xlsx' } + })); + const { options, hook } = await run( + { success: true, successCount: 2, results: [] }, + { unprocessedFiles: exports } + ); + + expect(hook.current.organizeConflicts).toEqual([]); + expect(options.addNotification.mock.calls.map((call) => call[0])).not.toEqual( + expect.arrayContaining([expect.stringMatching(/Cannot organize/)]) + ); + expect(options.executeAction.mock.calls[0][0].operations).toEqual([ + expect.objectContaining({ + source: exports[0].path, + destination: '/Documents/Uncategorized/search-performance-2026-09-03.xlsx', + analysisLabel: 'GSC exports' + }), + expect.objectContaining({ + source: exports[1].path, + destination: '/Documents/Uncategorized/search-performance-2026-09-03_1.xlsx', + analysisLabel: 'GSC exports' + }) + ]); + }); + + describe('a batch main refused before any file', () => { + const lockBusy = { + success: false, + error: 'Another batch operation is already in progress. Please wait for it to complete.', + errorCode: 'BATCH_LOCK_TIMEOUT' + }; + + test('the summary gives the reason, and no toast says to check the logs', async () => { + const { options } = await run(lockBusy); + + expect(lastRun(options)).toEqual( + expect.objectContaining({ + outcome: 'none', + count: 0, + headline: 'No files were organized', + detail: expect.stringContaining('Another batch operation is already in progress') + }) + ); + const messages = options.addNotification.mock.calls.map((call) => call[0]); + expect(messages.filter((m) => /Check the logs/i.test(m))).toEqual([]); + expect(messages).toEqual( + expect.arrayContaining([ + expect.stringContaining('Another batch operation is already in progress') + ]) + ); + }); + + test('each file gives that reason, not that the run ended before it', async () => { + const { options } = await run(lockBusy); + + const rows = runFilesDispatches(options).at(-1).payload; + expect(rows.map((r) => r.outcome)).toEqual(['notMoved', 'notMoved', 'notMoved']); + for (const row of rows) { + expect(row.reason).toMatch(/Another batch operation is already in progress/); + } + expect(lastRun(options).notMovedCount).toBe(3); }); }); }); diff --git a/test/useOrganization.test.js b/test/useOrganization.test.js index fe3ee6b..b618324 100644 --- a/test/useOrganization.test.js +++ b/test/useOrganization.test.js @@ -415,7 +415,9 @@ describe('useOrganization', () => { type: 'move', source: '/in/receipt.pdf', destination: '/Library/Finance/receipt.pdf', - suggestion: { folder: 'Finance', path: '/Library/Finance', source: 'engine' } + suggestion: { folder: 'Finance', path: '/Library/Finance', source: 'engine' }, + // The label, so a correction away from Finance is learned under it. + analysisLabel: 'Taxes' } ]); }); diff --git a/test/validationSchemas.test.js b/test/validationSchemas.test.js index 732fea4..bafcfb5 100644 --- a/test/validationSchemas.test.js +++ b/test/validationSchemas.test.js @@ -345,6 +345,23 @@ describe('validationSchemas (Zod path)', () => { }); }); + // The same for the analysis label: a correction is learned under it. + test('preserves the per-op analysis label on a batch_organize payload', () => { + const result = schemas.fileOperation.safeParse({ + type: 'batch_organize', + operations: [ + { + source: '/a/file.txt', + destination: '/b/Finance/file.txt', + suggestion: { folder: 'Receipts', source: 'engine' }, + analysisLabel: 'Finance' + } + ] + }); + expect(result.success).toBe(true); + expect(result.data.operations[0].analysisLabel).toBe('Finance'); + }); + test('rejects a suggestion with a relative path', () => { const result = schemas.fileOperation.safeParse({ type: 'batch_organize', From eeecbbb204673b68a793ca30f5f89f5f512ab40f Mon Sep 17 00:00:00 2001 From: Levy Tate <78818969+iLevyTate@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:13:30 -0500 Subject: [PATCH 3/6] fix(analysis): grounded answers are not taken for prompt echoes, and shared folder-name words do not pick a folder dropPromptEchoes no longer checks the reasoning against Smart Folder descriptions (the prompt asks the model to cite them), and a word that also occurs in the document no longer counts as copied from a description. In matchCategoryToFolder's token-overlap step a word shared by two or more folder names ("exports") no longer scores, and a tie falls through to the description step instead of going to the first folder in the list. --- src/main/analysis/documentAnalysis.js | 8 +- src/main/analysis/utils.js | 72 +++++++--- src/main/services/FolderMatchingService.js | 41 ++++-- ...MatchingService.overlapSharedWords.test.js | 108 +++++++++++++++ test/analysis-utils.test.js | 128 ++++++++++++++++++ test/documentAnalysis.behavior.test.js | 19 +++ 6 files changed, 344 insertions(+), 32 deletions(-) create mode 100644 test/FolderMatchingService.overlapSharedWords.test.js diff --git a/src/main/analysis/documentAnalysis.js b/src/main/analysis/documentAnalysis.js index a3ba96c..6ed4d87 100644 --- a/src/main/analysis/documentAnalysis.js +++ b/src/main/analysis/documentAnalysis.js @@ -1113,7 +1113,13 @@ async function analyzeDocumentStages(filePath, smartFolders = [], options = {}, }); const normalized = normalizeAnalysisResult( { - ...dropPromptEchoes(analysis, smartFolders), + // The file's own words are not echoes of a folder description + // that happens to use them too. + ...dropPromptEchoes( + analysis, + smartFolders, + `${fileName || ''}\n${extractedTextForStorage || ''}` + ), llmSuggestedName: analysis.suggestedName || null, contentLength: extractedTextLength, extractionMethod: 'content', diff --git a/src/main/analysis/utils.js b/src/main/analysis/utils.js index fa5cdf8..37d8013 100644 --- a/src/main/analysis/utils.js +++ b/src/main/analysis/utils.js @@ -95,6 +95,9 @@ const ECHO_STOPWORDS = new Set( ) ); const ECHO_FIELDS = ['summary', 'purpose', 'project', 'reasoning', 'type', 'entity']; +// The prompt asks for the reasoning to cite the chosen folder's description, +// so it is only checked against the schema instructions. +const ECHO_SCHEMA_ONLY_FIELDS = new Set(['reasoning']); // A value is an echo when nearly all of its words come from one source text // AND it reproduces a good part of that text. The second test keeps a real // answer that merely shares vocabulary ("A logo for a company or @@ -127,42 +130,71 @@ function echoWords(text) { * guess so the file is flagged for review. Same idea as * normalizeImageContentType, applied to the free-text fields. * + * A well-described folder shares its vocabulary with the files that belong + * in it: a GSC export's summary names the same queries, clicks and + * impressions the folder's description lists. When the caller has the + * document's text, a word the document itself contains is the model reading + * the file, not the folder description, so it is not counted as copied from + * one. Callers without text (images, media) keep the stricter check. The + * schema instructions are generic words any long document contains, so + * they are always checked in full. + * * @param {Record} result - Model output (mutated copy returned) * @param {Array<{ description?: string }>} [smartFolders] + * @param {string | null} [documentText] - The file's extracted text and name * @returns {Record} */ -function dropPromptEchoes(result, smartFolders = []) { +function dropPromptEchoes(result, smartFolders = [], documentText = null) { if (!result || typeof result !== 'object') return result; - const sources = [ - // The instructions without their "(e.g., ...)" examples: an example like - // 'sunset_beach' is a legitimate thing for a picture to show. - ...Object.values(ANALYSIS_SCHEMA_PROMPT) + /** @param {string[]} texts */ + const toSources = (texts) => + texts.map((text) => new Set(echoWords(text))).filter((source) => source.size > 0); + // The instructions without their "(e.g., ...)" examples: an example like + // 'sunset_beach' is a legitimate thing for a picture to show. + const schemaSources = toSources( + Object.values(ANALYSIS_SCHEMA_PROMPT) .filter((v) => typeof v === 'string') - .map((v) => v.replace(/\(e\.g\.[^)]*\)/gi, ' ')), - ...(Array.isArray(smartFolders) ? smartFolders : []) + .map((v) => v.replace(/\(e\.g\.[^)]*\)/gi, ' ')) + ); + const folderSources = toSources( + (Array.isArray(smartFolders) ? smartFolders : []) .map((f) => f?.description) .filter((d) => typeof d === 'string' && d.trim()) - ] - .map((text) => new Set(echoWords(text))) - .filter((source) => source.size > 0); + ); + /** @type {Set} */ + const documentWords = new Set( + typeof documentText === 'string' && documentText ? echoWords(documentText) : [] + ); - /** @param {unknown} value */ - const isEcho = (value) => { - if (typeof value !== 'string') return false; - // Compared without "(e.g., ...)" on both sides: a copied instruction - // carries its examples along. - const words = new Set(echoWords(value.replace(/\(e\.g\.[^)]*\)/gi, ' '))); - if (words.size < ECHO_MIN_WORDS) return false; - return sources.some((source) => { + /** + * @param {Set} words + * @param {Set[]} sources + * @param {Set} [grounded] - Words not counted as shared + */ + const copiesAny = (words, sources, grounded) => + sources.some((source) => { let shared = 0; - for (const word of words) if (source.has(word)) shared += 1; + for (const word of words) if (source.has(word) && !grounded?.has(word)) shared += 1; return ( shared / words.size >= ECHO_CONTAINMENT && shared / source.size >= ECHO_SOURCE_COVERAGE ); }); + + /** @param {string} field */ + const isEcho = (field) => { + const value = result[field]; + if (typeof value !== 'string') return false; + // Compared without "(e.g., ...)" on both sides: a copied instruction + // carries its examples along. + const words = new Set(echoWords(value.replace(/\(e\.g\.[^)]*\)/gi, ' '))); + if (words.size < ECHO_MIN_WORDS) return false; + return ( + copiesAny(words, schemaSources) || + (!ECHO_SCHEMA_ONLY_FIELDS.has(field) && copiesAny(words, folderSources, documentWords)) + ); }; - const echoed = ECHO_FIELDS.filter((field) => isEcho(result[field])); + const echoed = ECHO_FIELDS.filter(isEcho); if (echoed.length === 0) return result; const cleaned = { ...result }; diff --git a/src/main/services/FolderMatchingService.js b/src/main/services/FolderMatchingService.js index 2e7a24f..e8dcdde 100644 --- a/src/main/services/FolderMatchingService.js +++ b/src/main/services/FolderMatchingService.js @@ -1971,29 +1971,48 @@ class FolderMatchingService { // Token overlap scoring (simple, deterministic). Filler words and plain // numbers do not count, so a shared "for", "data" or "2026" alone is not - // a match. + // a match. Nor does a word two or more folder names share: with "GSC + // exports", "Bing exports" and "Clarity exports", "exports" does not tell + // them apart, and counting it filed "Search Console exports" in whichever + // of them came first. + const nameTokensByFolder = folders.map((f) => + overlapTokens(canon(String(f?.name || '').trim())) + ); + /** @type {Map} */ + const foldersPerToken = new Map(); + for (const nameTokens of nameTokensByFolder) { + for (const t of new Set(nameTokens)) { + foldersPerToken.set(t, (foldersPerToken.get(t) || 0) + 1); + } + } const tokens = new Set(overlapTokens(rawCanon)); let best = null; let bestScore = 0; - for (const f of folders) { + let bestShared = 0; + let tiedShared = false; + folders.forEach((f, index) => { const name = String(f?.name || '').trim(); - if (!name) continue; - const nameCanon = canon(name); - const nameTokens = overlapTokens(nameCanon); - if (nameTokens.length === 0) continue; - let score = 0; + const nameTokens = nameTokensByFolder[index]; + if (!name || nameTokens.length === 0) return; + let shared = 0; nameTokens.forEach((t) => { - if (tokens.has(t)) score += 1; + if (tokens.has(t) && (foldersPerToken.get(t) || 0) < 2) shared += 1; }); + if (shared === 0) return; // Small bias for shorter names to avoid always matching long "Financial Documents" when raw is "Financial" - score -= Math.min(0.25, nameTokens.length * 0.01); + const score = shared - Math.min(0.25, nameTokens.length * 0.01); + if (shared === bestShared) tiedShared = true; if (score > bestScore) { + if (shared > bestShared) tiedShared = false; bestScore = score; + bestShared = shared; best = name; } - } + }); - if (bestScore > 0.5 && best) { + // Two folders matching as many words each is a guess, not a match: the + // description step below can tell them apart, or nothing does. + if (bestScore > 0.5 && best && !tiedShared) { logger.debug('[FolderMatching] Token overlap match', { rawCategory: raw, matchedFolder: best, diff --git a/test/FolderMatchingService.overlapSharedWords.test.js b/test/FolderMatchingService.overlapSharedWords.test.js new file mode 100644 index 0000000..003bd0d --- /dev/null +++ b/test/FolderMatchingService.overlapSharedWords.test.js @@ -0,0 +1,108 @@ +/** + * @jest-environment node + * + * A word several folder names share does not tell those folders apart. With + * "GSC exports", "Bing exports" and "Clarity exports", the token overlap step + * used to score each of them on "exports" alone and keep whichever came + * first, so "Google Search Console exports" was filed under "Bing exports" + * whenever that folder was added first. + */ + +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/services/LlamaService', () => ({ + getInstance: () => ({ generateEmbedding: jest.fn(), getConfig: jest.fn() }) +})); + +const FolderMatchingService = require('../src/main/services/FolderMatchingService'); + +const gsc = { + name: 'GSC exports', + description: + 'Google Search Console performance exports in Excel: queries, pages, clicks, impressions, CTR and position.' +}; +const bing = { + name: 'Bing exports', + description: + 'Bing Webmaster Tools exports: keywords, pages, clicks and impressions from Bing search.' +}; +const clarity = { + name: 'Clarity exports', + description: 'Microsoft Clarity CSV exports: sessions, users, scroll depth, browsers and devices.' +}; +const seo = { + name: 'SEO audits', + description: 'PDF SEO audit reports with site scores, backlinks and recommendations.' +}; +const uncategorized = { + name: 'Uncategorized', + description: 'Files that fit no other folder.', + category: 'uncategorized', + isDefault: true +}; + +const orders = { + 'Bing first': [bing, clarity, gsc, seo, uncategorized], + 'GSC first': [gsc, bing, clarity, seo, uncategorized] +}; + +describe.each(Object.entries(orders))('token overlap with shared words (%s)', (_order, folders) => { + const match = (label) => FolderMatchingService.matchCategoryToFolder(label, folders); + + test('a spelled-out folder name goes to the folder its description names', () => { + expect(match('Google Search Console exports')).toBe('GSC exports'); + expect(match('Search Console exports')).toBe('GSC exports'); + }); + + test('a distinctive word still decides the match', () => { + expect(match('Bing keyword exports')).toBe('Bing exports'); + expect(match('Clarity session exports')).toBe('Clarity exports'); + }); + + test('a word only one description lists decides the match', () => { + expect(match('Keyword exports')).toBe('Bing exports'); + }); +}); + +describe('a label that only shares a common word', () => { + test.each(['Web analytics exports', 'Keyword exports', 'Monthly exports'])( + '%s is matched the same way whatever the folder order', + (label) => { + const results = Object.values(orders).map((folders) => + FolderMatchingService.matchCategoryToFolder(label, folders) + ); + expect(results[0]).toBe(results[1]); + } + ); + + test('Web analytics exports is not filed in an exports folder by order', () => { + for (const folders of Object.values(orders)) { + expect(FolderMatchingService.matchCategoryToFolder('Web analytics exports', folders)).toBe( + 'Uncategorized' + ); + } + }); +}); + +describe('two folders matching as many distinctive words', () => { + test('fall through to the descriptions instead of folder order', () => { + const invoices = { name: 'Client invoices', description: 'Bills sent to clients' }; + const receipts = { name: 'Vendor receipts', description: 'Receipts from vendors' }; + const label = 'Client receipts'; + for (const folders of [ + [invoices, receipts, uncategorized], + [receipts, invoices, uncategorized] + ]) { + expect(FolderMatchingService.matchCategoryToFolder(label, folders)).toBe('Uncategorized'); + } + }); +}); diff --git a/test/analysis-utils.test.js b/test/analysis-utils.test.js index 16d892a..deb743d 100644 --- a/test/analysis-utils.test.js +++ b/test/analysis-utils.test.js @@ -280,4 +280,132 @@ describe('dropPromptEchoes', () => { test('passes a missing answer through', () => { expect(dropPromptEchoes(null, folders)).toBeNull(); }); + + // Folders whose descriptions name the columns their files carry: a correct + // answer reads the same words out of the file. + describe('with well-described folders', () => { + const exportFolders = [ + { + name: 'GSC exports', + description: + 'Google Search Console performance exports in Excel: queries, pages, clicks, impressions, CTR and position.' + }, + { + name: 'Bing exports', + description: + 'Bing Webmaster Tools exports: keywords, pages, clicks and impressions from Bing search.' + }, + { + name: 'Clarity exports', + description: + 'Microsoft Clarity CSV exports: sessions, users, scroll depth, browsers and devices.' + }, + { + name: 'SEO audits', + description: 'PDF SEO audit reports with site scores, backlinks and recommendations.' + } + ]; + const bingDocument = + 'bing-webmaster-tools-keywords.csv\nBing Webmaster Tools - Search Performance\nKeyword,Clicks,Impressions,CTR,Avg position\nlocal ai organizer,12,340,3.5%,4.2'; + const clarityDocument = + 'clarity-dashboard-export.csv\nMicrosoft Clarity dashboard\nSessions,Users,Scroll depth,Browsers\n1520,1203,54%,Chrome'; + const gscDocument = + 'Queries.xlsx\nTop queries,Clicks,Impressions,CTR,Position\nfile organizer,40,1200,3.3%,6.1'; + + test.each([ + [ + 'reasoning that cites the folder description', + 'reasoning', + 'Contains Bing Webmaster Tools keywords, clicks and impressions from Bing search.', + bingDocument + ], + [ + 'a summary in the folder description words', + 'summary', + 'Bing Webmaster Tools export of keywords, pages, clicks and impressions.', + bingDocument + ], + [ + 'a summary naming the file columns', + 'summary', + 'Microsoft Clarity CSV export: sessions, users, scroll depth and browsers.', + clarityDocument + ], + [ + 'a terse dashboard summary', + 'summary', + 'Microsoft Clarity dashboard export: sessions, users, scroll depth and browsers.', + clarityDocument + ], + [ + 'a purpose naming the file columns', + 'purpose', + 'Search Console export of queries, clicks, impressions, CTR and position.', + gscDocument + ] + ])('keeps %s', (_label, field, value, documentText) => { + const input = { category: 'Bing exports', confidence: 90, [field]: value }; + expect(dropPromptEchoes(input, exportFolders, documentText)).toBe(input); + }); + + test('keeps reasoning that cites a folder description without document text', () => { + const input = { + category: 'Bing exports', + confidence: 90, + reasoning: + 'Contains Bing Webmaster Tools keywords, clicks and impressions from Bing search.' + }; + expect(dropPromptEchoes(input, exportFolders)).toBe(input); + }); + + test('still clears a description copied with no support in the document', () => { + const result = dropPromptEchoes( + { + category: 'SEO audits', + confidence: 90, + summary: 'PDF SEO audit reports with site scores, backlinks and recommendations.' + }, + exportFolders, + 'vacation-photos.txt\nPacking list for the beach trip: towels, sunscreen, snacks.' + ); + expect(result.summary).toBeNull(); + expect(result.confidence).toBe(50); + expect(result.promptEchoFields).toEqual(['summary']); + }); + + test('still clears a copied description when no document text is given', () => { + const result = dropPromptEchoes( + { + confidence: 90, + summary: 'Bing Webmaster Tools export of keywords, pages, clicks and impressions.' + }, + exportFolders + ); + expect(result.summary).toBeNull(); + expect(result.confidence).toBe(50); + }); + + test('still clears a copied schema instruction in the reasoning', () => { + const result = dropPromptEchoes( + { + confidence: 90, + reasoning: + 'Brief explanation of why this category was chosen based on the content and folder description.' + }, + exportFolders, + bingDocument + ); + expect(result.reasoning).toBeNull(); + expect(result.promptEchoFields).toEqual(['reasoning']); + }); + + test('does not let common document words hide a copied schema instruction', () => { + const result = dropPromptEchoes( + { confidence: 90, summary: "A concise 1-2 sentence summary of the document's content." }, + exportFolders, + 'Write a concise summary of the document content in 1 or 2 sentences.' + ); + expect(result.summary).toBeNull(); + }); + }); }); diff --git a/test/documentAnalysis.behavior.test.js b/test/documentAnalysis.behavior.test.js index 79fe1e0..7ae63f9 100644 --- a/test/documentAnalysis.behavior.test.js +++ b/test/documentAnalysis.behavior.test.js @@ -159,6 +159,25 @@ describe('documentAnalysis (behavior)', () => { ); }); + test('gives the prompt-echo guard the file name and extracted text', async () => { + const { dropPromptEchoes } = require('../src/main/analysis/utils'); + extractors.extractTextFromPdf.mockResolvedValue('Keyword,Clicks,Impressions'); + documentLlm.analyzeTextWithLlama.mockResolvedValue({ + summary: 'Keyword clicks and impressions', + category: 'Bing exports', + confidence: 90 + }); + const folders = [{ name: 'Bing exports', description: 'Bing keyword exports' }]; + + await analyzeDocumentFile('bing-keywords.pdf', folders); + + expect(dropPromptEchoes).toHaveBeenCalledWith( + expect.objectContaining({ category: 'Bing exports' }), + folders, + expect.stringMatching(/bing-keywords\.pdf[\s\S]*Keyword,Clicks,Impressions/) + ); + }); + test('uses OCR fallback when PDF extraction returns empty text', async () => { const filePath = 'scanned.pdf'; extractors.extractTextFromPdf.mockResolvedValue(''); // Empty result From 52f933543e8abfff4f09356775753c01a7592e52 Mon Sep 17 00:00:00 2001 From: Levy Tate <78818969+iLevyTate@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:13:34 -0500 Subject: [PATCH 4/6] fix(memory): the model budget uses available memory, and an Apple Silicon Mac is always Metal ModelMemoryManager budgeted 70% of os.freemem(), which on macOS counts only free pages, so without a VRAM figure a busy Mac got a budget of a few hundred MB and evicted models between files. It now uses the shared available-memory reading (unchanged on Windows and Linux). GPUMonitor returns Metal with unified memory on darwin/arm64 even when system_profiler fails or times out. --- src/main/services/GPUMonitor.js | 94 +++++++++----- src/main/services/ModelMemoryManager.js | 20 +-- test/GPUMonitor.test.js | 117 ++++++++++++++++++ ...ModelMemoryManager.availableMemory.test.js | 111 +++++++++++++++++ test/ModelMemoryManager.extended.test.js | 7 ++ 5 files changed, 313 insertions(+), 36 deletions(-) create mode 100644 test/ModelMemoryManager.availableMemory.test.js diff --git a/src/main/services/GPUMonitor.js b/src/main/services/GPUMonitor.js index 7babe85..7249451 100644 --- a/src/main/services/GPUMonitor.js +++ b/src/main/services/GPUMonitor.js @@ -1,6 +1,7 @@ // @ts-check // src/main/services/GPUMonitor.js +const os = require('os'); const { execFile } = require('child_process'); const { promisify } = require('util'); const { createLogger } = require('../../shared/logger'); @@ -84,6 +85,7 @@ const logger = createLogger('GPUMonitor'); class GPUMonitor { constructor() { this._platform = process.platform; + this._arch = process.arch; this._gpuInfo = null; this._detectPromise = null; } @@ -137,40 +139,74 @@ class GPUMonitor { } async _detectMacGPU() { + // Every arm64 Mac is Apple Silicon: a Metal GPU on memory it shares with + // the CPU. Keep that answer when system_profiler fails, times out during + // a busy start or names the GPU some other way. Reporting a CPU there left + // the model budget at 70% of free RAM, which macOS keeps at a few hundred + // MB on purpose, and models were evicted and reloaded for every file. + const appleSilicon = this._arch === 'arm64'; + let profiled = false; + /** @type {any} */ + let gpu = null; try { const output = await runCommand('system_profiler', ['SPDisplaysDataType', '-json']); - if (!output) return { type: 'cpu', name: 'CPU' }; - const data = JSON.parse(output); - const gpu = data.SPDisplaysDataType?.[0]; - - if (gpu?.sppci_model?.toLowerCase().includes('apple')) { - const memOutput = await runCommand('sysctl', ['hw.memsize']); - const totalMem = parseInt(memOutput?.split(':')[1]?.trim(), 10) || 0; - const vramEstimate = Math.round(totalMem * 0.75); - - return { - type: 'metal', - name: gpu.sppci_model, - vramBytes: vramEstimate, - vramMB: Math.round(vramEstimate / 1024 / 1024), - isAppleSilicon: true - }; + if (output) { + gpu = JSON.parse(output).SPDisplaysDataType?.[0]; + profiled = true; } - - const rawVram = String(gpu?.sppci_vram || ''); - const vramNum = parseInt(rawVram, 10) || 0; - const vramMB = /GB/i.test(rawVram) ? vramNum * 1024 : vramNum; - - return { - type: 'metal', - name: gpu?.sppci_model || 'Unknown GPU', - vramBytes: vramMB * 1024 * 1024, - vramMB, - isAppleSilicon: false - }; } catch { - return { type: 'cpu', name: 'CPU' }; + // Output that does not parse counts as no output. + profiled = false; } + + const model = typeof gpu?.sppci_model === 'string' ? gpu.sppci_model : ''; + if (appleSilicon || model.toLowerCase().includes('apple')) { + if (!model) { + logger.info('[GPU] system_profiler gave no GPU model; assuming the Apple Silicon GPU'); + } + return this._appleSiliconGPUInfo(model || 'Apple Silicon GPU'); + } + if (!profiled) return { type: 'cpu', name: 'CPU' }; + + const rawVram = String(gpu?.sppci_vram || ''); + const vramNum = parseInt(rawVram, 10) || 0; + const vramMB = /GB/i.test(rawVram) ? vramNum * 1024 : vramNum; + + return { + type: 'metal', + name: model || 'Unknown GPU', + vramBytes: vramMB * 1024 * 1024, + vramMB, + isAppleSilicon: false + }; + } + + /** + * Apple Silicon GPU info. Metal addresses the same memory as the CPU, so the + * "VRAM" figure is an estimate of 75% of total RAM. + * @private + * @param {string} name + * @returns {Promise>} + */ + async _appleSiliconGPUInfo(name) { + const memOutput = await runCommand('sysctl', ['hw.memsize']); + const parsedMem = parseInt( + String(memOutput || '') + .split(':')[1] + ?.trim() || '', + 10 + ); + // os.totalmem() reads the same hw.memsize through libuv. + const totalMem = parsedMem > 0 ? parsedMem : os.totalmem(); + const vramEstimate = Math.round(totalMem * 0.75); + + return { + type: 'metal', + name, + vramBytes: vramEstimate, + vramMB: Math.round(vramEstimate / 1024 / 1024), + isAppleSilicon: true + }; } async _detectWindowsGPU() { diff --git a/src/main/services/ModelMemoryManager.js b/src/main/services/ModelMemoryManager.js index 1e9a0e8..08d6311 100644 --- a/src/main/services/ModelMemoryManager.js +++ b/src/main/services/ModelMemoryManager.js @@ -12,6 +12,7 @@ const os = require('os'); const { createLogger } = require('../../shared/logger'); const { delay } = require('../../shared/promiseUtils'); +const { peekAvailableMemoryBytes } = require('../utils/systemMemory'); const logger = createLogger('ModelMemoryManager'); @@ -112,7 +113,7 @@ class ModelMemoryManager { * Calculate maximum memory we can use. * * Budget = max(ramBudget, vramBudget) where - * ramBudget = min(70% of free system RAM, 16 GiB) + * ramBudget = min(70% of available system RAM, 16 GiB) * vramBudget = 80% of reported VRAM (0 when no GPU info) * * On discrete GPUs (e.g. NVIDIA), models are GPU-offloaded into VRAM which is @@ -124,19 +125,24 @@ class ModelMemoryManager { * pool there, so the VRAM share is additionally capped at total RAM minus * UNIFIED_MEMORY_SYSTEM_RESERVE_BYTES; without the cap an 8 GB machine was * budgeted at 4.8 GB for models alone. + * + * "Available" comes from systemMemory: os.freemem() on Windows and Linux, + * where it already counts reclaimable caches, and the kernel's available + * figure on macOS, where os.freemem() counts only free pages and a busy Mac + * shows a few hundred MB. */ _calculateMaxMemory() { const totalMemory = os.totalmem(); - const freeMemory = os.freemem(); + const availableMemory = peekAvailableMemoryBytes(); - // System RAM budget: 70% of free, capped at 16GB - const ramBudget = Math.min(freeMemory * 0.7, 16 * 1024 * 1024 * 1024); + // System RAM budget: 70% of available, capped at 16GB + const ramBudget = Math.min(availableMemory * 0.7, 16 * 1024 * 1024 * 1024); let maxUsable = ramBudget; // When GPU info is available, use the larger of RAM and VRAM budgets. // On discrete GPUs, models are loaded into VRAM via GPU offload, so system - // RAM free-mem should not constrain the budget. + // RAM availability should not constrain the budget. if (this._gpuInfo?.vramMB && this._gpuInfo.vramMB > 0) { const vramBytes = this._gpuInfo.vramMB * 1024 * 1024; let vramBudget = Math.floor(vramBytes * 0.8); // 80% of VRAM @@ -157,7 +163,7 @@ class ModelMemoryManager { } else { logger.info('[Memory] Calculated max memory usage (no GPU VRAM info)', { totalGB: Math.round(totalMemory / 1024 / 1024 / 1024), - freeGB: Math.round(freeMemory / 1024 / 1024 / 1024), + availableGB: Math.round(availableMemory / 1024 / 1024 / 1024), maxUsableGB: Math.round(maxUsable / 1024 / 1024 / 1024) }); } @@ -166,7 +172,7 @@ class ModelMemoryManager { } /** - * Refresh the memory budget based on current free memory. + * Refresh the memory budget based on current available memory. * Called before load decisions to avoid using a stale snapshot from constructor time. */ _refreshMemoryBudget() { diff --git a/test/GPUMonitor.test.js b/test/GPUMonitor.test.js index a3f9726..944b993 100644 --- a/test/GPUMonitor.test.js +++ b/test/GPUMonitor.test.js @@ -161,6 +161,123 @@ describe('GPUMonitor', () => { expect(result.percentUsed).toBe(20); }); + describe('macOS detection', () => { + const os = require('os'); + const MiB = 1024 * 1024; + const expectedUnifiedVramMB = (totalBytes) => Math.round(Math.round(totalBytes * 0.75) / MiB); + + function macMonitor(arch) { + const monitor = new GPUMonitor(); + monitor._platform = 'darwin'; + monitor._arch = arch; + return monitor; + } + + test('Apple Silicon reads the model name and sizes VRAM at 75% of hw.memsize', async () => { + const monitor = macMonitor('arm64'); + mockExecFileAsync + .mockResolvedValueOnce({ + stdout: JSON.stringify({ SPDisplaysDataType: [{ sppci_model: 'Apple M4 Pro' }] }), + stderr: '' + }) + .mockResolvedValueOnce({ stdout: 'hw.memsize: 25769803776\n', stderr: '' }); + + const result = await monitor.detectGPU(); + + expect(result).toEqual({ + type: 'metal', + name: 'Apple M4 Pro', + vramBytes: 19327352832, + vramMB: 18432, + isAppleSilicon: true + }); + }); + + test('Apple Silicon stays Metal with unified VRAM when system_profiler fails or times out', async () => { + const monitor = macMonitor('arm64'); + // runCommand turns every rejection (including the timeout kill) into null. + mockExecFileAsync.mockRejectedValue(new Error('system_profiler timed out')); + + const result = await monitor.detectGPU(); + + expect(result).toEqual({ + type: 'metal', + name: 'Apple Silicon GPU', + vramBytes: Math.round(os.totalmem() * 0.75), + vramMB: expectedUnifiedVramMB(os.totalmem()), + isAppleSilicon: true + }); + expect(result.vramMB).toBeGreaterThan(0); + }); + + test('Apple Silicon keeps a GPU model name without "apple" in it', async () => { + const monitor = macMonitor('arm64'); + mockExecFileAsync + .mockResolvedValueOnce({ + stdout: JSON.stringify({ SPDisplaysDataType: [{ sppci_model: 'Integrated GPU' }] }), + stderr: '' + }) + .mockResolvedValueOnce({ stdout: 'hw.memsize: 17179869184\n', stderr: '' }); + + const result = await monitor.detectGPU(); + + expect(result).toEqual( + expect.objectContaining({ + type: 'metal', + name: 'Integrated GPU', + vramMB: 12288, + isAppleSilicon: true + }) + ); + }); + + test('an unreadable hw.memsize falls back to os.totalmem()', async () => { + const monitor = macMonitor('arm64'); + mockExecFileAsync + .mockResolvedValueOnce({ + stdout: JSON.stringify({ SPDisplaysDataType: [{ sppci_model: 'Apple M2' }] }), + stderr: '' + }) + .mockRejectedValueOnce(new Error('sysctl not found')); + + const result = await monitor.detectGPU(); + + expect(result.name).toBe('Apple M2'); + expect(result.vramMB).toBe(expectedUnifiedVramMB(os.totalmem())); + expect(result.vramMB).toBeGreaterThan(0); + }); + + test('an Intel Mac still reports a CPU when system_profiler fails', async () => { + const monitor = macMonitor('x64'); + mockExecFileAsync.mockRejectedValue(new Error('system_profiler timed out')); + + const result = await monitor.detectGPU(); + + expect(result).toEqual({ type: 'cpu', name: 'CPU' }); + expect(mockExecFileAsync).toHaveBeenCalledTimes(1); + }); + + test('an Intel Mac still reads a discrete GPU from system_profiler', async () => { + const monitor = macMonitor('x64'); + mockExecFileAsync.mockResolvedValueOnce({ + stdout: JSON.stringify({ + SPDisplaysDataType: [{ sppci_model: 'AMD Radeon Pro 5500M', sppci_vram: '8 GB' }] + }), + stderr: '' + }); + + const result = await monitor.detectGPU(); + + expect(result).toEqual({ + type: 'metal', + name: 'AMD Radeon Pro 5500M', + vramBytes: 8192 * MiB, + vramMB: 8192, + isAppleSilicon: false + }); + }); + }); + describe('child process options', () => { const { TIMEOUTS } = require('../src/shared/performanceConstants'); diff --git a/test/ModelMemoryManager.availableMemory.test.js b/test/ModelMemoryManager.availableMemory.test.js new file mode 100644 index 0000000..0052969 --- /dev/null +++ b/test/ModelMemoryManager.availableMemory.test.js @@ -0,0 +1,111 @@ +/** + * @jest-environment node + * + * The RAM half of the model budget follows AVAILABLE memory (systemMemory), + * not os.freemem(). On macOS os.freemem() counts only free pages: a busy + * 24 GB Mac reports about 400 MB, and without a GPU memory figure the whole + * model budget fell to 280 MB, so models were evicted and reloaded for every + * file. On Windows and Linux the figure is os.freemem() as before. + */ + +// isolateModules re-runs mock factories, so every copy shares these two. +const mockTotalmem = jest.fn(() => 24 * 1024 * 1024 * 1024); +const mockFreemem = jest.fn(() => 400 * 1024 * 1024); +jest.mock('os', () => ({ + totalmem: () => mockTotalmem(), + freemem: () => mockFreemem() +})); + +jest.mock('../src/shared/logger', () => ({ + createLogger: () => ({ info: jest.fn(), warn: jest.fn(), error: jest.fn(), debug: jest.fn() }) +})); + +// systemMemory probes `sysctl -n kern.memorystatus_level` on darwin. +const mockAsyncSpawn = jest.fn(); +jest.mock('../src/main/utils/asyncSpawnUtils', () => ({ + asyncSpawn: (...args) => mockAsyncSpawn(...args) +})); + +const MiB = 1024 * 1024; +const GiB = 1024 * MiB; + +const realPlatform = Object.getOwnPropertyDescriptor(process, 'platform'); + +/** + * Load ModelMemoryManager and the shared systemMemory reader fresh, as on a + * host of the given platform (the shared reader fixes its platform on first use). + */ +function loadOn(platform) { + Object.defineProperty(process, 'platform', { value: platform, configurable: true }); + let modules; + jest.isolateModules(() => { + modules = { + ModelMemoryManager: require('../src/main/services/ModelMemoryManager').ModelMemoryManager, + systemMemory: require('../src/main/utils/systemMemory') + }; + }); + return modules; +} + +function createMockLlamaService() { + return { _models: {}, _contexts: {}, _loadModel: jest.fn() }; +} + +describe('ModelMemoryManager budget uses available memory', () => { + beforeEach(() => { + mockAsyncSpawn.mockReset(); + }); + + afterEach(() => { + Object.defineProperty(process, 'platform', realPlatform); + }); + + test('on macOS without a GPU memory figure the budget follows the kernel available figure', async () => { + // 60% of 24 GiB available, while only 400 MB of pages are free. + mockAsyncSpawn.mockResolvedValue({ status: 0, stdout: '60\n' }); + const { ModelMemoryManager, systemMemory } = loadOn('darwin'); + + const manager = new ModelMemoryManager(createMockLlamaService()); + // The first reading has not landed yet; let it land, then refresh as + // every load decision does. + await systemMemory.getAvailableMemoryBytes(); + manager._refreshMemoryBudget(); + + const available = Math.round((24 * GiB * 60) / 100); + expect(manager._maxMemoryUsage).toBeCloseTo(available * 0.7, -1); + // Without the available figure: 0.7 x 400 MB = 280 MB. + expect(manager._maxMemoryUsage).toBeGreaterThan(10 * GiB); + expect(mockAsyncSpawn).toHaveBeenCalledWith( + '/usr/sbin/sysctl', + ['-n', 'kern.memorystatus_level'], + expect.anything() + ); + }); + + test('on macOS a GPU-less budget gets the same figure through setGpuInfo(null)', async () => { + mockAsyncSpawn.mockResolvedValue({ status: 0, stdout: '50\n' }); + const { ModelMemoryManager, systemMemory } = loadOn('darwin'); + await systemMemory.getAvailableMemoryBytes(); + + const manager = new ModelMemoryManager(createMockLlamaService()); + // LlamaService passes null after a Metal init falls back to the CPU. + manager.setGpuInfo(null); + + expect(manager._maxMemoryUsage).toBeCloseTo(12 * GiB * 0.7, -1); + }); + + test('on Windows the budget is still 70% of os.freemem() and nothing is spawned', () => { + mockFreemem.mockReturnValue(6 * GiB); + try { + const { ModelMemoryManager } = loadOn('win32'); + + const manager = new ModelMemoryManager(createMockLlamaService()); + manager._refreshMemoryBudget(); + + expect(manager._maxMemoryUsage).toBeCloseTo(6 * GiB * 0.7, -1); + expect(mockAsyncSpawn).not.toHaveBeenCalled(); + } finally { + mockFreemem.mockReturnValue(400 * MiB); + } + }); +}); diff --git a/test/ModelMemoryManager.extended.test.js b/test/ModelMemoryManager.extended.test.js index 0ff7f6f..dbf334d 100644 --- a/test/ModelMemoryManager.extended.test.js +++ b/test/ModelMemoryManager.extended.test.js @@ -26,6 +26,13 @@ jest.mock('../src/shared/logger', () => ({ }) })); +// The budget reads available memory through systemMemory, which asks the +// kernel on a macOS host. Route it to the mocked os.freemem() above so the +// budget figures below hold on every CI platform. +jest.mock('../src/main/utils/systemMemory', () => ({ + peekAvailableMemoryBytes: () => require('os').freemem() +})); + const { ModelMemoryManager } = require('../src/main/services/ModelMemoryManager'); function createMockLlamaService() { From df7f207b48c58bc30d7e9f989687f3dbd4bbdc7c Mon Sep 17 00:00:00 2001 From: Levy Tate <78818969+iLevyTate@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:13:37 -0500 Subject: [PATCH 5/6] fix(copy): Mac wording, readable MCP client names, accurate rule wording and the documented Zed config Finder instead of Explorer on a Mac; the Uncategorized access warning names the right OS setting; MCP copy confirmations name the app; the Advanced settings text drops "Save to apply"; Memory & Rules and the User Guide no longer say a typed rule applies to every file of that type; the Zed snippet drops the undocumented source key. --- docs/USER_GUIDE.md | 12 ++-- src/main/core/customFolders.js | 18 ++++- src/main/transports/mcp/configSnippets.js | 3 +- src/renderer/components/SettingsPanel.jsx | 2 +- .../organize/FeedbackMemoryPanel.jsx | 5 +- .../components/search/nodes/FolderNode.jsx | 13 +++- .../components/settings/McpServerSection.jsx | 9 ++- .../organize/useOrganizeNotificationFocus.js | 12 +++- test/components/FeedbackMemoryPanel.test.js | 7 +- test/components/FolderNode.test.js | 30 +++++++- test/components/McpServerSection.test.js | 32 ++++++++- test/components/SettingsPanel.test.js | 3 + test/customFolders.test.js | 34 +++++++++ test/unit/mcp/configSnippets.test.js | 15 ++-- test/useOrganizeNotificationFocus.test.js | 71 ++++++++++++++----- 15 files changed, 226 insertions(+), 40 deletions(-) diff --git a/docs/USER_GUIDE.md b/docs/USER_GUIDE.md index 3cc376b..d53df9b 100644 --- a/docs/USER_GUIDE.md +++ b/docs/USER_GUIDE.md @@ -106,8 +106,10 @@ folder for the next such file. Its card then gives the reason _You moved 2 simil Undoing those moves takes it back, and so does moving as many such files away from your folder when StratoSort suggests it. -To give a rule straight away, type it in **Settings > Performance > Memory & Rules** (see -[Performance](#performance)). +You can also type a rule in **Settings > Performance > Memory & Rules** (see +[Performance](#performance)). A rule moves its folder up for files of that type when that folder is +already one of the folders StratoSort considers for the file. It does not add a folder StratoSort +did not consider. For a firm change, make the two corrections described above. --- @@ -227,8 +229,10 @@ See [MCP_SERVER.md](MCP_SERVER.md). ### Performance - **Auto-organize**: Watch Downloads (and related routing). -- **Memory & Rules**: Type a rule such as "CSV files go to Reports" and it applies to every file of - that type. Your corrections are listed here too; edit or delete any that are wrong. +- **Memory & Rules**: Type a rule such as "CSV files go to Reports". It moves Reports up for CSV + files when Reports is already one of the folders StratoSort considers for them. Two corrections + teach a firm change (see [Teaching StratoSort](#teaching-stratosort)). Your corrections are listed + here too; edit or delete any that are wrong. - **Background Mode**: Keep running in the tray. - **Exclusion rules**: Skip paths or patterns from watchers and triage. - **Processing limits** and **Search enrichment** (relationship expansion and the relationship index diff --git a/src/main/core/customFolders.js b/src/main/core/customFolders.js index 4f39ea2..e443c1c 100644 --- a/src/main/core/customFolders.js +++ b/src/main/core/customFolders.js @@ -115,6 +115,22 @@ async function probeFolder(op, label) { } } +/** + * What to tell the user when the Uncategorized folder cannot be created: the + * setting that most often blocks it on this OS. + * @param {NodeJS.Platform} [platform] + * @returns {string} + */ +function uncategorizedAccessHint(platform = process.platform) { + if (platform === 'win32') { + return "If Windows Security's Controlled folder access is on, allow StratoSort Stack through it."; + } + if (platform === 'darwin') { + return 'Check that StratoSort Stack is allowed in System Settings > Privacy & Security > Files and Folders.'; + } + return 'Check that you can write to that folder.'; +} + /** * Create the directory for a new or healed Uncategorized entry. Never throws, * and the entry always keeps `preferredPath`. @@ -157,7 +173,7 @@ async function createUncategorizedDirectory(preferredPath) { code: 'storage.uncategorized-unavailable', subsystem: 'storage', severity: 'warning', - message: `StratoSort could not create the Uncategorized folder at ${preferredPath}, so files that match no smart folder cannot be moved there. If Windows Security's Controlled folder access is on, allow StratoSort Stack through it.`, + message: `StratoSort could not create the Uncategorized folder at ${preferredPath}, so files that match no smart folder cannot be moved there. ${uncategorizedAccessHint()}`, detail: { path: preferredPath, code: created.error?.code } }); } catch { diff --git a/src/main/transports/mcp/configSnippets.js b/src/main/transports/mcp/configSnippets.js index b17ba0b..441cf5f 100644 --- a/src/main/transports/mcp/configSnippets.js +++ b/src/main/transports/mcp/configSnippets.js @@ -28,7 +28,8 @@ function generateSnippet(client, { port, token }) { case 'zed': return JSON.stringify( { - context_servers: { stratosort: { source: 'http', url, headers: { Authorization: auth } } } + // Zed's documented remote shape: only url and headers. + context_servers: { stratosort: { url, headers: { Authorization: auth } } } }, null, 2 diff --git a/src/renderer/components/SettingsPanel.jsx b/src/renderer/components/SettingsPanel.jsx index c91a536..7ec1243 100644 --- a/src/renderer/components/SettingsPanel.jsx +++ b/src/renderer/components/SettingsPanel.jsx @@ -1637,7 +1637,7 @@ const SettingsPanel = React.memo(function SettingsPanel() { {isSimpleMode ? 'Simple mode hides the advanced configuration panels and uses a streamlined retrieval path, while still embedding your files on-device in the background — so nothing needs re-processing if you switch to Advanced later.' - : 'Advanced reveals every configuration panel — AI models, semantic search, chat-with-documents, and the knowledge graph — and enables graph-aware retrieval at search time. Save to apply.'} + : 'Advanced reveals every configuration panel — AI models, semantic search, chat-with-documents, and the knowledge graph — and enables graph-aware retrieval at search time.'} diff --git a/src/renderer/components/organize/FeedbackMemoryPanel.jsx b/src/renderer/components/organize/FeedbackMemoryPanel.jsx index 2fabfac..52cc820 100644 --- a/src/renderer/components/organize/FeedbackMemoryPanel.jsx +++ b/src/renderer/components/organize/FeedbackMemoryPanel.jsx @@ -105,8 +105,9 @@ function FeedbackMemoryPanel({ className = '', refreshToken }) { Rules and notes that adjust future suggestions. A rule like “CSV files go to - Bing” applies to every file of that type. Your corrections and folder descriptions are - listed here too. Edit or delete any that are wrong. + Bing” moves that folder up for files of that type when it is already one of the + folders StratoSort considers for them. Your corrections and folder descriptions are listed + here too. Edit or delete any that are wrong.
diff --git a/src/renderer/components/search/nodes/FolderNode.jsx b/src/renderer/components/search/nodes/FolderNode.jsx index bdff72a..4960e7d 100644 --- a/src/renderer/components/search/nodes/FolderNode.jsx +++ b/src/renderer/components/search/nodes/FolderNode.jsx @@ -6,6 +6,14 @@ import { IconButton } from '../../ui'; import { useAppSelector } from '../../../store/hooks'; import { selectSmartFolders } from '../../../store/selectors'; import { resolveSmartFolderPath } from '../utils/graphLayoutUtils'; +import { isMac, isWindows } from '../../../utils/platform'; + +// Named after what the OS calls the window the folder opens in. +function revealFolderLabel() { + if (isMac) return 'Reveal folder in Finder'; + if (isWindows) return 'Reveal folder in File Explorer'; + return 'Reveal folder in file manager'; +} const FolderNode = memo(({ data, selected }) => { const label = data?.label || 'Suggested folder'; @@ -15,6 +23,7 @@ const FolderNode = memo(({ data, selected }) => { // its path on disk. Empty when the name matches no configured smart folder. const smartFolders = useAppSelector(selectSmartFolders); const folderPath = resolveSmartFolderPath(smartFolders, data?.label); + const revealLabel = revealFolderLabel(); const dispatchFolderAction = useCallback( (action) => { @@ -80,8 +89,8 @@ const FolderNode = memo(({ data, selected }) => { icon={} size="xs" variant="ghost" - title="Reveal folder in Explorer" - aria-label="Reveal folder in Explorer" + title={revealLabel} + aria-label={revealLabel} onClick={handleReveal} />
diff --git a/src/renderer/components/settings/McpServerSection.jsx b/src/renderer/components/settings/McpServerSection.jsx index 9a30dc6..063dcc9 100644 --- a/src/renderer/components/settings/McpServerSection.jsx +++ b/src/renderer/components/settings/McpServerSection.jsx @@ -33,6 +33,13 @@ const TOOLS = [ { name: 'list_smart_folders', desc: 'List your smart folders and where they are.' } ]; +// Names users know the clients by; the keys are the ids main expects. +const CLIENT_NAMES = { + claudeDesktop: 'Claude Desktop', + cursor: 'Cursor', + zed: 'Zed' +}; + // Plain words for the lifecycle states; 'running' shows the address instead. const STATUS_TEXT = { starting: 'Starting…', @@ -81,7 +88,7 @@ function McpServerSection({ addNotification }) { const result = await dispatch(getConfigSnippet(client)).unwrap(); const snippet = result?.snippet || ''; await navigator.clipboard.writeText(snippet); - addNotification?.(`Copied ${client} snippet.`, 'success'); + addNotification?.(`Copied ${CLIENT_NAMES[client] || 'MCP'} config.`, 'success'); } catch (err) { addNotification?.(err.message, 'error'); } diff --git a/src/renderer/phases/organize/useOrganizeNotificationFocus.js b/src/renderer/phases/organize/useOrganizeNotificationFocus.js index c68e611..da49f42 100644 --- a/src/renderer/phases/organize/useOrganizeNotificationFocus.js +++ b/src/renderer/phases/organize/useOrganizeNotificationFocus.js @@ -4,13 +4,21 @@ import { useAppDispatch, useAppSelector } from '../../store/hooks'; import { clearOrganizeFocus } from '../../store/slices/uiSlice'; import { findFileByPathOrName, findFileIndexByPathOrName } from '../../utils/findFileInList'; import { toCanonicalPath } from '../../utils/canonicalPath'; +import { isMac, isWindows } from '../../utils/platform'; import { createLogger } from '../../../shared/logger'; const logger = createLogger('OrganizeNotificationFocus'); +/** What the OS calls the window a revealed file is shown in. */ +function fileManagerName() { + if (isMac) return 'Finder'; + if (isWindows) return 'File Explorer'; + return 'your file manager'; +} + /** * When the user clicks a download/watcher notification, jump to the matching - * file in Organize (scroll + select + details), or reveal it in Explorer. + * file in Organize (scroll + select + details), or reveal it in the file manager. */ /** * @param {{ unprocessedFiles: any[], processedFiles: any[], setSelectedFiles: Function, setFocusFileIndex: Function, setViewingFileDetails: Function, setShowHistoryModal: Function, addNotification: Function, revealFile: Function }} args @@ -117,7 +125,7 @@ export function useOrganizeNotificationFocus({ await reveal(filePath); if (!cancelled) { addNotificationRef.current( - fileName ? `Opened ${fileName} in Explorer` : 'Opened file in Explorer', + `Opened ${fileName || 'file'} in ${fileManagerName()}`, 'info', 3500 ); diff --git a/test/components/FeedbackMemoryPanel.test.js b/test/components/FeedbackMemoryPanel.test.js index bde7906..4183656 100644 --- a/test/components/FeedbackMemoryPanel.test.js +++ b/test/components/FeedbackMemoryPanel.test.js @@ -76,7 +76,12 @@ describe('FeedbackMemoryPanel', () => { test('says what a rule does without promising more', async () => { render(); - expect(await screen.findByText(/applies to every file of that type/)).toBeInTheDocument(); + expect( + await screen.findByText( + /moves that folder up for files of that type when it is already one of the folders StratoSort considers for them/ + ) + ).toBeInTheDocument(); + expect(screen.queryByText(/applies to every file/)).not.toBeInTheDocument(); expect(screen.queryByText(/follow these/)).not.toBeInTheDocument(); }); }); diff --git a/test/components/FolderNode.test.js b/test/components/FolderNode.test.js index 31a03ba..b0f49c2 100644 --- a/test/components/FolderNode.test.js +++ b/test/components/FolderNode.test.js @@ -29,6 +29,17 @@ jest.mock('../../src/renderer/components/ui', () => ({ ) })); +// Read at render time, so each test can pick the platform. +const mockPlatform = { isMac: false, isWindows: true }; +jest.mock('../../src/renderer/utils/platform', () => ({ + get isMac() { + return mockPlatform.isMac; + }, + get isWindows() { + return mockPlatform.isWindows; + } +})); + const mockSmartFolders = [ { id: 'sf-1', name: 'Invoices/2025', path: 'C:\\Docs\\Invoices\\2025' }, { id: 'sf-2', name: 'Receipts', path: 'C:\\Docs\\Receipts' } @@ -134,11 +145,28 @@ describe('FolderNode keyboard affordances', () => { render(); fireEvent.click(screen.getByRole('button', { name: /Move connected files here/i })); - fireEvent.click(screen.getByRole('button', { name: /Reveal folder in Explorer/i })); + fireEvent.click(screen.getByRole('button', { name: 'Reveal folder in File Explorer' })); expect(handler).toHaveBeenCalledTimes(2); expect(handler.mock.calls[0][0].detail.action).toBe('moveFilesHere'); expect(handler.mock.calls[1][0].detail.action).toBe('reveal'); window.removeEventListener('graph:folderAction', handler); }); + + describe('reveal button names the platform file manager', () => { + afterEach(() => { + Object.assign(mockPlatform, { isMac: false, isWindows: true }); + }); + + test.each([ + ['Windows', { isMac: false, isWindows: true }, 'Reveal folder in File Explorer'], + ['macOS', { isMac: true, isWindows: false }, 'Reveal folder in Finder'], + ['Linux', { isMac: false, isWindows: false }, 'Reveal folder in file manager'] + ])('on %s', (_name, platform, label) => { + Object.assign(mockPlatform, platform); + render(); + expect(screen.getByRole('button', { name: label })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /in Explorer$/ })).not.toBeInTheDocument(); + }); + }); }); diff --git a/test/components/McpServerSection.test.js b/test/components/McpServerSection.test.js index 2690342..1f852c0 100644 --- a/test/components/McpServerSection.test.js +++ b/test/components/McpServerSection.test.js @@ -228,7 +228,37 @@ describe('McpServerSection', () => { fireEvent.click(copyButton); await waitFor(() => { expect(navigator.clipboard.writeText).toHaveBeenCalledWith('claudeDesktop-snippet'); - expect(addNotification).toHaveBeenCalledWith('Copied claudeDesktop snippet.', 'success'); + expect(addNotification).toHaveBeenCalledWith('Copied Claude Desktop config.', 'success'); + }); + }); + + test.each([ + ['Copy Cursor config', 'cursor', 'Copied Cursor config.'], + ['Copy Zed config', 'zed', 'Copied Zed config.'] + ])('"%s" confirms with the client name, not its id', async (buttonName, id, message) => { + const addNotification = jest.fn(); + const store = configureStore({ + reducer: { mcp: mcpReducer }, + preloadedState: { + mcp: { + enabled: true, + status: 'running', + port: 53827, + tokenMasked: 'test', + lastError: null, + isWorking: false + } + } + }); + render( + + + + ); + fireEvent.click(screen.getByRole('button', { name: buttonName })); + await waitFor(() => { + expect(navigator.clipboard.writeText).toHaveBeenCalledWith(`${id}-snippet`); + expect(addNotification).toHaveBeenCalledWith(message, 'success'); }); }); diff --git a/test/components/SettingsPanel.test.js b/test/components/SettingsPanel.test.js index eb45ba7..b20322b 100644 --- a/test/components/SettingsPanel.test.js +++ b/test/components/SettingsPanel.test.js @@ -700,6 +700,9 @@ describe('SettingsPanel regression guards', () => { expect(screen.getByText('Processing Limits Section')).toBeInTheDocument(); expect(screen.getByText('Graph Retrieval Section')).toBeInTheDocument(); expect(screen.getByText('Diagnostics Logs Section')).toBeInTheDocument(); + // Settings save automatically, so the mode text must not ask for a save. + expect(screen.getByText(/^Advanced reveals every configuration panel/)).toBeInTheDocument(); + expect(screen.queryByText(/Save to apply/)).not.toBeInTheDocument(); }); test('warns instead of reporting success when a vision model installs without its projector', async () => { diff --git a/test/customFolders.test.js b/test/customFolders.test.js index b56d685..a1ead89 100644 --- a/test/customFolders.test.js +++ b/test/customFolders.test.js @@ -860,6 +860,40 @@ describe('Custom Folders', () => { ); }); + describe.each([ + ['win32', /Windows Security's Controlled folder access/], + ['darwin', /System Settings > Privacy & Security > Files and Folders/], + ['linux', /Check that you can write to that folder\./] + ])('the unwritable-Documents warning on %s', (platform, hint) => { + const realPlatform = Object.getOwnPropertyDescriptor(process, 'platform'); + + afterEach(() => { + Object.defineProperty(process, 'platform', realPlatform); + }); + + test('names the setting for that OS only', async () => { + Object.defineProperty(process, 'platform', { ...realPlatform, value: platform }); + const eacces = Object.assign(new Error('EACCES: permission denied'), { code: 'EACCES' }); + mockFs.mkdir.mockImplementation(async (dir) => { + if (String(dir).startsWith('/mock/documents')) throw eacces; + }); + + await customFolders.loadCustomFolders(); + + const flag = require('../src/main/services/DegradedStateTracker') + .getInstance() + .list() + .find((f) => f.code === 'storage.uncategorized-unavailable'); + expect(flag.message).toMatch(hint); + if (platform !== 'win32') { + expect(flag.message).not.toMatch(/Windows|Controlled folder access/); + } + if (platform !== 'darwin') { + expect(flag.message).not.toMatch(/System Settings/); + } + }); + }); + test('a saved Documents path that still cannot be created is retried and flagged on every launch', async () => { const eperm = Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' }); const enoent = Object.assign(new Error('ENOENT'), { code: 'ENOENT' }); diff --git a/test/unit/mcp/configSnippets.test.js b/test/unit/mcp/configSnippets.test.js index 037d033..4a4bdd2 100644 --- a/test/unit/mcp/configSnippets.test.js +++ b/test/unit/mcp/configSnippets.test.js @@ -17,10 +17,17 @@ describe('configSnippets', () => { expect(s).toContain('"http://127.0.0.1:53827/mcp"'); }); - test('zed returns expected shape', () => { - const s = generateSnippet('zed', ctx); - expect(s).toContain('context_servers'); - expect(s).toContain('stratosort'); + test("zed returns Zed's documented remote shape: url and headers only", () => { + const parsed = JSON.parse(generateSnippet('zed', ctx)); + expect(parsed).toEqual({ + context_servers: { + stratosort: { + url: 'http://127.0.0.1:53827/mcp', + headers: { Authorization: `Bearer ${ctx.token}` } + } + } + }); + expect(parsed.context_servers.stratosort).not.toHaveProperty('source'); }); test('throws on unknown client', () => { diff --git a/test/useOrganizeNotificationFocus.test.js b/test/useOrganizeNotificationFocus.test.js index cacf082..8c2f2fe 100644 --- a/test/useOrganizeNotificationFocus.test.js +++ b/test/useOrganizeNotificationFocus.test.js @@ -23,6 +23,17 @@ jest.mock('../src/renderer/store/hooks', () => ({ }) })); +// Read at call time, so each test can pick the platform. +const mockPlatform = { isMac: false, isWindows: true }; +jest.mock('../src/renderer/utils/platform', () => ({ + get isMac() { + return mockPlatform.isMac; + }, + get isWindows() { + return mockPlatform.isWindows; + } +})); + jest.mock('../src/renderer/store/slices/uiSlice', () => ({ clearOrganizeFocus: jest.fn(() => ({ type: 'ui/clearOrganizeFocus' })) })); @@ -115,29 +126,51 @@ describe('useOrganizeNotificationFocus', () => { expect(mockDispatch).toHaveBeenCalledWith({ type: 'ui/clearOrganizeFocus' }); }); - test('reveals file in Explorer when not in organize lists', async () => { - mockOrganizeFocusRequest = { - filePath: '/downloads/new.pdf', - fileName: 'new.pdf', - openDetails: true, - requestedAt: 3000 - }; + describe.each([ + ['Windows', { isMac: false, isWindows: true }, 'File Explorer'], + ['macOS', { isMac: true, isWindows: false }, 'Finder'], + ['Linux', { isMac: false, isWindows: false }, 'your file manager'] + ])('on %s', (_name, platform, fileManager) => { + beforeEach(() => { + Object.assign(mockPlatform, platform); + }); - window.electronAPI = { - analysisHistory: { - getFileHistory: jest.fn().mockResolvedValue([]) - } - }; + afterEach(() => { + Object.assign(mockPlatform, { isMac: false, isWindows: true }); + delete window.electronAPI; + }); + + test(`reveals a file not in the organize lists and names ${fileManager}`, async () => { + mockOrganizeFocusRequest = { + filePath: '/downloads/new.pdf', + fileName: 'new.pdf', + openDetails: true, + requestedAt: 3000 + }; - const { revealFile, addNotification } = renderFocusHook(); + window.electronAPI = { + analysisHistory: { + getFileHistory: jest.fn().mockResolvedValue([]) + } + }; - await waitFor(() => { - expect(revealFile).toHaveBeenCalledWith('/downloads/new.pdf'); - }); - expect(addNotification).toHaveBeenCalledWith('Opened new.pdf in Explorer', 'info', 3500); - expect(mockDispatch).toHaveBeenCalledWith({ type: 'ui/clearOrganizeFocus' }); + const { revealFile, addNotification } = renderFocusHook(); - delete window.electronAPI; + await waitFor(() => { + expect(revealFile).toHaveBeenCalledWith('/downloads/new.pdf'); + }); + expect(addNotification).toHaveBeenCalledWith( + `Opened new.pdf in ${fileManager}`, + 'info', + 3500 + ); + expect(addNotification).not.toHaveBeenCalledWith( + expect.stringMatching(/in Explorer$/), + expect.anything(), + expect.anything() + ); + expect(mockDispatch).toHaveBeenCalledWith({ type: 'ui/clearOrganizeFocus' }); + }); }); test('ignores duplicate focus requests with the same requestedAt', () => { From cf3d86ef689ac06bc198ae2dfa736343414ec2fd Mon Sep 17 00:00:00 2001 From: Levy Tate <78818969+iLevyTate@users.noreply.github.com> Date: Sat, 14 Nov 2026 14:13:42 -0500 Subject: [PATCH 6/6] docs(changelog): add the final-review fixes to 5.3.0 --- CHANGELOG.md | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index d202dce..0d33425 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,44 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Fixed +- **Two files given the same new name no longer stop the whole Move.** Two exports from the same + day, for example, could both be renamed to the same name in the same folder, and Organize refused + the run with "Cannot organize: 2 files have destination conflicts". The second file now gets a + number (`_1`), as it does when a file of that name is already in the folder, and Preview marks it + "Name taken — number added". If files still clash, the message lists their own names, not the + shared new name. +- **Correcting a file whose AI label already named the right folder now teaches StratoSort.** When + the label was right but the ranking put another folder first, the correction was saved without the + label, so two such corrections never changed later suggestions. +- **A short, accurate summary that uses a Smart Folder description's words is no longer erased.** It + was taken for a copy of the description: the summary or reason was removed, the confidence was cut + to 50% and the file could be held for review. Words that also appear in the file no longer count + as copied, and the reason may cite the folder's description, as the analysis asks it to. Real + copies of a description or of the instructions are still caught. +- **A label that paraphrases a folder name no longer goes to whichever folder was added first.** + With folders such as "GSC exports" and "Bing exports", a label like "Google Search Console + exports" matched every folder on the shared word "exports", and the first folder in the list won. + Words that several folder names share are now ignored, and a tie is decided by the folder + descriptions. +- **On a Mac, models are no longer unloaded and loaded again between files when the GPU check gives + no answer.** The model memory budget was based on free memory pages only, which macOS keeps low, + so a busy Mac could get a budget of a few hundred MB. It now uses the memory macOS reports as + available, and an Apple Silicon Mac is always treated as having its Metal GPU. +- **A Move the app refuses as a whole now says why.** When another run was still in progress, or the + batch was too large, the app said only "Check the logs for details" and listed every file as if + the run had ended before it. The reason is now shown in the run summary and on each file. +- **A card whose folder you changed no longer shows a confidence score.** The score was for + StratoSort's own choice, so beside your choice it looked like the app agreed with it. +- **On a Mac, messages name Finder instead of Explorer,** and a warning that the Uncategorized + folder could not be created points to System Settings > Privacy & Security instead of Windows + Security. The MCP copy buttons confirm with the app's name (Claude Desktop, Cursor, Zed) instead + of an internal id, and the Advanced settings text no longer says "Save to apply", since settings + save automatically. +- **Memory & Rules no longer says a typed rule applies to every file of that type.** A rule moves + its folder up when StratoSort already considers that folder for a file; two corrections teach a + firm change. The User Guide says the same. +- **The Zed MCP config matches the format in Zed's documentation.** It no longer includes a + `"source": "http"` entry. - **Two identical files in one folder are no longer both sent to the trash when one run renames or moves them.** Each was taken for a copy of the other that was already in place, so both were removed instead of moved, and the run could then fail and be undone with the two files missing