Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

feat(ui): editor remembers recent folders and files (#836)

Call Whited9248e121c8a
diff --git a/ui/src/components/workbench/EditorApp.tsx b/ui/src/components/workbench/EditorApp.tsx
index dde694933..25e6a078a 100644
--- a/ui/src/components/workbench/EditorApp.tsx
+++ b/ui/src/components/workbench/EditorApp.tsx
@@ -5,8 +5,9 @@ import clsx from 'clsx';
import { useWindowCloseGuard, useWindowManager, useWindowState } from '../../context/WindowManagerContext';
import { MAX_RESTORED_TABS, WINDOW_RESTORE_PARAM } from '../../lib/workbenchPersistence';
-import { contentUrl, downloadFile, fileMeta, joinPath, parentDir, writeFile, type FsEntry } from '../../lib/filesApi';
+import { FilesApiError, contentUrl, downloadFile, fileMeta, joinPath, parentDir, writeFile, type FsEntry } from '../../lib/filesApi';
import { isEditableFile, isEditableMeta, previewOverlayKind, previewRenderKind } from '../../lib/filePreview';
+import { forgetRecentFile, loadEditorRecents, recentPathLabel, rememberRecentFile, rememberRecentFolder, removeRecentFile, type EditorRecents, type RecentFile } from '../../lib/editorRecents';
import { FileTree } from './FileTree';
import { FilePreview } from '../ui/file-preview';
import { FilePicker, type FilePickerMode } from './FilePicker';
@@ -59,9 +60,16 @@ type PickerState = {
mode: FilePickerMode;
initialPath: string | null;
defaultName?: string;
+ // Recent explorer roots, surfaced as quick nav entries in the picker's rail. Captured when the
+ // picker opens (a snapshot) rather than read live, so it stays a plain value.
+ recentFolders?: string[];
onConfirm: (result: { path: string; name?: string }) => Promise<void> | void;
};
+// Outcome of opening a welcome "Recent" file: it opened, it's provably gone (drop the row), or it
+// couldn't be reached right now (leave the row — it may still exist).
+type RecentOpenResult = 'opened' | 'gone' | 'unavailable';
+
// Human language label for the status bar (design dnYPx shows e.g. "TypeScript React").
const LANGUAGE_LABEL: Record<string, string> = {
ts: 'TypeScript',
@@ -154,6 +162,10 @@ export const EditorApp: React.FC<{
const openFile = useCallback(
(path: string, name: string, mtime: number | null, target?: { line: number; column: number; endColumn: number }) => {
+ // Record the recent file here — the single chokepoint every real open flows through (tree,
+ // search jump, launch param). Session RESTORE deliberately rebuilds tabs without calling this,
+ // so a reload doesn't re-stamp restored files as freshly opened.
+ rememberRecentFile(path, name);
setRoot((r) => r ?? parentDir(path));
if (!target) setCursor(null);
setTabs((ts) => {
@@ -179,6 +191,7 @@ export const EditorApp: React.FC<{
// Open (or focus) a rich file (raster image / PDF / Office doc) as a read-only preview tab (no
// Monaco). Dedups by path inside the updater so a fast double-open can't append two tabs.
const openPreview = useCallback((path: string, name: string) => {
+ rememberRecentFile(path, name); // same chokepoint as openFile; restore bypasses both
setRoot((r) => r ?? parentDir(path));
setTabs((ts) => {
const existing = ts.find((x) => x.path === path);
@@ -371,13 +384,17 @@ export const EditorApp: React.FC<{
const dir = typeof params?.newFileDir === 'string' ? params.newFileDir : null;
if (dir) {
setRoot(dir);
+ rememberRecentFolder(dir);
newFile();
return;
}
// "Open in Editor" from a project (sidebar): root the explorer at the folder with NO tab open —
// just the file tree + the select-a-file hint, no untitled buffer.
const rootDir = typeof params?.rootDir === 'string' ? params.rootDir : null;
- if (rootDir) setRoot(rootDir);
+ if (rootDir) {
+ setRoot(rootDir);
+ rememberRecentFolder(rootDir);
+ }
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
@@ -433,8 +450,10 @@ export const EditorApp: React.FC<{
setPicker({
mode: 'open-directory',
initialPath: root,
+ recentFolders: loadEditorRecents().folders,
onConfirm: ({ path }) => {
setRoot(path);
+ rememberRecentFolder(path);
setPicker(null);
},
});
@@ -456,11 +475,13 @@ export const EditorApp: React.FC<{
setPicker({
mode: 'save-file',
initialPath: root,
+ recentFolders: loadEditorRecents().folders,
onConfirm: async ({ path, name }) => {
const full = joinPath(path, name as string);
const result = await writeFile(full, text, undefined, true);
setTabs((ts) => ts.map((x) => (x.id === tabId ? { ...x, path: full, name: name as string, mtime: result.mtime } : x)));
setRoot((r) => r ?? path);
+ rememberRecentFile(full, name as string);
// Re-list the folder the new file landed in, so it appears in the explorer tree.
setTreeRefresh({ path, nonce: ++treeRefreshSeq.current });
setPicker(null);
@@ -470,6 +491,34 @@ export const EditorApp: React.FC<{
[root],
);
+ // Open a folder from the welcome "Recent" list: root the explorer there directly (no picker) and
+ // bump it to the front of the recents.
+ const openRecentFolder = useCallback((path: string) => {
+ setRoot(path);
+ rememberRecentFolder(path);
+ }, []);
+
+ // Open a file from the welcome "Recent" list. Fetch fresh metadata, exactly like every other open
+ // path (routing to preview tab / Monaco / download by the same gate as onTreeOpen). The result
+ // tells the caller how to treat the row: only a definitive 'gone' (the path no longer resolves,
+ // 404) drops the entry — a transient/permission/other failure leaves it in place (the file may
+ // well still exist) and simply doesn't open, so recent history isn't lost to a network blip.
+ const openRecentFile = useCallback(
+ async (file: RecentFile): Promise<RecentOpenResult> => {
+ let m: Awaited<ReturnType<typeof fileMeta>>;
+ try {
+ m = await fileMeta(file.path);
+ } catch (e) {
+ return e instanceof FilesApiError && e.code === 'not_found' ? 'gone' : 'unavailable';
+ }
+ if (previewOverlayKind(m)) openPreview(file.path, file.name);
+ else if (isEditableMeta(m)) openFile(file.path, file.name, m.mtime);
+ else downloadFile(file.path);
+ return 'opened';
+ },
+ [openFile, openPreview],
+ );
+
// ⌘O Open Folder · ⌘N New File — only while THIS editor window holds focus (several windows can
// be open). Capture phase + preventDefault so ⌘O doesn't fall through to the browser's open dialog.
useEffect(() => {
@@ -646,7 +695,7 @@ export const EditorApp: React.FC<{
select-a-file hint (folder open, no tab). */}
<div className="flex min-w-0 flex-1 flex-col bg-surface">
{showWelcome ? (
- <Welcome onOpenFolder={openFolder} onNewFile={newFile} />
+ <Welcome onOpenFolder={openFolder} onNewFile={newFile} onOpenRecentFolder={openRecentFolder} onOpenRecentFile={openRecentFile} />
) : (
<>
{tabs.length > 0 && (
@@ -750,6 +799,7 @@ export const EditorApp: React.FC<{
mode={picker.mode}
initialPath={picker.initialPath}
defaultName={picker.defaultName}
+ recentFolders={picker.recentFolders}
onCancel={() => setPicker(null)}
onConfirm={picker.onConfirm}
/>
@@ -758,15 +808,37 @@ export const EditorApp: React.FC<{
);
};
-const Welcome: React.FC<{ onOpenFolder: () => void; onNewFile: () => void }> = ({ onOpenFolder, onNewFile }) => {
+const Welcome: React.FC<{
+ onOpenFolder: () => void;
+ onNewFile: () => void;
+ onOpenRecentFolder: (path: string) => void;
+ /** Opens a recent file; the caller drops the row only when it resolves 'gone'. */
+ onOpenRecentFile: (file: RecentFile) => Promise<RecentOpenResult>;
+}> = ({ onOpenFolder, onNewFile, onOpenRecentFolder, onOpenRecentFile }) => {
const { t } = useTranslation();
+ // Read fresh on mount: the store is shared by every editor window + the full-page route (last
+ // write wins), and the welcome only mounts when nothing is open — so no live subscription is
+ // needed. Kept in state only so a 404'd file can be dropped from the view below.
+ const [recents, setRecents] = useState<EditorRecents>(() => loadEditorRecents());
const actions: { Icon: typeof FolderOpen; color: string; label: string; onClick: () => void; sc?: string }[] = [
{ Icon: FolderOpen, color: 'text-cyan', label: t('apps.editor.openFolder'), onClick: onOpenFolder, sc: '⌘O' },
{ Icon: FilePlus, color: 'text-mint', label: t('apps.fileBrowser.newFile'), onClick: onNewFile, sc: '⌘N' },
];
+ const hasRecents = recents.folders.length > 0 || recents.files.length > 0;
+
+ // Opening a recent file that's provably gone drops just that row — from the view and the store —
+ // showing nothing else. An 'unavailable' (transient/permission) result leaves the row untouched.
+ // Folder clicks always root the explorer, which unmounts this screen.
+ const openRecentFile = async (file: RecentFile) => {
+ if ((await onOpenRecentFile(file)) === 'gone') {
+ forgetRecentFile(file.path);
+ setRecents((r) => removeRecentFile(r, file.path));
+ }
+ };
+
return (
<div className="grid min-w-0 flex-1 place-items-center bg-surface p-10">
- <div className="flex w-[440px] max-w-full flex-col gap-6">
+ <div className="flex max-h-full w-[440px] max-w-full flex-col gap-6 overflow-y-auto">
<div className="flex items-center gap-3.5">
<span className="grid size-14 place-items-center rounded-2xl border border-cyan/60 bg-cyan-soft">
<CodeXml className="size-7 text-cyan" />
@@ -788,10 +860,32 @@ const Welcome: React.FC<{ onOpenFolder: () => void; onNewFile: () => void }> = (
))}
</div>
<div className="font-mono text-[11px] font-bold uppercase tracking-[0.1em] text-muted">{t('apps.editor.recent')}</div>
- <div className="flex items-center gap-2 text-[12.5px] text-muted">
- <Clock className="size-3.5" /> {t('apps.editor.noRecent')}
- </div>
+ {hasRecents ? (
+ // Folders first, then files — each a compact row: name + its containing directory (dimmed).
+ <div className="flex flex-col gap-0.5">
+ {recents.folders.map((path) => (
+ <RecentRow key={`d:${path}`} Icon={FolderOpen} iconColor="text-cyan" name={recentPathLabel(path)} dir={parentDir(path)} onClick={() => onOpenRecentFolder(path)} />
+ ))}
+ {recents.files.map((file) => (
+ <RecentRow key={`f:${file.path}`} Icon={FileText} iconColor="text-violet" name={file.name} dir={parentDir(file.path)} onClick={() => void openRecentFile(file)} />
+ ))}
+ </div>
+ ) : (
+ <div className="flex items-center gap-2 text-[12.5px] text-muted">
+ <Clock className="size-3.5" /> {t('apps.editor.noRecent')}
+ </div>
+ )}
</div>
</div>
);
};
+
+// One row in the welcome "Recent" list: an icon, the folder/file name, and its containing directory
+// (dimmed, truncated) so same-named entries in different places stay distinguishable.
+const RecentRow: React.FC<{ Icon: typeof FolderOpen; iconColor: string; name: string; dir: string; onClick: () => void }> = ({ Icon, iconColor, name, dir, onClick }) => (
+ <button type="button" onClick={onClick} className="flex w-full items-center gap-2.5 rounded-lg px-3 py-1.5 text-left transition hover:bg-foreground/[0.06]">
+ <Icon className={clsx('size-4 shrink-0', iconColor)} />
+ <span className="max-w-[55%] shrink-0 truncate text-[13px] font-medium text-foreground">{name}</span>
+ <span className="min-w-0 flex-1 truncate text-[11.5px] text-muted">{dir}</span>
+ </button>
+);
diff --git a/ui/src/components/workbench/FilePicker.tsx b/ui/src/components/workbench/FilePicker.tsx
index b44307c51..9087ab647 100644
--- a/ui/src/components/workbench/FilePicker.tsx
+++ b/ui/src/components/workbench/FilePicker.tsx
@@ -35,13 +35,15 @@ export const FilePicker: React.FC<{
initialPath?: string | null;
/** save-file: pre-filled filename. */
defaultName?: string;
+ /** Recently opened folders, shown as quick nav entries at the top of the rail. */
+ recentFolders?: string[];
onCancel: () => void;
/**
* open-directory → result = { path: <folder> }; save-file → { path: <folder>, name }.
* Async: THROW to keep the dialog open and surface the message (e.g. the name already exists).
*/
onConfirm: (result: { path: string; name?: string }) => Promise<void> | void;
-}> = ({ mode, initialPath, defaultName, onCancel, onConfirm }) => {
+}> = ({ mode, initialPath, defaultName, recentFolders, onCancel, onConfirm }) => {
const { t } = useTranslation();
const { projects } = useWorkbenchProjectsTree();
const [cwd, setCwd] = useState('');
@@ -219,6 +221,10 @@ export const FilePicker: React.FC<{
<div className="flex min-h-0 flex-1 overflow-hidden">
{/* Rail: favorites + projects */}
<aside className="hidden w-[150px] shrink-0 flex-col gap-0.5 overflow-y-auto border-r border-border bg-surface-2/40 p-2 sm:flex">
+ {recentFolders && recentFolders.length > 0 && <RailTitle>{t('apps.editor.recent')}</RailTitle>}
+ {(recentFolders || []).map((p) => (
+ <RailRow key={`r:${p}`} label={p.split(/[\\/]/).filter(Boolean).pop() || p} active={cwd === p} onClick={() => navigate(p)} />
+ ))}
{sysFavs.length > 0 && <RailTitle>{t('apps.fileBrowser.favorites')}</RailTitle>}
{sysFavs.map((f) => (
<RailRow key={f.path} label={f.path.split('/').filter(Boolean).pop() || f.path} active={cwd === f.path} onClick={() => navigate(f.path)} />
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index c7bf261a3..e9787d2d7 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -636,7 +636,7 @@
"welcomeSub": "A code editor for files on this machine · VS Code engine",
"start": "Start",
"recent": "Recent",
- "noRecent": "No recent folders",
+ "noRecent": "No recent folders or files",
"openFolder": "Open Folder…",
"openFolderPrompt": "Folder path to open",
"browseFiles": "Browse Files…",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index c42c29882..6448dfb0b 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -636,7 +636,7 @@
"welcomeSub": "本机文件的代码编辑器 · VS Code 内核",
"start": "开始",
"recent": "最近",
- "noRecent": "暂无最近打开的目录",
+ "noRecent": "暂无最近打开的文件夹或文件",
"openFolder": "打开文件夹…",
"openFolderPrompt": "要打开的文件夹路径",
"browseFiles": "浏览文件…",
diff --git a/ui/src/lib/editorRecents.test.ts b/ui/src/lib/editorRecents.test.ts
new file mode 100644
index 000000000..7c507ff56
--- /dev/null
+++ b/ui/src/lib/editorRecents.test.ts
@@ -0,0 +1,150 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ MAX_RECENT_FILES,
+ MAX_RECENT_FOLDERS,
+ addRecentFile,
+ addRecentFolder,
+ parseEditorRecents,
+ recentPathLabel,
+ removeRecentFile,
+ serializeEditorRecents,
+ type EditorRecents,
+} from './editorRecents';
+
+const empty: EditorRecents = { folders: [], files: [] };
+
+describe('editor recents — round trip', () => {
+ it('serializes and parses back to the same folders + files', () => {
+ const recents: EditorRecents = {
+ folders: ['/src', '/tmp/work'],
+ files: [{ path: '/src/a.ts', name: 'a.ts' }],
+ };
+ expect(parseEditorRecents(serializeEditorRecents(recents))).toEqual(recents);
+ });
+});
+
+describe('editor recents — add folder (most-recent-first, dedup, cap)', () => {
+ it('prepends the newest folder', () => {
+ const r = addRecentFolder(addRecentFolder(empty, '/a'), '/b');
+ expect(r.folders).toEqual(['/b', '/a']);
+ });
+
+ it('re-opening a folder bumps it to the front without duplicating', () => {
+ const r = addRecentFolder(addRecentFolder(addRecentFolder(empty, '/a'), '/b'), '/a');
+ expect(r.folders).toEqual(['/a', '/b']);
+ });
+
+ it('caps folders at MAX_RECENT_FOLDERS, dropping the oldest', () => {
+ let r = empty;
+ for (let i = 0; i < MAX_RECENT_FOLDERS + 5; i += 1) r = addRecentFolder(r, `/f${i}`);
+ expect(r.folders).toHaveLength(MAX_RECENT_FOLDERS);
+ expect(r.folders[0]).toBe(`/f${MAX_RECENT_FOLDERS + 4}`); // newest first
+ expect(r.folders).not.toContain('/f0'); // oldest evicted
+ });
+
+ it('ignores an empty folder path', () => {
+ expect(addRecentFolder(empty, '').folders).toEqual([]);
+ });
+});
+
+describe('editor recents — add file (most-recent-first, dedup, cap)', () => {
+ it('prepends the newest file and dedups by path (name refreshes)', () => {
+ const r = addRecentFile(addRecentFile(empty, { path: '/a.ts', name: 'a.ts' }), { path: '/a.ts', name: 'renamed.ts' });
+ expect(r.files).toEqual([{ path: '/a.ts', name: 'renamed.ts' }]);
+ });
+
+ it('caps files at MAX_RECENT_FILES', () => {
+ let r = empty;
+ for (let i = 0; i < MAX_RECENT_FILES + 5; i += 1) r = addRecentFile(r, { path: `/f${i}.ts`, name: `f${i}.ts` });
+ expect(r.files).toHaveLength(MAX_RECENT_FILES);
+ expect(r.files[0].path).toBe(`/f${MAX_RECENT_FILES + 4}.ts`);
+ });
+
+ it('falls back to the last path segment when a name is missing', () => {
+ const r = addRecentFile(empty, { path: '/x/y/z.ts', name: '' });
+ expect(r.files[0]).toEqual({ path: '/x/y/z.ts', name: 'z.ts' });
+ });
+
+ it('ignores a file with an empty path', () => {
+ expect(addRecentFile(empty, { path: '', name: 'x' }).files).toEqual([]);
+ });
+});
+
+describe('editor recents — remove file', () => {
+ it('drops only the matching path, leaving folders + other files intact', () => {
+ const recents: EditorRecents = {
+ folders: ['/src'],
+ files: [{ path: '/a.ts', name: 'a.ts' }, { path: '/b.ts', name: 'b.ts' }],
+ };
+ const r = removeRecentFile(recents, '/a.ts');
+ expect(r.files).toEqual([{ path: '/b.ts', name: 'b.ts' }]);
+ expect(r.folders).toEqual(['/src']);
+ });
+});
+
+describe('editor recents — corrupt / old data is ignored', () => {
+ it('returns empty for invalid JSON', () => {
+ expect(parseEditorRecents('{not json')).toEqual(empty);
+ });
+
+ it('returns empty for null / undefined / empty input', () => {
+ expect(parseEditorRecents(null)).toEqual(empty);
+ expect(parseEditorRecents(undefined)).toEqual(empty);
+ expect(parseEditorRecents('')).toEqual(empty);
+ });
+
+ it('returns empty for a mismatched schema version', () => {
+ expect(parseEditorRecents(JSON.stringify({ version: 2, folders: ['/a'], files: [] }))).toEqual(empty);
+ });
+
+ it('returns empty for a non-object / array payload', () => {
+ expect(parseEditorRecents(JSON.stringify(['/a']))).toEqual(empty);
+ expect(parseEditorRecents(JSON.stringify(42))).toEqual(empty);
+ });
+
+ it('coerces non-array lists to empty rather than throwing', () => {
+ expect(parseEditorRecents(JSON.stringify({ version: 1, folders: 'nope', files: {} }))).toEqual(empty);
+ });
+
+ it('drops non-string folders and malformed file entries but keeps valid siblings', () => {
+ const raw = JSON.stringify({
+ version: 1,
+ folders: ['/good', 42, null, '/good2'],
+ files: [
+ { path: '/a.ts', name: 'a.ts' },
+ { name: 'no-path.ts' },
+ { path: 123 },
+ 'bogus',
+ { path: '/b.ts', name: 'b.ts' },
+ ],
+ });
+ expect(parseEditorRecents(raw)).toEqual({
+ folders: ['/good', '/good2'],
+ files: [{ path: '/a.ts', name: 'a.ts' }, { path: '/b.ts', name: 'b.ts' }],
+ });
+ });
+
+ it('de-dups and caps a corrupt oversized payload on read', () => {
+ const raw = JSON.stringify({
+ version: 1,
+ folders: [...Array.from({ length: MAX_RECENT_FOLDERS + 10 }, (_, i) => `/f${i}`), '/f0'],
+ files: Array.from({ length: MAX_RECENT_FILES + 10 }, () => ({ path: '/dup.ts', name: 'dup.ts' })),
+ });
+ const r = parseEditorRecents(raw);
+ expect(r.folders).toHaveLength(MAX_RECENT_FOLDERS);
+ expect(r.files).toEqual([{ path: '/dup.ts', name: 'dup.ts' }]); // all dups collapse to one
+ });
+});
+
+describe('recentPathLabel', () => {
+ it('returns the last segment for POSIX and Windows paths', () => {
+ expect(recentPathLabel('/a/b/c.ts')).toBe('c.ts');
+ expect(recentPathLabel('C:\\work\\proj')).toBe('proj');
+ expect(recentPathLabel('/a/b/')).toBe('b');
+ });
+
+ it('falls back to the whole path for a root', () => {
+ expect(recentPathLabel('/')).toBe('/');
+ });
+});
diff --git a/ui/src/lib/editorRecents.ts b/ui/src/lib/editorRecents.ts
new file mode 100644
index 000000000..8014b820b
--- /dev/null
+++ b/ui/src/lib/editorRecents.ts
@@ -0,0 +1,171 @@
+// Versioned localStorage store for the Editor's "Recent" welcome lists: the folders a user has
+// opened as an explorer root, and the files they've opened. Mirrors workbenchPersistence's shape —
+// pure parse/serialize/mutate helpers (unit-testable, corruption-tolerant) plus thin storage
+// wrappers — but is a DISTINCT concern from window persistence:
+//
+// - workbenchPersistence restores the LAST session's open windows + tabs on a reload.
+// - this is a longer-lived, cross-session MRU history shown on the editor's welcome screen.
+//
+// Every editor window and the full-page /apps/editor route share this one store; there's no
+// coordination, so writes are last-write-wins and the welcome screen reads fresh on mount.
+
+// Bump the version suffix to invalidate an incompatible on-disk shape — a value under an older key
+// is simply never read, so old/corrupt data is ignored silently (not migrated).
+export const EDITOR_RECENTS_STORAGE_KEY = 'avibe.editor.recents.v1';
+
+// Keep the welcome lists short (VS Code-style), most-recent-first. Also bounds the stored payload so
+// one corrupt/oversized entry can't grow the store — or flood the welcome screen — without limit.
+export const MAX_RECENT_FOLDERS = 8;
+export const MAX_RECENT_FILES = 8;
+
+export interface RecentFile {
+ path: string;
+ name: string;
+}
+
+export interface EditorRecents {
+ // Absolute folder paths; the display label is derived from the last segment.
+ folders: string[];
+ files: RecentFile[];
+}
+
+interface PersistedRecents {
+ version: 1;
+ folders: string[];
+ files: RecentFile[];
+}
+
+// A fresh empty value on every call — never a shared mutable object, so a caller holding it in
+// React state can't be aliased by the next reader.
+function empty(): EditorRecents {
+ return { folders: [], files: [] };
+}
+
+function isNonEmptyString(v: unknown): v is string {
+ return typeof v === 'string' && v.length > 0;
+}
+
+// The display label for a recent path: its last path segment (Windows- and POSIX-aware), falling
+// back to the whole path for a root like "/". Shared by the welcome list (folder labels) and the
+// file-name fallback below.
+export function recentPathLabel(path: string): string {
+ return path.split(/[\\/]/).filter(Boolean).pop() || path;
+}
+
+// Prepend `value` as the most-recent entry, drop any existing entry with the same key (so a re-open
+// bumps it to the front rather than duplicating), and cap the list length.
+function prepend<T>(list: T[], value: T, key: (item: T) => string, cap: number): T[] {
+ const k = key(value);
+ return [value, ...list.filter((item) => key(item) !== k)].slice(0, cap);
+}
+
+const folderKey = (p: string) => p;
+const fileKey = (f: RecentFile) => f.path;
+
+// Record a folder opened as the explorer root. Pure — returns a new EditorRecents.
+export function addRecentFolder(recents: EditorRecents, path: string): EditorRecents {
+ if (!isNonEmptyString(path)) return recents;
+ return { ...recents, folders: prepend(recents.folders, path, folderKey, MAX_RECENT_FOLDERS) };
+}
+
+// Record an opened file. Pure — returns a new EditorRecents.
+export function addRecentFile(recents: EditorRecents, file: RecentFile): EditorRecents {
+ if (!isNonEmptyString(file.path)) return recents;
+ const entry: RecentFile = { path: file.path, name: isNonEmptyString(file.name) ? file.name : recentPathLabel(file.path) };
+ return { ...recents, files: prepend(recents.files, entry, fileKey, MAX_RECENT_FILES) };
+}
+
+// Drop a file whose path no longer resolves (opening it failed). Pure.
+export function removeRecentFile(recents: EditorRecents, path: string): EditorRecents {
+ return { ...recents, files: recents.files.filter((f) => f.path !== path) };
+}
+
+// De-dup a list by key, keeping the first occurrence (most-recent-first order) and capping length —
+// so a hand-edited/corrupt blob with duplicate or oversized lists still parses to a sane shape.
+function dedupeCap<T>(list: T[], key: (item: T) => string, cap: number): T[] {
+ const seen = new Set<string>();
+ const out: T[] = [];
+ for (const item of list) {
+ const k = key(item);
+ if (seen.has(k)) continue;
+ seen.add(k);
+ out.push(item);
+ if (out.length >= cap) break;
+ }
+ return out;
+}
+
+// Parse a raw stored payload into recents. Pure (no storage access) so it's unit-testable; any
+// corruption — invalid JSON, wrong/absent version, non-array lists, malformed entries — yields the
+// empty set or drops just the bad entries, and never throws.
+export function parseEditorRecents(raw: string | null | undefined): EditorRecents {
+ if (!raw) return empty();
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(raw);
+ } catch {
+ return empty();
+ }
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || (parsed as { version?: unknown }).version !== 1) {
+ return empty();
+ }
+ const p = parsed as { folders?: unknown; files?: unknown };
+ const folders = dedupeCap((Array.isArray(p.folders) ? p.folders : []).filter(isNonEmptyString), folderKey, MAX_RECENT_FOLDERS);
+ const files = dedupeCap(
+ (Array.isArray(p.files) ? p.files : []).flatMap((f): RecentFile[] => {
+ if (!f || typeof f !== 'object') return [];
+ const ff = f as { path?: unknown; name?: unknown };
+ if (!isNonEmptyString(ff.path)) return [];
+ // A missing/corrupt name falls back to the path's last segment, so a row always has a label.
+ return [{ path: ff.path, name: isNonEmptyString(ff.name) ? ff.name : recentPathLabel(ff.path) }];
+ }),
+ fileKey,
+ MAX_RECENT_FILES,
+ );
+ return { folders, files };
+}
+
+// Serialize recents to the versioned payload string. Pure.
+export function serializeEditorRecents(recents: EditorRecents): string {
+ const payload: PersistedRecents = { version: 1, folders: recents.folders, files: recents.files };
+ return JSON.stringify(payload);
+}
+
+// Read + parse the persisted recents. Returns the empty set when storage is unavailable or empty.
+export function loadEditorRecents(): EditorRecents {
+ try {
+ return parseEditorRecents(window.localStorage.getItem(EDITOR_RECENTS_STORAGE_KEY));
+ } catch {
+ return empty();
+ }
+}
+
+// Serialize + write recents. Silently drops on any failure (storage disabled / quota exceeded) —
+// recents is best-effort and must never interrupt the user.
+function save(recents: EditorRecents): void {
+ try {
+ window.localStorage.setItem(EDITOR_RECENTS_STORAGE_KEY, serializeEditorRecents(recents));
+ } catch {
+ // ignore
+ }
+}
+
+// Storage-backed recorders. Each reads fresh (last write wins across the windows sharing this store),
+// applies the pure mutation, persists, and returns the updated recents for the caller to render.
+export function rememberRecentFolder(path: string): EditorRecents {
+ const next = addRecentFolder(loadEditorRecents(), path);
+ save(next);
+ return next;
+}
+
+export function rememberRecentFile(path: string, name: string): EditorRecents {
+ const next = addRecentFile(loadEditorRecents(), { path, name });
+ save(next);
+ return next;
+}
+
+export function forgetRecentFile(path: string): EditorRecents {
+ const next = removeRecentFile(loadEditorRecents(), path);
+ save(next);
+ return next;
+}