Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Keep the source when it changes during a cross-Library move

arxhr0076e82fbf31c6d
diff --git a/src/main/features/library_transfer.ts b/src/main/features/library_transfer.ts
index 2ada607a..dbd28e43 100644
--- a/src/main/features/library_transfer.ts
+++ b/src/main/features/library_transfer.ts
@@ -5,9 +5,11 @@
* Source resolution and every destination write stay behind the global and
* project Library path validators. Cross-Library moves are copy-then-delete:
* the source is removed only after the destination copy and index refresh
- * succeed; a failed source delete rolls the destination back best-effort.
+ * succeed and the source is unchanged since the copy began; a failed or
+ * skipped source delete rolls the destination back best-effort.
*/
+import * as fs from 'node:fs';
import * as path from 'node:path';
import * as contexts from './contexts';
@@ -113,6 +115,30 @@ async function resolveSourceAbs(userId: string, ref: LibraryRef, rel: string): P
return { ok: true, absPath: resolved.absPath };
}
+/**
+ * Fingerprint of a file or folder tree (path, size and mtime of every entry),
+ * or null when it cannot be read. Two fingerprints differ when the source was
+ * edited, added to or removed from between them.
+ */
+function fingerprintEntry(absPath: string): string | null {
+ const rows: string[] = [];
+ const walk = (abs: string, rel: string): void => {
+ const stat = fs.statSync(abs);
+ if (stat.isDirectory()) {
+ rows.push(`${rel}/`);
+ for (const name of fs.readdirSync(abs).sort()) walk(path.join(abs, name), `${rel}/${name}`);
+ return;
+ }
+ rows.push(`${rel}:${stat.size}:${stat.mtimeMs}`);
+ };
+ try {
+ walk(absPath, '');
+ } catch {
+ return null;
+ }
+ return rows.join('\n');
+}
+
async function copyInto(
userId: string,
destination: LibraryRef,
@@ -218,6 +244,7 @@ export async function transferLibraryEntries(
results.push({ ...resultBase, ok: false, error: 'account_changed' });
continue;
}
+ const sourceBefore = mode === 'move' ? fingerprintEntry(resolved.absPath) : null;
const copied = await copyInto(userId, destination, resolved.absPath, targetRel);
if (copied.ok === false) {
results.push({ ...resultBase, ok: false, error: normalizeError(copied.error) });
@@ -239,10 +266,15 @@ export async function transferLibraryEntries(
continue;
}
let removed: { ok: boolean; error?: string };
- try {
- removed = await deleteFrom(userId, source, sourceRel);
- } catch {
- removed = { ok: false, error: 'source_delete_failed' };
+ if (fingerprintEntry(resolved.absPath) !== sourceBefore) {
+ // Edited while it was being copied: deleting now would lose those edits.
+ removed = { ok: false, error: 'source_changed' };
+ } else {
+ try {
+ removed = await deleteFrom(userId, source, sourceRel);
+ } catch {
+ removed = { ok: false, error: 'source_delete_failed' };
+ }
}
if (!removed.ok) {
let rollback: { ok: boolean; error?: string };
diff --git a/test/main/features/library_transfer_source_changed.test.ts b/test/main/features/library_transfer_source_changed.test.ts
new file mode 100644
index 00000000..bfd3f3e2
--- /dev/null
+++ b/test/main/features/library_transfer_source_changed.test.ts
@@ -0,0 +1,99 @@
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const state = vi.hoisted(() => ({
+ root: '',
+ calls: [] as Array<{ op: string; args: unknown[] }>,
+ duringCopy: null as null | (() => void),
+}));
+
+vi.mock('../../../src/main/features/users', () => ({
+ getActiveUserId: () => 'u1',
+}));
+
+vi.mock('../../../src/main/features/contexts', () => ({
+ resolveContextEntryAbsPath: (rel: string) => `${state.root}/${rel}`,
+ copyContextEntryFromPath: (source: string, target: string) => {
+ state.calls.push({ op: 'copy-global', args: [source, target] });
+ return { ok: true, path: target, fileCount: 1, bytes: 10 };
+ },
+ deleteContextTarget: (rel: string) => {
+ state.calls.push({ op: 'delete-global', args: [rel] });
+ return { ok: true };
+ },
+}));
+
+vi.mock('../../../src/main/features/project_files', () => ({
+ resolveProjectEntryAbsPath: async () => ({ ok: false, error: 'not_found' }),
+ copyProjectEntryFromPath: async (_uid: string, _pid: string, source: string, target: string) => {
+ state.calls.push({ op: 'copy-project', args: [source, target] });
+ // Simulates the user saving the source while the destination is written.
+ state.duringCopy?.();
+ return { ok: true, name: target, fileCount: 1, bytes: 10 };
+ },
+ deleteProjectEntry: async (_uid: string, pid: string, rel: string) => {
+ state.calls.push({ op: 'delete-project', args: [pid, rel] });
+ return { ok: true };
+ },
+}));
+
+beforeEach(() => {
+ state.root = fs.mkdtempSync(path.join(os.tmpdir(), 'orkas-transfer-'));
+ state.calls.length = 0;
+ state.duringCopy = null;
+ vi.resetModules();
+});
+
+afterEach(() => {
+ fs.rmSync(state.root, { recursive: true, force: true });
+});
+
+async function moveToProject(sourcePath: string) {
+ const mod = await import('../../../src/main/features/library_transfer');
+ return mod.transferLibraryEntries('u1', {
+ mode: 'move',
+ source: { scope: 'global' },
+ paths: [sourcePath],
+ destination: { scope: 'project', projectId: 'p1' },
+ });
+}
+
+describe('library_transfer move when the source changes during the copy', () => {
+ it('keeps the source and rolls the destination back when a file is edited mid-copy', async () => {
+ const file = path.join(state.root, 'note.md');
+ fs.writeFileSync(file, 'old');
+ state.duringCopy = () => fs.writeFileSync(file, 'old and new edits');
+
+ const result = await moveToProject('note.md');
+
+ expect(result).toMatchObject({ ok: true, succeeded: 0, failed: 1 });
+ expect((result as { results: Array<{ error?: string }> }).results[0].error).toBe('source_delete_failed');
+ expect(state.calls.map((row) => row.op)).toEqual(['copy-project', 'delete-project']);
+ expect(fs.readFileSync(file, 'utf8')).toBe('old and new edits');
+ });
+
+ it('keeps the source when a file is added to a moved folder mid-copy', async () => {
+ const dir = path.join(state.root, 'folder');
+ fs.mkdirSync(dir);
+ fs.writeFileSync(path.join(dir, 'a.md'), 'a');
+ state.duringCopy = () => fs.writeFileSync(path.join(dir, 'b.md'), 'b');
+
+ const result = await moveToProject('folder');
+
+ expect(result).toMatchObject({ ok: true, succeeded: 0, failed: 1 });
+ expect(state.calls.map((row) => row.op)).toEqual(['copy-project', 'delete-project']);
+ expect(fs.existsSync(path.join(dir, 'b.md'))).toBe(true);
+ });
+
+ it('still deletes the source when nothing changed during the copy', async () => {
+ fs.writeFileSync(path.join(state.root, 'note.md'), 'old');
+
+ const result = await moveToProject('note.md');
+
+ expect(result).toMatchObject({ ok: true, succeeded: 1, failed: 0 });
+ expect(state.calls.map((row) => row.op)).toEqual(['copy-project', 'delete-global']);
+ });
+});