Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(companions): preserve imported content and report partial saves

zqchris87f31e257689
diff --git a/apps/desktop/src/main/bot-import/README.md b/apps/desktop/src/main/bot-import/README.md
index 48b99aa711..20ed52aa3a 100644
--- a/apps/desktop/src/main/bot-import/README.md
+++ b/apps/desktop/src/main/bot-import/README.md
@@ -45,11 +45,23 @@ omitting it retains normal companion defaults, and a rejected request can be cor
- Hermes default/profile homes and OpenClaw's selected agent workspace are read
independently. OpenClaw's current SQLite cron store takes precedence over the
- legacy JSON store; a database failure never substitutes a stale backup.
+ legacy JSON store; a database failure never substitutes a stale backup. The worker
+ uses the native SQLite binding selected by Main, including isolated Electron dev
+ bindings. Driver, size and database failures retain distinct safe reason codes.
+- Memory discovery includes Markdown, TXT and attachments under the memory trees,
+ including hidden subdirectories. Hermes `memories/` and a user-maintained `memory/`
+ archive stay separate; OpenClaw also includes workspace `DREAMS.md`. Supported media
+ originals enter the shared media ledger with a companion-owned import reference
+ and a memory document linking the managed URL. Retry reuses that reference;
+ companion deletion releases only its own refs through recoverable cleanup.
+ Unsupported attachments remain visible failures, not silently omitted files.
- Selected identity/user/instruction documents and memories retain their original
text in the encrypted environment. Profile prompt fields and the native memory
store receive copies with known selected env/MCP/auth credentials masked, while
- ordinary text stays unchanged. Env references and original credentials remain
+ ordinary text stays unchanged. Import summaries/titles obey the storage UTF-16
+ length bounds, and document parts preserve source frontmatter and whitespace.
+ Each new part is read back before it counts as saved; failures preserve part
+ progress and safe storage reasons. Existing edited parts are not overwritten. Env references and original credentials remain
available to host execution; no model call or extra confirmation is added.
Selected skill folders retain their
real scripts, templates, executable bits and `SKILL.md`.
@@ -144,7 +156,9 @@ omitting it retains normal companion defaults, and a rejected request can be cor
Codex hosts remain partitioned by companion environment identity.
Before publishing a selected Skill, UTF-8 and BOM-marked UTF-16 text (including
SKILL.md, scripts and reference resources) masks all known source credentials.
- Unchanged resources and binary assets retain their bytes. Affected skills keep
+ Recognizable boolean/numeric settings and ordinary MCP endpoint names are not
+ treated as credentials. Explicit credentials (including short values) and unknown
+ private settings remain masked. Unchanged resources and binary assets retain their bytes. Affected skills keep
their complete original resource tree in the encrypted environment after the
restart checkpoint is cleared. Their readable SKILL.md points commands to the
existing `run_command` bridge and its private `CINDY_IMPORTED_SKILLS/<slug>`
@@ -309,9 +323,14 @@ external data still require actual read evidence.
GUI imports send the additive `deferSetup` flag (the command defaults it to true).
Saving personality/memory/skills, private connections and disabled routine definitions
finishes before any data probe, source pause or target activation. `savedEntryIds`
-counts saved definitions independently of activation status. The completion page
-opens the normal teammate chat, without a per-item warning wall. One idempotent
-chat message explains that remaining setup can wait. Native Heartbeat is omitted;
+counts saved definitions independently of activation status. `saved: true` means
+that the save pass finished, not that every selected item succeeded. Both clients
+show saved/selected counts and distinguish partial imports from setup-only checks.
+An expandable, paginated detail list shows filenames, safe reasons and partial
+progress. Chat remains available alongside retry. Idempotent chat notices distinguish
+partial saves, pending setup and eventual completion without exposing raw exceptions.
+An invalid automation definition reports the conversion failure before setup warnings;
+valid definitions are saved disabled even when tool/model mapping is still pending. Native Heartbeat is omitted;
ordinary cron jobs named heartbeat are still imported.
The owner-scoped `companion_connections.import_setup` tool lists remaining checks
diff --git a/apps/desktop/src/main/bot-import/__tests__/environment.test.ts b/apps/desktop/src/main/bot-import/__tests__/environment.test.ts
index a372bb4454..32c0f6ef0d 100644
--- a/apps/desktop/src/main/bot-import/__tests__/environment.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/environment.test.ts
@@ -128,3 +128,17 @@ it('joins asynchronous writes before committed deletion removes credentials', as
await rejected; await removal;
expect(values.size).toBe(0);
});
+
+it('recovers media cleanup before removing the private import checkpoint', async () => {
+ const remove = vi.fn(() => true);
+ const removeResources = vi.fn().mockRejectedValueOnce(new Error('ledger unavailable')).mockResolvedValue(undefined);
+ const store = createCompanionEnvironmentStore({ read: () => 'private-checkpoint', write: () => true, remove, removeResources });
+ await store.stageRemoval(root, 'fixture', () => {});
+ await expect(store.finishRemoval(root, 'fixture', () => {})).rejects.toThrow('ledger unavailable');
+ expect(remove).not.toHaveBeenCalled();
+ await expect(fs.access(path.join(root, 'companion-import-cleanups/fixture.json'))).resolves.toBeUndefined();
+ await store.recoverRemovals(root, () => {}, async () => false);
+ expect(removeResources).toHaveBeenCalledTimes(2);
+ expect(remove).toHaveBeenCalledOnce();
+ await expect(fs.access(path.join(root, 'companion-import-cleanups/fixture.json'))).rejects.toThrow();
+});
diff --git a/apps/desktop/src/main/bot-import/__tests__/host.test.ts b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
index 5b02bd24c1..145fc743ab 100644
--- a/apps/desktop/src/main/bot-import/__tests__/host.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
@@ -402,7 +402,9 @@ it.each([false, true])('redacts all known credentials from profile/memory copies
expect(stored.env).not.toHaveProperty('EXCLUDED');
expect(JSON.stringify(stored)).not.toContain('fake-absent-from-selected-content');
expect(stored.documents).toEqual(Object.fromEntries(documents.map(item => [item.view.id, item.text])));
- expect(stored.pendingImport).toBeUndefined();
+ await vi.waitFor(async () => {
+ expect((await h.store.read(h.root, result.botId, () => {}))?.pendingImport).toBeUndefined();
+ });
});
it('persists redacted routine fields and retains identical publication masks across a handover retry after restart', async () => {
@@ -953,21 +955,21 @@ it.each(['directory', undefined] as const)('retries a repaired memory directory
await fs.mkdir(path.join(directory, 'nested'), { recursive: true });
await fs.writeFile(path.join(directory, 'nested', 'note.md'), 'Recovered note');
await fs.writeFile(path.join(directory, 'USER.md'), 'User preferences');
- await fs.writeFile(path.join(directory, 'ignored.txt'), 'Not a memory');
+ await fs.writeFile(path.join(directory, 'ignored.txt'), 'Recovered TXT archive');
await startCompanionImport(selection, 'reconnected-phone');
const result = await withBotProfileLocks([first.botId], () => getCompanionImportResult(selection.requestId));
expect(result).toMatchObject({ status: 'complete', botId: first.botId, savedEntryIds: ['healthy', brokenId] });
- expect(h.importDocument).toHaveBeenCalledTimes(3);
+ expect(h.importDocument).toHaveBeenCalledTimes(4);
expect(h.importDocument).toHaveBeenCalledWith(first.botId, expect.stringMatching(/^memory-[a-f0-9]{32}$/), 'broken/nested/note.md', 'Recovered note', 'reference');
expect(h.importDocument).toHaveBeenCalledWith(first.botId, expect.stringMatching(/^memory-[a-f0-9]{32}$/), 'broken/USER.md', 'User preferences', 'user');
expect((await storage.list()).map(record => [record.frontmatter.type, record.body.trim()])).toEqual(expect.arrayContaining([
- ['reference', 'Healthy'], ['reference', 'Recovered note'], ['user', 'User preferences'],
+ ['reference', 'Recovered TXT archive'], ['reference', 'Healthy'], ['reference', 'Recovered note'], ['user', 'User preferences'],
]));
const environment = await h.store.read(h.root, first.botId, () => {});
expect(Object.values(environment!.documents!)).toEqual(expect.arrayContaining(['Healthy', 'Recovered note', 'User preferences']));
await startCompanionImport(selection, 'phone');
- expect(h.importDocument).toHaveBeenCalledTimes(3);
- expect(await storage.list()).toHaveLength(3);
+ expect(h.importDocument).toHaveBeenCalledTimes(4);
+ expect(await storage.list()).toHaveLength(4);
});
it.each([false, true])('publishes completion after deferred setup without duplicate notices (legacy setup: %s)', async legacySetup => {
@@ -1102,3 +1104,23 @@ it.each(['short-legacy-document', `memory-${'a'.repeat(20)}-${'b'.repeat(20)}`])
expect(ids.every(id => id.length <= 40)).toBe(true);
if (originalId.length <= 40) expect(ids[0]).toBe(originalId);
});
+
+it('publishes a partial-save notice with the failed filename and safe reason, then a distinct completion notice', async () => {
+ h.snapshot.items = [{ view: { id: 'memory-doc', name: 'long-document.md', category: 'memory', selected: true }, text: 'Source text' }];
+ h.importDocument.mockRejectedValueOnce(Object.assign(new Error('private filesystem path'), { code: 'ENOSPC', importProgress: { saved: 1, total: 3 } }));
+ const [source] = await listCompanionImportSources('fixture');
+ const preview = await previewCompanionImport(source!.id, 'fixture');
+ const selection = { requestId: 'fixture-partial-notice', previewId: preview.id, name: 'Ada', entryIds: ['memory-doc'], takeover: false, deferSetup: true };
+ const accepted = await startCompanionImport(selection, 'fixture');
+ const first = await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));
+ expect(first).toMatchObject({ saved: true, status: 'needs-attention', savedEntryIds: [] });
+ const notice = vi.mocked(createMessage).mock.calls.at(-1)![1];
+ expect(notice.content).toContain(t('bots.import.chatPartial'));
+ expect(notice.content).toContain('long-document.md');
+ expect(notice.content).toContain(t('bots.import.diskFull'));
+ expect(notice.content).not.toContain('private filesystem path');
+ await startCompanionImport(selection, 'fixture');
+ const completed = await withBotProfileLocks([accepted.botId], () => getCompanionImportResult(selection.requestId));
+ expect(completed?.status).toBe('complete');
+ expect(vi.mocked(createMessage).mock.calls.at(-1)![1]).toMatchObject({ clientId: `companion-import:${selection.requestId}:ready`, content: t('bots.import.chatReady') });
+});
diff --git a/apps/desktop/src/main/bot-import/__tests__/memoryMedia.test.ts b/apps/desktop/src/main/bot-import/__tests__/memoryMedia.test.ts
new file mode 100644
index 0000000000..58a568c22f
--- /dev/null
+++ b/apps/desktop/src/main/bot-import/__tests__/memoryMedia.test.ts
@@ -0,0 +1,56 @@
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import Database from 'better-sqlite3';
+import { drizzle } from 'drizzle-orm/better-sqlite3';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import * as schema from '../../localDb/schema';
+const { default: migration0071 } = await import('../../../../drizzle/scripts/0071_bright_ultron') as unknown as { default: { run(db: Database.Database): void } };
+import type { LedgerDb } from '../../cindy-media/ledger';
+
+let root = '';
+let raw: Database.Database;
+let db: LedgerDb;
+vi.mock('electron', () => ({ app: { getPath: () => root } }));
+vi.mock('../../appSessionState', () => ({
+ activeOwnerScopeKey: () => 'cloud:import-owner:1',
+ dataOwnerStorageKey: () => 'a'.repeat(20),
+ getActiveAppSession: () => ({ mode: 'cloud', dataOwnerId: 'import-owner', generation: 1 }),
+ isAppSessionBoundaryPending: () => false,
+}));
+vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => ({ drizzle: db }) }));
+const { importMemoryMedia, removeImportedMemoryMedia } = await import('../memoryMedia.js');
+
+beforeEach(() => {
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'cindy-memory-media-test-'));
+ raw = new Database(':memory:');
+ raw.pragma('foreign_keys = ON');
+ const sql = fs.readFileSync(path.resolve(__dirname, '../../../../drizzle/0070_woozy_harpoon.sql'), 'utf8');
+ for (const statement of sql.split('--> statement-breakpoint')) if (statement.trim()) raw.exec(statement);
+ migration0071.run(raw);
+ db = drizzle(raw, { schema }) as unknown as LedgerDb;
+});
+afterEach(() => { raw.close(); fs.rmSync(root, { recursive: true, force: true }); });
+
+it('keeps original image bytes, retries without duplicate refs, and removes only the deleted companion reference', async () => {
+ const bytes = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+j5l0AAAAASUVORK5CYII=', 'base64');
+ const url = await importMemoryMedia('first', 'first-chat', bytes, () => {});
+ expect(await importMemoryMedia('first', 'first-chat', bytes, () => {})).toBe(url);
+ expect(await importMemoryMedia('second', 'second-chat', bytes, () => {})).toBe(url);
+ const [blob] = db.select().from(schema.mediaBlobs).all();
+ expect(blob.isCache).toBe(false);
+ const hash = url.match(/blobs\/(.+)\.png/)![1];
+ expect(fs.readFileSync(path.join(root, 'cindy-media', 'blobs', hash.slice(0, 2), `${hash}.png`))).toEqual(bytes);
+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(2);
+ await removeImportedMemoryMedia('first', () => {});
+ const refs = db.select().from(schema.mediaRefs).all();
+ expect(refs).toHaveLength(1);
+ expect(refs[0]).toMatchObject({ refId: 'companion-memory:second', originSessionId: 'second-chat' });
+});
+
+it('reports unsupported attachments and rejects writes after account changes', async () => {
+ await expect(importMemoryMedia('first', 'chat', Buffer.from('unknown binary'), () => {})).rejects.toThrow('MEMORY_ATTACHMENT_UNSUPPORTED');
+ await expect(importMemoryMedia('first', 'chat', Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), () => { throw new Error('OWNER_CHANGED'); })).rejects.toThrow('OWNER_CHANGED');
+ expect(db.select().from(schema.mediaRefs).all()).toHaveLength(0);
+ expect(db.select().from(schema.mediaBlobs).all()).toHaveLength(0);
+});
diff --git a/apps/desktop/src/main/bot-import/__tests__/openclawCron.test.ts b/apps/desktop/src/main/bot-import/__tests__/openclawCron.test.ts
new file mode 100644
index 0000000000..c888ad68b2
--- /dev/null
+++ b/apps/desktop/src/main/bot-import/__tests__/openclawCron.test.ts
@@ -0,0 +1,17 @@
+import { EventEmitter } from 'node:events';
+import { expect, it, vi } from 'vitest';
+const h = vi.hoisted(() => ({ binding: '/fixture/electron/better_sqlite3.node', data: {} as Record<string, unknown> }));
+vi.mock('../../localDb/betterSqliteFactory.js', () => ({ resolveBetterSqliteNativeBinding: () => h.binding }));
+vi.mock('node:worker_threads', () => ({ Worker: class extends EventEmitter {
+ constructor(_file: string, options: { workerData: Record<string, unknown> }) {
+ super(); h.data = options.workerData;
+ queueMicrotask(() => this.emit('message', { ok: true, jobs: [{ id: 'job' }] }));
+ }
+ terminate = vi.fn(async () => 0);
+} }));
+import { readOpenClawCronDatabase } from '../openclawCron.js';
+it('forwards the same native binding selected by Main to the readonly foreign-database worker', async () => {
+ await expect(readOpenClawCronDatabase({ database: 'source.sqlite', storeKey: 'store', agentId: 'agent', defaultAgent: false })).resolves.toEqual([{ id: 'job' }]);
+ expect(h.data).toMatchObject({ nativeBinding: h.binding, database: 'source.sqlite', agentId: 'agent', defaultAgent: false });
+ expect(h.data.modulePath).toMatch(/better-sqlite3/);
+});
diff --git a/apps/desktop/src/main/bot-import/__tests__/openclawCronWorker.test.ts b/apps/desktop/src/main/bot-import/__tests__/openclawCronWorker.test.ts
index 0343ece945..f6bbffbe13 100644
--- a/apps/desktop/src/main/bot-import/__tests__/openclawCronWorker.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/openclawCronWorker.test.ts
@@ -59,10 +59,33 @@ it.each(['tiny', 'utf8'] as const)('stops the worker iterator before retaining a
const exit = new Promise<void>((resolve, reject) => { worker.once('exit', code => code ? reject(new Error(`worker exit ${code}`)) : resolve()); worker.once('error', reject); });
const reply = await new Promise<unknown>((resolve, reject) => { worker.once('message', resolve); worker.once('error', reject); });
await exit;
- expect(reply).toEqual({ ok: false });
+ expect(reply).toEqual({ ok: false, code: 'SOURCE_DATABASE_TOO_LARGE' });
const counts = JSON.parse(await fs.readFile(database, 'utf8'));
expect(counts.closed).toBe(true);
expect(counts.read).toBeGreaterThan(1);
expect(counts.read).toBeLessThan(scenario === 'tiny' ? 65_000 : 13);
} finally { await worker.terminate(); }
});
+
+it.each([false, true])('passes the host native binding into the database constructor (driver fails: %s)', async fails => {
+ root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-import-sqlite-binding-'));
+ const nativeBinding = path.join(root, 'electron-native.node');
+ const databaseModule = path.join(root, 'driver.cjs');
+ await fs.writeFile(databaseModule, `module.exports = class {
+ constructor(file, options) {
+ if (options.nativeBinding !== ${JSON.stringify(nativeBinding)} || !options.readonly || !options.fileMustExist) throw new Error('wrong binding');
+ ${fails ? "throw Object.assign(new Error('private source path'), { code: 'ERR_DLOPEN_FAILED' });" : ''}
+ }
+ prepare() { return { *iterate() { yield { job_json: '{"id":"selected-binding"}', state_json: '{}' }; } }; }
+ close() {}
+ };`);
+ const source = await fs.readFile(new URL('../openclawCronWorker.ts', import.meta.url), 'utf8');
+ const module = path.join(root, 'worker.cjs');
+ await fs.writeFile(module, transformSync(source, { loader: 'ts', format: 'cjs', platform: 'node', target: 'node22', logLevel: 'silent' }).code);
+ const worker = new Worker(module, { workerData: { database: 'source', storeKey: 'store', agentId: 'main', defaultAgent: true, modulePath: databaseModule, nativeBinding } });
+ try {
+ const reply = await new Promise<unknown>((resolve, reject) => { worker.once('message', resolve); worker.once('error', reject); });
+ expect(reply).toEqual(fails ? { ok: false, code: 'SOURCE_DATABASE_DRIVER_UNAVAILABLE' } : { ok: true, jobs: [{ id: 'selected-binding', state: {} }] });
+ expect(JSON.stringify(reply)).not.toContain('private source path');
+ } finally { await worker.terminate(); }
+});
diff --git a/apps/desktop/src/main/bot-import/__tests__/process.test.ts b/apps/desktop/src/main/bot-import/__tests__/process.test.ts
index 380683eae1..026cc37d95 100644
--- a/apps/desktop/src/main/bot-import/__tests__/process.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/process.test.ts
@@ -46,3 +46,11 @@ it('preserves bounded ordinary settings even when deselected, while explicit sam
expect(redactEnvironmentValues('true 3000', privateValues)).not.toContain('3000');
expect(redactEnvironmentValues('fixture-private-value', { DEBUG: 'fixture-private-value' })).toBe('[DEBUG]');
});
+
+it('does not turn ordinary scalar settings or MCP endpoint names into content credentials', () => {
+ const env = { SOME_FEATURE_ENABLED: 'true', RETRY_COUNT: '1', TEMPERATURE: '0.5' };
+ const secrets = importedContentRedactions({ env, mcp: [{ name: 'native-mcp', url: 'http://localhost:9000/native-mcp?enabled=true&retry=1' }, { name: 'touchdesigner-mcp', url: 'http://localhost:9001/touchdesigner-mcp' }], credentials: [] });
+ const text = 'sys.exit(1) action="store_true" <path d="M1 0.5"/> native-mcp touchdesigner-mcp';
+ expect(redactEnvironmentValues(text, secrets)).toBe(text);
+ expect(redactEnvironmentValues('secret=1', { API_KEY: '1' })).toBe('secret=[API_KEY]');
+});
diff --git a/apps/desktop/src/main/bot-import/__tests__/skillResources.test.ts b/apps/desktop/src/main/bot-import/__tests__/skillResources.test.ts
index acf49919da..8cc3b0e4a2 100644
--- a/apps/desktop/src/main/bot-import/__tests__/skillResources.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/skillResources.test.ts
@@ -30,3 +30,20 @@ it.each(['failure', 'owner-change'])('cleans original resources after %s without
await expect(fs.access(directory)).rejects.toThrow();
expect(environment.env).not.toHaveProperty('CINDY_IMPORTED_SKILLS');
});
+
+it('executes the preserved resource with credentials while keeping ordinary code readable', async () => {
+ const { importedContentRedactions } = await import('../connectionCatalog.js');
+ const { importedProcessEnvironment, runImportedProcess } = await import('../process.js');
+ const environment: CompanionEnvironment = { version: 1, env: { API_KEY: 'fixture-execution-token', FEATURE_ENABLED: 'true', RETRIES: '1' }, mcp: [], credentials: [] };
+ const script = 'const value = "store_true"; if (process.env.API_KEY !== "fixture-execution-token") process.exit(1); console.log(value);';
+ const projected = projectImportedSkill([{ name: 'run.cjs', bytes: Buffer.from(script), executable: true }], 'native-mcp', importedContentRedactions(environment));
+ expect(projected.files[0]!.bytes.toString()).toContain('process.exit(1)');
+ expect(projected.files[0]!.bytes.toString()).toContain('store_true');
+ expect(projected.files[0]!.bytes.toString()).not.toContain('fixture-execution-token');
+ environment.skillFiles = { 'native-mcp': projected.originals! };
+ const result = await withImportedSkillResources(environment, () => {}, async env => runImportedProcess({
+ command: process.execPath, args: [path.join(env.CINDY_IMPORTED_SKILLS!, 'native-mcp/run.cjs')], cwd: env.CINDY_IMPORTED_SKILLS!,
+ env: importedProcessEnvironment(env), timeoutMs: 5000, signal: new AbortController().signal, assertOwner() {},
+ }));
+ expect(result).toEqual({ stdout: 'store_true\n', exitCode: 0 });
+});
diff --git a/apps/desktop/src/main/bot-import/__tests__/sources.test.ts b/apps/desktop/src/main/bot-import/__tests__/sources.test.ts
index fb7a68048b..a8ae6d426e 100644
--- a/apps/desktop/src/main/bot-import/__tests__/sources.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/sources.test.ts
@@ -534,3 +534,21 @@ it('preserves sorted skill-name precedence after streaming directory entries', a
expect(items[0]!.sourceAlias).toBe('a-first');
expect(items[0]!.files![0]!.bytes.toString()).toContain('First');
});
+
+it.each(['hermes', 'openclaw'] as const)('discovers %s custom archives, hidden TXT corpus and attachments without conflating roots', async kind => {
+ await write(`.${kind}/${kind === 'hermes' ? 'config.yaml' : 'openclaw.json'}`, '{}');
+ const workspace = `.${kind}/${kind === 'hermes' ? '' : 'workspace/'}`;
+ await write(`${workspace}memory/semantic/knowledge/note.md`, 'Custom archive');
+ await write(`${workspace}memory/.dreams/session-corpus/session.txt`, 'Full transcript');
+ await write(`${workspace}memory/picture.png`, 'fixture image bytes');
+ if (kind === 'hermes') await write('.hermes/memories/note.md', 'Built-in memory');
+ else await write(`${workspace}DREAMS.md`, 'Dreams document');
+ const reader = deps(); const [source] = await discoverImportSources(reader);
+ const snapshot = await inspectImportSource(source!, reader);
+ const memory = snapshot.items.filter(item => item.view.category === 'memory');
+ expect(memory.map(item => item.text)).toContain('Custom archive');
+ expect(memory.map(item => item.text)).toContain('Full transcript');
+ expect(memory.find(item => item.asset)?.asset?.bytes.toString()).toBe('fixture image bytes');
+ expect(memory.map(item => item.text)).toContain(kind === 'hermes' ? 'Built-in memory' : 'Dreams document');
+ expect(new Set(memory.map(item => item.view.id)).size).toBe(memory.length);
+});
diff --git a/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts b/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts
index 135f091327..b271204df7 100644
--- a/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts
@@ -366,3 +366,27 @@ it('returns a completed legacy deferred receipt even after its checkpoint was re
expect(deps.createCompanion).not.toHaveBeenCalled();
expect(deps.pauseSource).not.toHaveBeenCalled();
});
+
+it('reports the creation error instead of a setup mapping warning when an automation has no usable input', async () => {
+ const { deps } = harness();
+ const source = { ...snapshot.source, kind: 'openclaw' as const };
+ const item = normalizeAutomation(source, { id: 'invalid', tools: { allow: ['read'] }, schedule: { kind: 'every', everyMs: 60_000 }, payload: {} }, [], 'UTC');
+ expect(item.view.issues).toEqual(['SOURCE_TOOL_POLICY_NEEDS_MAPPING', 'SOURCE_AUTOMATION_INVALID']);
+ const result = await transferCompanion({ ...snapshot, source, items: [item] }, { ...selection, entryIds: [item.view.id], deferSetup: true }, deps);
+ expect(result.checks).toContainEqual({ entryId: item.view.id, status: 'needs-attention', message: 'SOURCE_AUTOMATION_INVALID' });
+ expect(result.savedEntryIds).not.toContain(item.view.id);
+ expect(deps.createRoutine).not.toHaveBeenCalled();
+ expect(deps.pauseSource).not.toHaveBeenCalled();
+});
+
+it('preserves concrete memory failures and partial progress in a retryable receipt', async () => {
+ const { deps } = harness();
+ vi.mocked(deps.importItem).mockRejectedValueOnce(Object.assign(new Error('private disk path'), { code: 'ENOSPC', importProgress: { saved: 1, total: 3 } }));
+ const result = await transferCompanion(snapshot, selection, deps);
+ expect(result.checks).toContainEqual({ entryId: 'memory', status: 'needs-attention', message: 'IMPORT_DISK_FULL', progress: { saved: 1, total: 3 } });
+ expect(JSON.stringify(result)).not.toContain('private disk path');
+ expect(result.savedEntryIds).not.toContain('memory');
+ const retried = await transferCompanion(snapshot, selection, deps);
+ expect(retried.savedEntryIds).toContain('memory');
+ expect(retried.checks.find(check => check.entryId === 'memory')?.progress).toBeUndefined();
+});
diff --git a/apps/desktop/src/main/bot-import/connectionCatalog.ts b/apps/desktop/src/main/bot-import/connectionCatalog.ts
index b560920818..343d548a49 100644
--- a/apps/desktop/src/main/bot-import/connectionCatalog.ts
+++ b/apps/desktop/src/main/bot-import/connectionCatalog.ts
@@ -2,7 +2,7 @@ import type { Tool } from '@modelcontextprotocol/sdk/types.js';
import type { ImportedMcpServer } from './types.js';
import type { CompanionEnvironment } from './environment.js';
import { fingerprint } from './files.js';
-import { environmentRedactions, redactEnvironmentData, redactEnvironmentValues } from './process.js';
+import { environmentRedactions, isPublicImportSetting, redactEnvironmentData, redactEnvironmentValues } from './process.js';
/** Include resolved connection-local values without overwriting same-named imports. */
export function connectionRedactions(server: ImportedMcpServer, environment: Record<string, string>): Record<string, string> {
@@ -24,10 +24,21 @@ function urlCredentialValues(raw: string, includePath = false): string[] {
const values = [raw];
try {
const url = new URL(raw);
- values.push(url.username, url.password, ...url.searchParams.values());
- // URLSearchParams already decodes once; retain the wire representation too.
- for (const pair of url.search.slice(1).split('&')) if (pair.includes('=')) values.push(pair.slice(pair.indexOf('=') + 1));
- if (includePath) values.push(url.pathname, ...url.pathname.split('/').filter(Boolean));
+ values.push(url.username, url.password);
+ // Apply the same setting classification to decoded and wire query values.
+ for (const [name, value] of url.searchParams) if (!isPublicImportSetting(name, value)) values.push(value);
+ for (const pair of url.search.slice(1).split('&')) {
+ if (!pair.includes('=')) continue;
+ const params = new URLSearchParams(pair);
+ const [name, value] = [...params.entries()][0] ?? [];
+ if (name && value && !isPublicImportSetting(name, value)) values.push(pair.slice(pair.indexOf('=') + 1));
+ }
+ if (includePath) {
+ // Ordinary endpoint names are routing, not credentials. Keep the full URL
+ // private; mask only opaque path components that can carry access tokens.
+ const parts = url.pathname.split('/').filter(part => /(?:token|secret|credential|key)/i.test(part) || part.length >= 32 || part.length >= 20 && /[A-Z0-9_]/.test(part) || /%[0-9a-f]{2}/i.test(part));
+ values.push(...parts);
+ }
} catch { /* Invalid URLs fail at execution; never publish the literal in errors. */ }
return [...new Set(values.filter(value => value && value !== '/').flatMap(value => {
try { return [value, decodeURIComponent(value)]; } catch { return [value]; }
diff --git a/apps/desktop/src/main/bot-import/environment.ts b/apps/desktop/src/main/bot-import/environment.ts
index 406575b3fb..3b763ba120 100644
--- a/apps/desktop/src/main/bot-import/environment.ts
+++ b/apps/desktop/src/main/bot-import/environment.ts
@@ -38,6 +38,7 @@ export interface CompanionSecretIo {
read(key: string, assertOwner?: () => void): string | null | Promise<string | null>;
write(key: string, value: string, assertOwner?: () => void): boolean | Promise<boolean>;
remove(key: string): boolean;
+ removeResources?(botId: string, assertOwner: () => void): Promise<void>;
}
function bindingPath(userData: string, botId: string): string {
@@ -118,6 +119,8 @@ export function createCompanionEnvironmentStore(io: CompanionSecretIo) {
await queues.get(key)?.catch(() => {});
await Promise.allSettled([...(writes.get(key) ?? [])]);
assertOwner();
+ await io.removeResources?.(botId, assertOwner);
+ assertOwner();
store.remove(botId);
assertOwner();
// Rejected pre-profile imports have no profile-folder deletion step.
diff --git a/apps/desktop/src/main/bot-import/host.ts b/apps/desktop/src/main/bot-import/host.ts
index f103f9ebdc..ee409982f0 100644
--- a/apps/desktop/src/main/bot-import/host.ts
+++ b/apps/desktop/src/main/bot-import/host.ts
@@ -1,3 +1,4 @@
+import { companionImportReasonKey } from '@cindy/maker-shared/companion-import';
import { createMessage } from '../localDb/ipc/messages.js';
import { t } from '../i18n.js';
import { randomUUID } from 'node:crypto';
@@ -28,6 +29,7 @@ import { transferCompanion, validateImportSelection, validateImportRequestIdenti
import { CompanionImportError, type ImportItem, type ImportSnapshot, type ImportSource } from './types.js';
import { changeSourceAutomationState } from './takeover.js';
import { verifyImportedAutomation } from './verification.js';
+import { importMemoryMedia } from './memoryMedia.js';
import { projectImportedSkill } from './skillResources.js';
import { assertImportedAutomationReady } from './automationRuntime.js';
@@ -459,6 +461,13 @@ export async function startCompanionImport(selection: CompanionImportSelection,
await importBotSkillFiles(scope.root, botId, slug, projected.files, scope.assert, item.view.enabled !== false);
} else if (item.view.category === 'memory' || item.view.category === 'personality') {
const documents = [...(item.text ? [{ id: item.view.id, name: item.view.name, text: item.text, role: item.role }] : []), ...item.documents ?? []];
+ const attachments = [...(item.asset ? [item.asset] : []), ...(item.files ?? [])];
+ for (const file of attachments) {
+ const sessionId = await transferDeps.createConversation(botId);
+ const url = await importMemoryMedia(botId, sessionId, file.bytes, scope.assert);
+ documents.push({ id: `memory-${fingerprint([item.view.id, file.name]).slice(0, 32)}`, name: file.name,
+ text: `![${redactText(file.name).replace(/[\[\]\r\n]/g, '')}](${url})`, role: undefined });
+ }
for (const document of documents) {
scope.assert();
await getBotMemoryService().importDocument(botId, document.id, redactText(document.name), redactText(document.text), document.role === 'user' ? 'user' : 'reference');
@@ -605,8 +614,13 @@ export async function startCompanionImport(selection: CompanionImportSelection,
const pending = result.checks.some(check => check.status === 'needs-attention');
// Keep the legacy setup ID across upgrades, but do not let its
// idempotency key swallow the later successful completion message.
- await createMessage(result.canonicalSessionId, { clientId: `companion-import:${selection.requestId}${pending ? '' : ':ready'}`, role: 'assistant',
- content: t(`bots.import.${pending ? 'chatSetup' : 'chatReady'}`) });
+ const savedIds = new Set(result.savedEntryIds);
+ const unsaved = new Map(selected.filter(item => !savedIds.has(item.view.id)).map(item => [item.view.id, item]));
+ const failures = result.checks.filter(check => unsaved.has(check.entryId));
+ const details = failures.slice(0, 20).map(check => `${redactText(unsaved.get(check.entryId)?.view.name ?? check.entryId).slice(0, 160)} · ${t(`bots.import.${check.progress?.saved ? 'partlySaved' : 'notSaved'}`)} · ${t(`bots.import.${companionImportReasonKey(check.message)}`)}`).join('\n');
+ const partialKey = unsaved.size ? `:partial:${fingerprint(failures).slice(0, 16)}` : '';
+ await createMessage(result.canonicalSessionId, { clientId: `companion-import:${selection.requestId}${partialKey || (pending ? '' : ':ready')}`, role: 'assistant',
+ content: unsaved.size ? `${t('bots.import.chatPartial')}\n\n${details}${failures.length > 20 ? `\n… (${failures.length})` : ''}` : t(`bots.import.${pending ? 'chatSetup' : 'chatReady'}`) });
scope.assert();
}
if (result.status === 'complete') await companionEnvironmentStore.update(scope.root, result.botId, scope.assert, env => { delete env.pendingImport; });
diff --git a/apps/desktop/src/main/bot-import/memoryMedia.ts b/apps/desktop/src/main/bot-import/memoryMedia.ts
new file mode 100644
index 0000000000..4ad052d46e
--- /dev/null
+++ b/apps/desktop/src/main/bot-import/memoryMedia.ts
@@ -0,0 +1,34 @@
+import { createHash } from 'node:crypto';
+import { getDbClient } from '../localDb/client/current.js';
+import { ingestMedia } from '../cindy-media/ingest.js';
+import { hasRef, removeRefs } from '../cindy-media/ledger.js';
+import { captureMediaRefCompensationScope } from '../cindy-media/refCompensationJournal.js';
+import { sniffMediaMime } from '../cindy-media/sniffMediaMime.js';
+import { CompanionImportError } from './types.js';
+
+const reference = (botId: string) => ({ refKind: 'import' as const, refId: `companion-memory:${botId}` });
+
+/** Import originals through the media ledger; retries reuse this companion's reference. */
+export async function importMemoryMedia(botId: string, sessionId: string, bytes: Buffer, assertOwner: () => void): Promise<string> {
+ assertOwner();
+ const db = getDbClient().drizzle;
+ const scope = captureMediaRefCompensationScope();
+ const mimeType = sniffMediaMime(bytes);
+ if (!mimeType) throw new CompanionImportError('MEMORY_ATTACHMENT_UNSUPPORTED');
+ const hash = createHash('sha256').update(bytes).digest('hex');
+ const exists = await hasRef({ hash, ...reference(botId) }, db);
+ assertOwner();
+ const media = await ingestMedia({ buffer: bytes, mimeType, isCache: false,
+ refs: exists ? [] : [{ ...reference(botId), originSessionId: sessionId, originKind: 'user' }],
+ assertStillValid: assertOwner, refCompensationScope: scope }, db);
+ assertOwner();
+ return media.url;
+}
+
+/** The import owns originals until companion deletion, independent of editable memory text. */
+export async function removeImportedMemoryMedia(botId: string, assertOwner: () => void): Promise<void> {
+ assertOwner();
+ const db = getDbClient().drizzle;
+ await removeRefs(reference(botId), db);
+ assertOwner();
+}
diff --git a/apps/desktop/src/main/bot-import/openclawCron.ts b/apps/desktop/src/main/bot-import/openclawCron.ts
index 3edd7650fe..e6843ed3eb 100644
--- a/apps/desktop/src/main/bot-import/openclawCron.ts
+++ b/apps/desktop/src/main/bot-import/openclawCron.ts
@@ -2,6 +2,7 @@ import { createRequire } from 'node:module';
import path from 'node:path';
// eslint-disable-next-line no-restricted-imports -- Foreign database access belongs in an isolated read-only worker.
import { Worker } from 'node:worker_threads';
+import { resolveBetterSqliteNativeBinding } from '../localDb/betterSqliteFactory.js';
import { CompanionImportError } from './types.js';
export function readOpenClawCronDatabase(input: {
@@ -10,20 +11,20 @@ export function readOpenClawCronDatabase(input: {
return new Promise((resolve, reject) => {
const require = createRequire(typeof __filename === 'string' ? __filename : import.meta.url);
const worker = new Worker(path.join(__dirname, 'openclawCronWorker.js'), {
- workerData: { ...input, modulePath: require.resolve('better-sqlite3') },
+ workerData: { ...input, modulePath: require.resolve('better-sqlite3'), nativeBinding: resolveBetterSqliteNativeBinding() },
});
let settled = false;
- const finish = (jobs?: Record<string, unknown>[]) => {
+ const finish = (jobs?: Record<string, unknown>[], code = 'SOURCE_DATABASE_UNAVAILABLE') => {
if (settled) return;
settled = true;
clearTimeout(timer);
void worker.terminate().then(() => {
if (jobs) resolve(jobs);
- else reject(new CompanionImportError('SOURCE_DATABASE_UNAVAILABLE'));
- }, () => reject(new CompanionImportError('SOURCE_DATABASE_UNAVAILABLE')));
+ else reject(new CompanionImportError(code));
+ }, () => reject(new CompanionImportError(code)));
};
const timer = setTimeout(() => finish(), 15_000);
- worker.once('message', (message: { ok?: boolean; jobs?: Record<string, unknown>[] }) => finish(message.ok ? message.jobs : undefined));
+ worker.once('message', (message: { ok?: boolean; jobs?: Record<string, unknown>[]; code?: string }) => finish(message.ok ? message.jobs : undefined, ['SOURCE_DATABASE_DRIVER_UNAVAILABLE', 'SOURCE_DATABASE_TOO_LARGE', 'SOURCE_DATABASE_INVALID'].includes(message.code ?? '') ? message.code : undefined));
worker.on('error', () => finish());
worker.once('exit', () => finish());
});
diff --git a/apps/desktop/src/main/bot-import/openclawCronWorker.ts b/apps/desktop/src/main/bot-import/openclawCronWorker.ts
index 9d1fdb1c6d..b1f485fa6a 100644
--- a/apps/desktop/src/main/bot-import/openclawCronWorker.ts
+++ b/apps/desktop/src/main/bot-import/openclawCronWorker.ts
@@ -3,15 +3,15 @@ import { parentPort, workerData } from 'node:worker_threads';
import type Database from 'better-sqlite3';
/** Foreign SQLite reads stay off Electron main and include committed WAL content. */
-const { database, storeKey, agentId, defaultAgent, modulePath } = workerData as {
- database: string; storeKey: string; agentId: string; defaultAgent: boolean; modulePath: string;
+const { database, storeKey, agentId, defaultAgent, modulePath, nativeBinding } = workerData as {
+ database: string; storeKey: string; agentId: string; defaultAgent: boolean; modulePath: string; nativeBinding?: string;
};
let db: Database.Database | undefined;
try {
const require = createRequire(typeof __filename === 'string' ? __filename : import.meta.url);
const loaded = require(modulePath) as typeof Database | { default: typeof Database };
const Constructor = 'default' in loaded ? loaded.default : loaded;
- db = new Constructor(database, { readonly: true, fileMustExist: true, timeout: 5000 });
+ db = new Constructor(database, { readonly: true, fileMustExist: true, timeout: 5000, ...(nativeBinding ? { nativeBinding } : {}) });
const rows = db.prepare(`SELECT job_json, state_json FROM cron_jobs
WHERE store_key = ? AND (COALESCE(agent_id, owner_agent_id) = ?
OR (? = 1 AND COALESCE(agent_id, owner_agent_id) IS NULL))
@@ -22,11 +22,12 @@ try {
// Account for retained row/object overhead too, including empty JSON rows.
// Check before parsing or retaining this row, never materialize the result set.
bytes += Buffer.byteLength(row.job_json) + Buffer.byteLength(row.state_json) + 256;
- if (bytes > 16 * 1024 * 1024) throw new Error('limit');
+ if (bytes > 16 * 1024 * 1024) throw Object.assign(new Error('limit'), { code: 'SOURCE_DATABASE_TOO_LARGE' });
jobs.push({ ...JSON.parse(row.job_json), state: JSON.parse(row.state_json) });
}
parentPort?.postMessage({ ok: true, jobs });
-} catch {
+} catch (error) {
// SQL errors may include source paths/content; only a stable code crosses back.
- parentPort?.postMessage({ ok: false });
+ const code = (error as { code?: string }).code;
+ parentPort?.postMessage({ ok: false, code: code === 'ERR_DLOPEN_FAILED' || code === 'MODULE_NOT_FOUND' ? 'SOURCE_DATABASE_DRIVER_UNAVAILABLE' : code === 'SOURCE_DATABASE_TOO_LARGE' ? code : error instanceof SyntaxError ? 'SOURCE_DATABASE_INVALID' : 'SOURCE_DATABASE_UNAVAILABLE' });
} finally { db?.close(); }
diff --git a/apps/desktop/src/main/bot-import/process.ts b/apps/desktop/src/main/bot-import/process.ts
index 325bcddae7..4c5bd9a14b 100644
--- a/apps/desktop/src/main/bot-import/process.ts
+++ b/apps/desktop/src/main/bot-import/process.ts
@@ -54,7 +54,10 @@ export function runImportedProcess(input: {
/** Recognisable ordinary settings keep their meaning; arbitrary keys remain private. */
export function isPublicImportSetting(name: string, value: string): boolean {
- return /^(LANG|LANGUAGE|LC_ALL|LC_CTYPE)$/i.test(name) && /^(?:C|POSIX|[a-z]{2,3}(?:[_-][a-z]{2})?)(?:\.UTF-?8)?$/i.test(value)
+ return (!/(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|AUTH|CREDENTIAL|COOKIE)/i.test(name)
+ && /(?:^|_)(?:ENABLED|DISABLED|COUNT|RETRIES|RETRY|LIMIT|TIMEOUT|INTERVAL|SIZE|TEMPERATURE|TOP_P|HEADLESS|UNBUFFERED)(?:_|$)|^(?:MAX_|MIN_|PYTHONUNBUFFERED$)/i.test(name)
+ && /^(?:true|false|[+-]?\d+(?:\.\d+)?)$/i.test(value))
+ || /^(LANG|LANGUAGE|LC_ALL|LC_CTYPE)$/i.test(name) && /^(?:C|POSIX|[a-z]{2,3}(?:[_-][a-z]{2})?)(?:\.UTF-?8)?$/i.test(value)
|| /^(?:[A-Z0-9]+_)*REGION$/i.test(name) && /^(?:[a-z]{2}|global|[a-z]{2}(?:-[a-z]+)+-\d)$/i.test(value)
|| /^(?:DEBUG|VERBOSE|CI|NO_COLOR|FORCE_COLOR)$/i.test(name) && /^(?:true|false|0|1)$/i.test(value)
|| /^(?:PORT|HTTP_PORT|HTTPS_PORT|SERVER_PORT|APP_PORT)$/i.test(name) && /^\d{1,5}$/.test(value) && Number(value) <= 65535
diff --git a/apps/desktop/src/main/bot-import/runtime.ts b/apps/desktop/src/main/bot-import/runtime.ts
index 81a4ba4dc1..1a0f36e5c5 100644
--- a/apps/desktop/src/main/bot-import/runtime.ts
+++ b/apps/desktop/src/main/bot-import/runtime.ts
@@ -6,6 +6,7 @@ import { botEnvironmentSecretIo } from '../secrets/providerSecretStore.js';
import { createCompanionEnvironmentStore } from './environment.js';
import { fingerprint } from './files.js';
import { CompanionImportError } from './types.js';
+import { removeImportedMemoryMedia } from './memoryMedia.js';
import { closeInvalidImportedConnections } from './connections.js';
// Bot IDs are not reused. Retain a process-local deletion fence so a delayed DB
@@ -18,6 +19,7 @@ export const companionEnvironmentStore = createCompanionEnvironmentStore({
read: (key, assertOwner) => botEnvironmentSecretIo.read(key, assertOwner),
write: (key, value, assertOwner) => botEnvironmentSecretIo.write(key, value, assertOwner),
remove: key => botEnvironmentSecretIo.remove(key),
+ removeResources: removeImportedMemoryMedia,
});
/** Called only after profile deletion commits; failed deletions retain access. */
diff --git a/apps/desktop/src/main/bot-import/sources.ts b/apps/desktop/src/main/bot-import/sources.ts
index bc0705a8ac..1084bb5dcf 100644
--- a/apps/desktop/src/main/bot-import/sources.ts
+++ b/apps/desktop/src/main/bot-import/sources.ts
@@ -127,11 +127,15 @@ async function memoryDocuments(items: ImportItem[], root: string, prefix: string
const failed = (name: string, error: unknown, kind: 'file' | 'directory' | 'unknown') => items.push({ view: { id: entryId('memory', `${prefix}/${name}`), category: 'memory', name: name || prefix, selected: true },
sourceFile: { root: directory, file: path.join(directory, name), kind }, captureIssue: error instanceof CompanionImportError ? error.code : 'IMPORT_ITEM_FAILED' });
let files;
- try { files = await readImportTree(directory, name => /\.md$/i.test(name), budget, failed); }
+ try { files = await readImportTree(directory, undefined, budget, failed); }
catch (error) { failed('', error, 'directory'); return; }
- for (const file of files.filter(file => /\.md$/i.test(file.name))) {
+ for (const file of files) {
+ if (!/\.(md|txt)$/i.test(file.name)) {
+ items.push({ view: { id: entryId('memory', `${prefix}/${file.name}`), category: 'memory', name: `${prefix}/${file.name}`, selected: true }, asset: { name: `${prefix}/${file.name}`, bytes: file.bytes } });
+ continue;
+ }
if (!file.bytes.toString('utf8').trim()) continue;
- items.push({ view: { id: entryId('memory', `${prefix}/${file.name}`), category: 'memory', name: file.name, selected: true },
+ items.push({ view: { id: entryId('memory', `${prefix}/${file.name}`), category: 'memory', name: file.name, description: prefix, selected: true },
text: file.bytes.toString('utf8'), role: /(^|\/)USER\.md$/i.test(file.name) ? 'user' : undefined });
}
}
@@ -267,6 +271,10 @@ export async function inspectImportSource(source: ImportSource, deps: SourceRead
if (items.length !== before) break;
}
await memoryDocuments(items, source.root, 'memories', budget);
+ // Some installations keep their own archive alongside Hermes' built-in memories.
+ // Keep distinct paths/IDs; this does not redefine the upstream layout.
+ await memoryDocuments(items, source.root, 'memory', budget);
+ await document(items, source.root, 'MEMORY.md', undefined, 'memory', budget);
const raw = await optionalText(source.root, path.join(source.root, 'cron', 'jobs.json'), budget);
let decoded: unknown;
try { decoded = raw ? JSON.parse(raw) : []; } catch { throw new CompanionImportError('SOURCE_AUTOMATIONS_INVALID'); }
@@ -278,6 +286,7 @@ export async function inspectImportSource(source: ImportSource, deps: SourceRead
await document(items, workspace, 'USER.md', 'user', 'memory', budget);
await document(items, workspace, 'MEMORY.md', undefined, 'memory', budget);
await memoryDocuments(items, workspace, 'memory', budget);
+ await document(items, workspace, 'DREAMS.md', undefined, 'memory', budget);
const rows = agentRows(values);
const defaultAgent = (rows.find(row => row.default === true) ?? rows[0])?.id === source.agentId;
const storeKey = sourcePath(deps.home, string(object(values.cron).store) || path.join(source.root, 'cron', 'jobs.json'), source.root);
diff --git a/apps/desktop/src/main/bot-import/transfer.ts b/apps/desktop/src/main/bot-import/transfer.ts
index a3491151aa..52cf7e67ea 100644
--- a/apps/desktop/src/main/bot-import/transfer.ts
+++ b/apps/desktop/src/main/bot-import/transfer.ts
@@ -2,7 +2,7 @@ import { promises as fs } from 'node:fs';
import type { CompanionImportResult, CompanionImportSelection } from '@cindy/maker-shared/companion-import';
import type { RoutineInput } from '@cindy/maker-scheduler';
import { createImportBudget, fingerprint, readImportFile, readImportTree, reserveSnapshotItems, type ImportReadBudget } from './files.js';
-import { CompanionImportError, object, type ImportItem, type ImportSnapshot, type ImportSource } from './types.js';
+import { CompanionImportError, importFailureCode, object, type ImportItem, type ImportSnapshot, type ImportSource } from './types.js';
import { normalizeImportSkill } from './skills.js';
import { resolveImportEnvironmentDependencies, selectedImportEnvironment } from './environmentSelection.js';
@@ -116,8 +116,8 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com
receipt.deferSetup = selection.deferSetup === true;
const botId = receipt.result.botId;
const save = async () => { deps.assertOwner(); await deps.saveReceipt(receipt); deps.assertOwner(); };
- const check = (entryId: string, status: CompanionImportResult['checks'][number]['status'], message?: string) => {
- receipt.result.checks = [...receipt.result.checks.filter(item => item.entryId !== entryId), { entryId, status, ...(message ? { message } : {}) }];
+ const check = (entryId: string, status: CompanionImportResult['checks'][number]['status'], message?: string, progress?: { saved: number; total: number }) => {
+ receipt.result.checks = [...receipt.result.checks.filter(item => item.entryId !== entryId), { entryId, status, ...(message ? { message } : {}), ...(progress ? { progress } : {}) }];
};
receipt.result.status = 'running';
receipt.result.checks = receipt.result.checks.filter(item => item.entryId !== 'import');
@@ -137,14 +137,19 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com
// keep containment anchored to the original memory root in either case.
const directory = source.kind === 'directory' || source.kind !== 'file' && (await fs.stat(source.file)).isDirectory();
if (directory) {
- const files = await readImportTree(source.root, name => /\.md$/i.test(name), budget, undefined, source.file);
- item.documents = files.filter(file => file.bytes.toString('utf8').trim()).map(file => ({
+ const files = await readImportTree(source.root, undefined, budget, undefined, source.file);
+ item.files = files.filter(file => !/\.(md|txt)$/i.test(file.name));
+ item.documents = files.filter(file => /\.(md|txt)$/i.test(file.name) && file.bytes.toString('utf8').trim()).map(file => ({
id: recoveredDocumentId(`${item.view.id}-${fingerprint(file.name).slice(0, 20)}`), name: file.name, text: file.bytes.toString('utf8'),
...(/(^|\/)USER\.md$/i.test(file.name) ? { role: 'user' as const } : {}),
}));
- } else item.text = (await readImportFile(source.root, source.file, budget)).bytes.toString('utf8');
+ } else {
+ const file = await readImportFile(source.root, source.file, budget);
+ if (/\.(md|txt)$/i.test(file.name)) item.text = file.bytes.toString('utf8');
+ else item.asset = { name: file.name, bytes: file.bytes };
+ }
delete item.captureIssue;
- } catch (error) { item.captureIssue = error instanceof CompanionImportError ? error.code : 'IMPORT_ITEM_FAILED'; }
+ } catch (error) { item.captureIssue = importFailureCode(error); }
deps.assertOwner();
}
if (item.sourceDirectory && !item.filesComplete) {
@@ -171,7 +176,7 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com
delete item.captureIssue;
} catch (error) {
deps.assertOwner();
- item.captureIssue = error instanceof CompanionImportError ? error.code : 'IMPORT_ITEM_FAILED';
+ item.captureIssue = importFailureCode(error);
}
deps.assertOwner();
}
@@ -199,7 +204,7 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com
check(item.view.id, item.view.issues?.length ? 'needs-attention' : 'copied', item.view.issues?.[0]);
} catch (error) {
deps.assertOwner();
- check(item.view.id, 'needs-attention', error instanceof CompanionImportError ? error.code : 'IMPORT_ITEM_FAILED');
+ check(item.view.id, 'needs-attention', importFailureCode(error), (error as { importProgress?: { saved: number; total: number } })?.importProgress);
}
await save();
}
@@ -232,7 +237,7 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com
&& prior?.phase !== 'pausing-source' && prior?.phase !== 'source-paused') continue;
const automation = item.automation!;
if (!automation.input) {
- check(item.view.id, 'needs-attention', item.view.issues?.[0] ?? 'SOURCE_AUTOMATION_INVALID');
+ check(item.view.id, 'needs-attention', item.view.issues?.find(issue => !['SOURCE_TOOL_POLICY_NEEDS_MAPPING', 'AUTOMATION_MODEL_NEEDS_MAPPING'].includes(issue)) ?? 'SOURCE_AUTOMATION_INVALID');
await save(); continue;
}
let record = receipt.routines[item.view.id];
@@ -244,7 +249,7 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com
await save();
} catch (error) {
deps.assertOwner();
- check(item.view.id, 'needs-attention', error instanceof CompanionImportError ? error.code : 'IMPORT_ITEM_FAILED');
+ check(item.view.id, 'needs-attention', importFailureCode(error));
await save(); continue;
}
}
diff --git a/apps/desktop/src/main/bot-import/types.ts b/apps/desktop/src/main/bot-import/types.ts
index 44ea67e5cf..9bf304a583 100644
--- a/apps/desktop/src/main/bot-import/types.ts
+++ b/apps/desktop/src/main/bot-import/types.ts
@@ -89,3 +89,16 @@ export const object = (value: unknown): Record<string, unknown> =>
value !== null && typeof value === 'object' && !Array.isArray(value)
? value as Record<string, unknown> : {};
export const string = (value: unknown): string => typeof value === 'string' ? value : '';
+
+export function importFailureCode(error: unknown): string {
+ if (error instanceof CompanionImportError) return error.code;
+ const code = (error as { code?: string } | null)?.code;
+ const known: Record<string, string> = {
+ 'description-has-newline': 'MEMORY_METADATA_INVALID', 'description-too-long': 'MEMORY_DESCRIPTION_TOO_LONG', 'title-too-long': 'MEMORY_TITLE_TOO_LONG',
+ 'shard-too-large': 'MEMORY_CONTENT_TOO_LARGE', 'invalid-frontmatter': 'MEMORY_METADATA_INVALID',
+ 'version-conflict': 'MEMORY_CHANGED', 'already-exists': 'MEMORY_CHANGED',
+ 'not-ready': 'MEMORY_STORAGE_UNAVAILABLE', 'io-error': 'MEMORY_WRITE_FAILED',
+ ENOSPC: 'IMPORT_DISK_FULL', EACCES: 'IMPORT_PERMISSION_DENIED', EPERM: 'IMPORT_PERMISSION_DENIED',
+ };
+ return code && known[code] || 'IMPORT_ITEM_FAILED';
+}
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botMemoryService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botMemoryService.test.ts
index b8ed0f3caf..29cf87f011 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botMemoryService.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botMemoryService.test.ts
@@ -231,3 +231,37 @@ it('imports long original memory into the real index without losing Unicode, and
expect(restored.map(row => row.body).join('')).toBe(original);
expect(await fs.readFile(path.join(dir, 'MEMORY.md'), 'utf8')).toContain(entries[0]!.filename);
});
+
+it('round-trips emoji summaries, source frontmatter, blank lines and all parts through real storage', async () => {
+ const { service } = setup();
+ const original = '---\ntitle: Source title\n---\n' + '🙂'.repeat(110) + '\n\n' + ('段落 abc 🙂 '.repeat(1500)) + '\n ';
+ await service.importDocument('bot-1', 'complete-source', '🙂'.repeat(90), original);
+ await service.importDocument('bot-1', 'complete-source', '🙂'.repeat(90), original);
+ const records = (await storage.list()).filter(record => record.filename.startsWith('reference_import_complete-source_'))
+ .sort((a, b) => Number(a.filename.match(/_(\d+)\.md$/)![1]) - Number(b.filename.match(/_(\d+)\.md$/)![1]));
+ expect(records.length).toBeGreaterThan(2);
+ expect(records.map(record => record.body).join('')).toBe(original);
+ for (const record of records) expect(record.frontmatter.description.length).toBeLessThanOrEqual(200);
+});
+
+it('reports a partial document write and retries missing chunks without duplicating or replacing saved content', async () => {
+ const { service } = setup();
+ const original = ' ' + 'x'.repeat(18000) + '\n\nlast paragraph 🙂';
+ const write = storage.write.bind(storage);
+ let fail = true;
+ vi.spyOn(storage, 'write').mockImplementation(async opts => {
+ if (fail && opts.name.endsWith('_1')) throw Object.assign(new Error('private filesystem detail'), { code: 'ENOSPC' });
+ return write(opts);
+ });
+ await expect(service.importDocument('bot-1', 'retry-document', 'retry', original)).rejects.toMatchObject({ code: 'ENOSPC', importProgress: { saved: 1, total: 3 } });
+ const first = await storage.read('reference_import_retry-document_0.md');
+ fail = false;
+ await service.importDocument('bot-1', 'retry-document', 'retry', original);
+ const parts = await Promise.all([0, 1, 2].map(index => storage.read(`reference_import_retry-document_${index}.md`)));
+ expect(parts.map(part => part.body).join('')).toBe(original);
+ expect(parts[0].frontmatter.updatedAt).toBe(first.frontmatter.updatedAt);
+ // A user edit through the filesystem must not be hidden by stale serialization metadata.
+ await fs.appendFile(path.join(dir, first.filename), '\nUser added this later.');
+ expect((await storage.read(first.filename)).body).toContain('User added this later.');
+ await expect(service.importDocument('bot-1', 'retry-document', 'retry', original)).rejects.toThrow('PRECONDITION_FAILED');
+});
diff --git a/apps/desktop/src/main/maker-ipc/botMemoryService.ts b/apps/desktop/src/main/maker-ipc/botMemoryService.ts
index 0fc9ddb8ce..5146fbd4ba 100644
--- a/apps/desktop/src/main/maker-ipc/botMemoryService.ts
+++ b/apps/desktop/src/main/maker-ipc/botMemoryService.ts
@@ -68,7 +68,7 @@ function plainText(body: string): string {
export function botMemoryDescriptionFromBody(body: string): string {
const text = plainText(body);
const sentence = /^.+?[。!?!?;;](?=\s|$|[^。!?!?;;])/u.exec(text)?.[0] ?? text;
- return Array.from(sentence).slice(0, DESCRIPTION_MAX).join('').trim();
+ return sentence.slice(0, DESCRIPTION_MAX).replace(/[\uD800-\uDBFF]$/u, '').trim();
}
function preview(body: string): string {
@@ -203,22 +203,28 @@ export function createBotMemoryService(deps: BotMemoryServiceDeps) {
}
if (chunk) chunks.push(chunk);
for (const [index, body] of chunks.entries()) {
- if (!body.trim()) continue;
+ // Whitespace inside a source document is content too.
+ if (!body) continue;
const name = `import_${id}_${index}`;
- await serialized(`${botId}/${type}_${name}.md`, async () => {
+ try { await serialized(`${botId}/${type}_${name}.md`, async () => {
owner.assertCurrent?.();
const existing = await store.read(`${type}_${name}.md`).catch(error => {
if (error instanceof MemoryError && error.code === 'not-found') return null;
throw error;
});
if (existing) {
- if (existing.body.trim() !== body.trim()) throwIpcError('PRECONDITION_FAILED', 'Imported memory was edited');
+ if (existing.body.trim() !== body.trim()) throw new MemoryError('version-conflict', '[PRECONDITION_FAILED] Imported memory was edited');
return;
}
- await store.write({ type, name, title: Array.from(title).slice(0, BOT_MEMORY_TITLE_MAX).join(''),
- description: botMemoryDescriptionFromBody(body) || title.slice(0, DESCRIPTION_MAX), body });
+ await store.write({ type, name, title: title.slice(0, BOT_MEMORY_TITLE_MAX).replace(/[\uD800-\uDBFF]$/u, ''),
+ description: botMemoryDescriptionFromBody(body) || botMemoryDescriptionFromBody(title) || id, body, preserveBody: true });
+ const saved = await store.read(`${type}_${name}.md`);
+ if (saved.body !== body) throw new MemoryError('io-error', 'Imported content readback mismatch');
owner.assertCurrent?.();
- });
+ }); } catch (error) {
+ if (error instanceof Error) Object.assign(error, { importProgress: { saved: index, total: chunks.length } });
+ throw error;
+ }
}
scheduleRefresh(owner);
},
diff --git a/apps/desktop/src/main/routines/__tests__/service.test.ts b/apps/desktop/src/main/routines/__tests__/service.test.ts
index fe0945f8c0..095c5d52d7 100644
--- a/apps/desktop/src/main/routines/__tests__/service.test.ts
+++ b/apps/desktop/src/main/routines/__tests__/service.test.ts
@@ -582,3 +582,25 @@ it('passes the saved reminder choice and check into the shared runner and return
await vi.waitFor(async () => expect((await routineTools.history('bot', routine.id))[0].status).toBe('skipped'));
expect(mock.storage.insert).toHaveBeenCalledWith(expect.objectContaining({ targetSessionId: 'canonical-task', silentWhenIdle: false, preRunHook }));
});
+
+it('persists all imported paused routines before tool-policy setup and never dispatches them', async () => {
+ const { normalizeAutomation } = await import('../../bot-import/sourceAutomations.js');
+ const guard = vi.fn(async () => { throw new Error('SOURCE_TOOL_POLICY_NEEDS_MAPPING'); });
+ configureRoutineHost({ getBot: mock.getBot, getScheduler: () => mock.scheduler, getScheduleStorage: () => mock.storage, assertImportedAutomationReady: guard });
+ for (let index = 0; index < 11; index++) {
+ const item = normalizeAutomation({ agentId: 'source', kind: 'openclaw', name: 'Source', root: '/fixture', workspace: '/fixture', configFile: '/fixture/openclaw.json' }, {
+ id: `report-${index}`, name: `Report ${index}`, enabled: false,
+ schedule: { kind: 'every', everyMs: 60_000 }, payload: { message: 'Read the report' },
+ ...(index < 4 ? { tools: { allow: ['read'] } } : {}),
+ }, [], 'UTC');
+ expect(item.automation?.input).toBeDefined();
+ if (index < 4) expect(item.view.issues).toContain('SOURCE_TOOL_POLICY_NEEDS_MAPPING');
+ await routineTools.createOnce('bot', item.automation!.input!, `imported-report-${index}`);
+ }
+ expect(guard).not.toHaveBeenCalled();
+ const routines = await routineTools.list('bot');
+ expect(routines).toHaveLength(11);
+ expect(routines.every(routine => !routine.enabled)).toBe(true);
+ expect(mock.scheduler.runNow).not.toHaveBeenCalled();
+ await expect(routineTools.runNow('bot', routines[0].id)).rejects.toThrow('SOURCE_TOOL_POLICY_NEEDS_MAPPING');
+});
diff --git a/apps/desktop/src/renderer/features/bots/BotImportForm.tsx b/apps/desktop/src/renderer/features/bots/BotImportForm.tsx
index 93f3a22cb4..81994283aa 100644
--- a/apps/desktop/src/renderer/features/bots/BotImportForm.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotImportForm.tsx
@@ -1,7 +1,7 @@
import { useEffect, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
-import { compactCompanionImportSelection, areCompanionImportEntriesSelected, toggleCompanionImportEntries, companionImportCategories, type CompanionImportCategory, type CompanionImportApi, type CompanionImportPreview, type CompanionImportResult, type CompanionImportSelection, type CompanionImportSource } from '@cindy/maker-shared/companion-import';
+import { companionImportReasonKey, companionImportErrorCode, compactCompanionImportSelection, areCompanionImportEntriesSelected, toggleCompanionImportEntries, companionImportCategories, type CompanionImportCategory, type CompanionImportApi, type CompanionImportPreview, type CompanionImportResult, type CompanionImportSelection, type CompanionImportSource } from '@cindy/maker-shared/companion-import';
import { normalizeBotName } from '../../../shared/botCreation';
import { BOT_PORTRAIT_COUNT, BotPortraitPicker, galleryPortrait } from './BotPortraitPicker';
import { useBotProfiles } from './botStore';
@@ -25,16 +25,19 @@ export function BotImportForm({ api = window.electronAPI.companionImport, onBack
const [page, setPage] = useState(0);
const [takeover, setTakeover] = useState(true);
const [busy, setBusy] = useState(false);
- const [error, setError] = useState(false);
+ const [error, setError] = useState<string>();
+ const [details, setDetails] = useState(false);
+ const [detailPage, setDetailPage] = useState(0);
const [result, setResult] = useState<CompanionImportResult>();
+ useEffect(() => setDetailPage(0), [result]);
const intent = useRef<CompanionImportSelection | undefined>(undefined);
const alive = useRef(true);
const lock = useRef(false);
const duplicate = bots.some(bot => bot.id !== result?.botId && bot.status !== 'archived' && normalizeBotName(bot.name) === normalizeBotName(name));
- useEffect(() => { alive.current = true; void api.sources().then(value => { if (alive.current) setSources(value); }).catch(() => { if (alive.current) setError(true); }); return () => { alive.current = false; }; }, [api]);
+ useEffect(() => { alive.current = true; void api.sources().then(value => { if (alive.current) setSources(value); }).catch(cause => { if (alive.current) setError(companionImportErrorCode(cause) ?? 'IMPORT_ITEM_FAILED'); }); return () => { alive.current = false; }; }, [api]);
const act = async (fn: () => Promise<void>) => {
if (lock.current) return;
- lock.current = true; setBusy(true); onBusy(true); setError(false);
+ lock.current = true; setBusy(true); onBusy(true); setError(undefined);
try { await fn(); } catch (cause) {
const code = extractIpcError(cause)?.code;
// Only definitive creation/preflight rejections unlock editing. An ambiguous ACK
@@ -49,7 +52,7 @@ export function BotImportForm({ api = window.electronAPI.companionImport, onBack
// Host restarts invalidate source IDs too. Reuse the existing source step.
try { const refreshed = await api.sources(); if (alive.current) setSources(refreshed); } catch { /* Existing source buttons allow another attempt. */ }
}
- if (alive.current) setError(true);
+ if (alive.current) setError(companionImportErrorCode(cause) ?? 'IMPORT_ITEM_FAILED');
}
finally { lock.current = false; if (alive.current) { setBusy(false); onBusy(false); } }
};
@@ -77,6 +80,9 @@ export function BotImportForm({ api = window.electronAPI.companionImport, onBack
const selectedSet = new Set(selected);
const locked = busy || !!intent.current;
const saved = !!result?.saved || result?.status === 'complete';
+ const outstanding = result?.checks.filter(check => check.status === 'needs-attention') ?? [];
+ const savedIds = new Set(result?.savedEntryIds);
+ const incomplete = result?.savedEntryIds ? selected.some(id => !savedIds.has(id)) : outstanding.some(check => check.message === 'IMPORT_ITEM_FAILED');
const finished = result && result.status !== 'running';
const categoryEntries = preview?.entries.filter(entry => entry.category === category) ?? [];
const filtered = categoryEntries.filter(entry => `${entry.name} ${entry.description ?? ''}`.toLocaleLowerCase().includes(query.toLocaleLowerCase()));
@@ -87,15 +93,26 @@ export function BotImportForm({ api = window.electronAPI.companionImport, onBack
return <div className="flex min-h-0 flex-col gap-5">
<div className="min-h-0 space-y-5 overflow-y-auto">
{finished && saved ? <div role="status" className="space-y-5">
- <p className="text-16 font-medium text-[var(--text-primary)]">{tr('complete')}</p>
+ <p className="text-16 font-medium text-[var(--text-primary)]">{tr(incomplete ? 'partial' : 'complete')}</p>
<div className="divide-y divide-[var(--border-default)]">
{companionImportCategories.map(group => {
const ids = new Set(preview?.entries.filter(entry => entry.category === group).map(entry => entry.id));
const count = result.savedEntryIds ? result.savedEntryIds.filter(id => ids.has(id)).length : result.checks.filter(check => ids.has(check.entryId) && check.status !== 'needs-attention').length;
if (!ids.size) return null;
- return <div key={group} className="flex items-center justify-between gap-3 py-3 text-14"><span>{tr(group)}</span><span className="text-[var(--text-secondary)]">{count}</span></div>;
+ return <div key={group} className="flex items-center justify-between gap-3 py-3 text-14"><span>{tr(group)}</span><span className="text-[var(--text-secondary)]">{count} / {selected.filter(id => ids.has(id)).length}</span></div>;
})}
</div>
+ {outstanding.length ? <>
+ <Button variant="secondary" onClick={() => { setDetails(!details); setDetailPage(0); }}>{tr('details')} · {outstanding.length}</Button>
+ {details ? <div className="space-y-3">
+ {outstanding.slice(detailPage * 20, (detailPage + 1) * 20).map(check => <div key={check.entryId} className="break-words text-13">
+ <p className="text-[var(--text-primary)]">{preview?.entries.find(entry => entry.id === check.entryId)?.name ?? tr('itemAttention')}</p>
+ <p className="text-[var(--text-secondary)]">{tr(check.progress?.saved ? 'partlySaved' : savedIds.has(check.entryId) ? 'savedNeedsSetup' : 'notSaved')} · {tr(companionImportReasonKey(check.message))}</p>
+ {check.progress ? <p className="text-[var(--text-secondary)]">{check.progress.saved} / {check.progress.total}</p> : null}
+ </div>)}
+ {outstanding.length > 20 ? <div className="flex justify-between gap-3"><Button variant="secondary" disabled={detailPage === 0} onClick={() => setDetailPage(detailPage - 1)}>{tr('previous')}</Button><span>{detailPage + 1} / {Math.ceil(outstanding.length / 20)}</span><Button variant="secondary" disabled={(detailPage + 1) * 20 >= outstanding.length} onClick={() => setDetailPage(detailPage + 1)}>{tr('next')}</Button></div> : null}
+ </div> : null}
+ </> : null}
</div> : result?.status === 'running' ? <div role="status" className="space-y-3 py-5">
<p className="text-16 font-medium">{tr('running')}</p>
<p className="text-13 text-[var(--text-secondary)]">{result.checks.length} / {selected.length}</p>
@@ -139,11 +156,11 @@ export function BotImportForm({ api = window.electronAPI.companionImport, onBack
</div>
{preview.entries.some(entry => entry.category === 'automations' && selectedSet.has(entry.id)) ? <label className="flex items-start gap-3 text-13"><input type="checkbox" checked={takeover} disabled={locked} onChange={event => setTakeover(event.target.checked)} className="mt-1 h-4 w-4 shrink-0 accent-[var(--text-primary)]" /><span>{tr('takeover')}</span></label> : null}
</>}
- {(error || duplicate) && !saved ? <p role="alert" className="text-13 text-[var(--text-danger)]">{duplicate ? t('bots.guided.duplicateName') : tr('error')}</p> : null}
+ {(error || duplicate) ? <p role="alert" className="text-13 text-[var(--text-danger)]">{duplicate ? t('bots.guided.duplicateName') : tr(companionImportReasonKey(error))}</p> : null}
</div>
<div className="flex shrink-0 flex-wrap justify-between gap-3 py-3">
{!saved ? <Button variant="secondary" size="lg" disabled={busy} onClick={() => category ? setCategory(undefined) : onBack()}>{tr('back')}</Button> : null}
- {finished ? <>{!saved ? <Button variant="secondary" size="lg" disabled={busy} onClick={() => void submit()}>{tr('retry')}</Button> : null}<Button variant="cta" size="lg" className={saved ? 'ml-auto' : undefined} disabled={!result.canonicalSessionId} onClick={() => onCreated(result.botId)}>{tr('open')}</Button></> : preview && !category ? <Button variant="cta" size="lg" loading={busy} disabled={busy || !name.trim() || !portrait || duplicate} onClick={() => void submit()}>{tr('submit')}</Button> : null}
+ {finished ? <>{!saved || incomplete ? <Button variant="secondary" size="lg" disabled={busy} onClick={() => void submit()}>{tr('retry')}</Button> : null}<Button variant="cta" size="lg" className={saved ? 'ml-auto' : undefined} disabled={!result.canonicalSessionId} onClick={() => onCreated(result.botId)}>{tr('open')}</Button></> : preview && !category ? <Button variant="cta" size="lg" loading={busy} disabled={busy || !name.trim() || !portrait || duplicate} onClick={() => void submit()}>{tr('submit')}</Button> : null}
</div>
</div>;
}
diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botImport.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botImport.test.tsx
index 4624ea1132..13163c82fb 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botImport.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botImport.test.tsx
@@ -171,3 +171,29 @@ it('shows 142 selected skills in a flat searchable paginated list and opens chat
expect(screen.queryByRole('alert')).toBeNull();
expect(screen.queryByRole('button', { name: 'bots.import.retry' })).toBeNull();
});
+
+it('distinguishes partial saves, setup-only checks and failed automations while leaving chat and retry available', async () => {
+ const entries = [
+ { id: 'partial', name: 'long-document.md', category: 'memory' as const, selected: true },
+ { id: 'saved', name: 'ready.md', category: 'memory' as const, selected: true },
+ { id: 'routine', name: 'Daily report', category: 'automations' as const, selected: true },
+ ];
+ const api: CompanionImportApi = { sources: async () => [{ id: 'source', name: 'Ada', kind: 'hermes' }],
+ preview: async () => ({ id: 'preview', name: 'Ada', source: { id: 'source', name: 'Ada', kind: 'hermes' }, entries }), status: async () => undefined,
+ start: vi.fn(async input => ({ requestId: input.requestId, botId: 'bot', canonicalSessionId: 'chat', saved: true, savedEntryIds: ['saved'], status: 'needs-attention' as const,
+ checks: [{ entryId: 'partial', status: 'needs-attention' as const, message: 'IMPORT_DISK_FULL', progress: { saved: 1, total: 3 } }, { entryId: 'routine', status: 'needs-attention' as const, message: 'SOURCE_AUTOMATION_INVALID' }] })) };
+ const created = vi.fn();
+ render(<BotImportForm api={api} onCreated={created} onBack={() => {}} onBusy={() => {}} />);
+ fireEvent.click(await screen.findByRole('button', { name: /Ada.*Hermes/ }));
+ fireEvent.click(await screen.findByRole('button', { name: 'bots.import.submit' }));
+ await screen.findByText('bots.import.partial');
+ expect(screen.queryByText('bots.import.complete')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: /bots.import.details/ }));
+ expect(screen.getByText('long-document.md')).toBeTruthy();
+ expect(screen.getByText(/bots.import.partlySaved.*bots.import.diskFull/)).toBeTruthy();
+ expect(screen.getByText('1 / 3')).toBeTruthy();
+ expect(screen.getByText(/bots.import.notSaved.*bots.import.automationInvalid/)).toBeTruthy();
+ expect(screen.getByRole('button', { name: 'bots.import.retry' })).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'bots.import.open' }));
+ expect(created).toHaveBeenCalledWith('bot');
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index 84ec7940b6..3b25596a6f 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8287,7 +8287,25 @@
"previous": "Previous",
"next": "Next",
"chatSetup": "Your imported information is saved. We can start talking. Some items still need a login or a check; we can finish those whenever you are ready. Source automations stay unchanged until takeover.",
- "chatReady": "Your information has been imported. We can start talking."
+ "chatReady": "Your information has been imported. We can start talking.",
+ "partial": "Some content was not fully imported",
+ "details": "View import details",
+ "partlySaved": "Partially saved",
+ "savedNeedsSetup": "Saved; setup or activation remains",
+ "notSaved": "Not saved",
+ "databaseDriver": "The database driver could not load. Update or repair Cindy, then retry.",
+ "databaseUnavailable": "The source database could not be read. Original data is unchanged; retry after repair.",
+ "fileTooLarge": "A file or this import exceeds the read limit. Content was not truncated.",
+ "memoryMetadata": "The memory summary or title exceeds storage requirements.",
+ "memoryWrite": "Memory writing or integrity verification failed. You can retry.",
+ "memoryChanged": "The saved memory was changed and has not been overwritten.",
+ "attachmentUnsupported": "This attachment format is not supported yet. The original remains at the source.",
+ "diskFull": "Disk space is insufficient. Free space, then retry.",
+ "permissionDenied": "Permission to read or save this item is missing. Fix permissions, then retry.",
+ "setupDeferred": "Continue sign-in and verification in the teammate chat.",
+ "automationInvalid": "The automation definition could not be converted; it was not created.",
+ "itemFailed": "This item is unfinished. Retry or view import details.",
+ "chatPartial": "Your teammate is created, but some content was not fully saved. The items below still need attention; other content and chat remain available."
}
},
"common": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index f664e46f96..a1b51b900d 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8285,7 +8285,25 @@
"previous": "前のページ",
"next": "次のページ",
"chatSetup": "取り込める情報を保存しました。すぐに会話を始められます。ログインや確認が必要な項目は、都合のよいときに進めましょう。引き継ぎが完了するまで、元の自動化の状態は変わりません。",
- "chatReady": "情報をインポートしました。会話を始められます。"
+ "chatReady": "情報をインポートしました。会話を始められます。",
+ "partial": "一部の内容は完全にインポートされていません",
+ "details": "インポートの詳細",
+ "partlySaved": "一部のみ保存済み",
+ "savedNeedsSetup": "保存済み・設定または有効化が必要",
+ "notSaved": "未保存",
+ "databaseDriver": "データベースドライバーを読み込めません。Cindy を更新または修復して再試行してください。",
+ "databaseUnavailable": "元のデータベースを読み込めません。元データは変更されていません。修復後に再試行できます。",
+ "fileTooLarge": "ファイルまたはインポート全体が読み取り上限を超えています。内容は切り捨てていません。",
+ "memoryMetadata": "メモリの概要またはタイトルが保存要件を満たしていません。",
+ "memoryWrite": "メモリの保存または整合性確認に失敗しました。再試行できます。",
+ "memoryChanged": "保存済みのメモリが変更されているため、上書きしていません。",
+ "attachmentUnsupported": "この添付形式にはまだ対応していません。元ファイルはインポート元に残っています。",
+ "diskFull": "ディスク容量が不足しています。空きを確保して再試行してください。",
+ "permissionDenied": "読み取りまたは保存の権限がありません。権限を修正して再試行してください。",
+ "setupDeferred": "パートナーとのチャットでログインと確認を続けられます。",
+ "automationInvalid": "自動化の定義を変換できず、作成されていません。",
+ "itemFailed": "この項目は未完了です。再試行するか詳細を確認してください。",
+ "chatPartial": "パートナーは作成されましたが、一部の情報は完全に保存されていません。以下の項目は対応が必要です。他の情報とチャットは利用できます。"
}
},
"common": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 828d79c0ca..bcebc25e74 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8285,7 +8285,25 @@
"previous": "이전 페이지",
"next": "다음 페이지",
"chatSetup": "가져올 수 있는 자료를 저장했어요. 바로 대화를 시작할 수 있어요. 로그인이나 확인이 필요한 항목은 편할 때 마무리하면 돼요. 인계가 끝날 때까지 기존 자동화 상태는 그대로 유지돼요.",
- "chatReady": "정보를 가져왔습니다. 이제 대화를 시작할 수 있어요."
+ "chatReady": "정보를 가져왔습니다. 이제 대화를 시작할 수 있어요.",
+ "partial": "일부 내용을 완전히 가져오지 못했습니다",
+ "details": "가져오기 세부 정보",
+ "partlySaved": "일부만 저장됨",
+ "savedNeedsSetup": "저장됨 · 설정 또는 활성화 필요",
+ "notSaved": "저장되지 않음",
+ "databaseDriver": "데이터베이스 드라이버를 불러올 수 없습니다. Cindy를 업데이트하거나 복구한 뒤 다시 시도하세요.",
+ "databaseUnavailable": "원본 데이터베이스를 읽을 수 없습니다. 원본은 변경되지 않았으며 복구 후 다시 시도할 수 있습니다.",
+ "fileTooLarge": "파일 또는 전체 자료가 읽기 한도를 초과했습니다. 내용을 잘라서 가져오지 않았습니다.",
+ "memoryMetadata": "기억 요약 또는 제목이 저장 요건에 맞지 않습니다.",
+ "memoryWrite": "기억 저장 또는 무결성 확인에 실패했습니다. 다시 시도할 수 있습니다.",
+ "memoryChanged": "저장된 기억이 변경되어 덮어쓰지 않았습니다.",
+ "attachmentUnsupported": "아직 지원하지 않는 첨부 형식입니다. 원본 파일은 소스에 남아 있습니다.",
+ "diskFull": "디스크 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요.",
+ "permissionDenied": "읽기 또는 저장 권한이 없습니다. 권한을 수정한 뒤 다시 시도하세요.",
+ "setupDeferred": "파트너 채팅에서 로그인과 확인을 계속할 수 있습니다.",
+ "automationInvalid": "자동화 정의를 변환할 수 없어 생성되지 않았습니다.",
+ "itemFailed": "아직 완료되지 않은 항목입니다. 다시 시도하거나 세부 정보를 확인하세요.",
+ "chatPartial": "파트너가 생성되었지만 일부 자료는 완전히 저장되지 않았습니다. 아래 항목은 추가 처리가 필요하며 다른 내용과 채팅은 계속 사용할 수 있습니다."
}
},
"common": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
index b02efa72b3..cf51fc56b9 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8285,7 +8285,25 @@
"previous": "上一页",
"next": "下一页",
"chatSetup": "已保存可导入的资料,可以开始交流了。部分内容还需要登录或检查,你方便时我们再继续。接管前,原来的自动化保持原状。",
- "chatReady": "资料已经导入,可以开始交流了。"
+ "chatReady": "资料已经导入,可以开始交流了。",
+ "partial": "部分内容未完整导入",
+ "details": "查看导入详情",
+ "partlySaved": "仅部分保存",
+ "savedNeedsSetup": "已保存,尚未启用或完成设置",
+ "notSaved": "未保存",
+ "databaseDriver": "数据库驱动无法加载,请更新或修复 Cindy 后重试。",
+ "databaseUnavailable": "无法读取来源数据库,原数据未改动。修复后可重试。",
+ "fileTooLarge": "文件或本次资料超过读取上限,未截断导入。",
+ "memoryMetadata": "记忆摘要或标题不符合存储要求。",
+ "memoryWrite": "记忆写入或完整性检查失败,可重试。",
+ "memoryChanged": "已保存的记忆发生变化,未覆盖。",
+ "attachmentUnsupported": "此附件格式暂不支持,原文件保留在来源。",
+ "diskFull": "磁盘空间不足,释放空间后可重试。",
+ "permissionDenied": "没有权限读取或保存此项,修复权限后可重试。",
+ "setupDeferred": "可在伙伴对话中继续登录与验证。",
+ "automationInvalid": "自动化定义无法转换,尚未创建。",
+ "itemFailed": "此项未完成,可重试并查看导入详情。",
+ "chatPartial": "伙伴已创建,但部分资料未完整保存。以下项目仍需处理;其他内容和对话可以正常使用。"
}
},
"common": {
diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
index 3373b7887c..a5d0a6b8e0 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8285,7 +8285,25 @@
"previous": "上一頁",
"next": "下一頁",
"chatSetup": "已儲存可匯入的資料,可以開始交流了。部分內容還需要登入或檢查,你方便時我們再繼續。接管前,原來的自動化保持原狀。",
- "chatReady": "資料已經匯入,可以開始交流了。"
+ "chatReady": "資料已經匯入,可以開始交流了。",
+ "partial": "部分內容未完整匯入",
+ "details": "查看匯入詳情",
+ "partlySaved": "僅部分儲存",
+ "savedNeedsSetup": "已儲存,尚未啟用或完成設定",
+ "notSaved": "未儲存",
+ "databaseDriver": "資料庫驅動程式無法載入,請更新或修復 Cindy 後重試。",
+ "databaseUnavailable": "無法讀取來源資料庫,原資料未變更。修復後可重試。",
+ "fileTooLarge": "檔案或本次資料超過讀取上限,未截斷匯入。",
+ "memoryMetadata": "記憶摘要或標題不符合儲存要求。",
+ "memoryWrite": "記憶寫入或完整性檢查失敗,可重試。",
+ "memoryChanged": "已儲存的記憶發生變更,未覆寫。",
+ "attachmentUnsupported": "此附件格式暫不支援,原檔案保留在來源。",
+ "diskFull": "磁碟空間不足,釋放空間後可重試。",
+ "permissionDenied": "沒有權限讀取或儲存此項,修復權限後可重試。",
+ "setupDeferred": "可在夥伴對話中繼續登入與驗證。",
+ "automationInvalid": "自動化定義無法轉換,尚未建立。",
+ "itemFailed": "此項未完成,可重試並查看匯入詳情。",
+ "chatPartial": "夥伴已建立,但部分資料未完整儲存。以下項目仍需處理;其他內容和對話可以正常使用。"
}
},
"common": {
diff --git a/apps/desktop/src/shared/ipc-errors.ts b/apps/desktop/src/shared/ipc-errors.ts
index 3c51b9c90d..0a7ebd8cd3 100644
--- a/apps/desktop/src/shared/ipc-errors.ts
+++ b/apps/desktop/src/shared/ipc-errors.ts
@@ -49,6 +49,9 @@ export const COMPANION_IMPORT_ERROR_CODES = [
'SOURCE_CONFIG_INVALID',
'SOURCE_CREDENTIAL_INVALID',
'SOURCE_DATABASE_UNAVAILABLE',
+ 'SOURCE_DATABASE_DRIVER_UNAVAILABLE',
+ 'SOURCE_DATABASE_TOO_LARGE',
+ 'SOURCE_DATABASE_INVALID',
'SOURCE_FILE_TOO_LARGE',
'SOURCE_HANDOVER_COMMAND_FAILED',
'SOURCE_HANDOVER_NOT_CONFIRMED',
diff --git a/apps/mobile/src/__tests__/CompanionImportSheet.test.tsx b/apps/mobile/src/__tests__/CompanionImportSheet.test.tsx
index b110747ff8..bf4cbe4837 100644
--- a/apps/mobile/src/__tests__/CompanionImportSheet.test.tsx
+++ b/apps/mobile/src/__tests__/CompanionImportSheet.test.tsx
@@ -175,3 +175,29 @@ it('submits all 10,000 selected entries compactly without raising the transport
await click('Ada · Hermes'); await click('devices.companionImport.submit');
expect(h.submit.mock.calls[0]?.[2].input).toMatchObject({ entryIds: [], entryRanges: [[0, 9999]], deferSetup: true });
});
+
+it('shows failed filenames and saved parts after a partial import without blocking chat or retry', async () => {
+ const result = { requestId: 'fixture-request-12345', botId: 'bot', canonicalSessionId: 'chat', saved: true, savedEntryIds: [], status: 'needs-attention',
+ checks: [{ entryId: 'memory', status: 'needs-attention', message: 'IMPORT_DISK_FULL', progress: { saved: 1, total: 3 } }] };
+ h.invoke.mockImplementation(async (_host: string, _channel: string, args: any[]) => {
+ const id = args[0].ref.id;
+ return { blocks: [{ primitive: 'companion-import', data: id === 'sources' ? { sources: [{ id: 'source', name: 'Ada', kind: 'hermes' }] }
+ : id.startsWith('preview:') ? { preview: { id: 'preview', name: 'Ada', source: { id: 'source', name: 'Ada', kind: 'hermes' }, entries: [{ id: 'memory', name: 'long-document.md', category: 'memory', selected: true }] } }
+ : { result } }] };
+ });
+ h.submit.mockReset().mockResolvedValue({ effects: [] });
+ const container = document.createElement('div'); root = createRoot(container);
+ await act(async () => root!.render(createElement(CompanionImportSheet, { visible: true, deviceId: 'host', deviceName: 'Mac', online: true, onClose() {}, onCreated: h.created })));
+ const click = async (text: string) => { await act(async () => { const button = [...container.querySelectorAll('button')].find(button => button.textContent?.startsWith(text)); expect(button).toBeDefined(); button!.click(); }); };
+ await click('Ada · Hermes'); await click('devices.companionImport.submit');
+ expect(container.textContent).toContain('devices.companionImport.partial');
+ expect(container.textContent).not.toContain('devices.companionImport.complete');
+ await click('devices.companionImport.details');
+ expect(container.textContent).toContain('long-document.md');
+ expect(container.textContent).toContain('devices.companionImport.partlySaved');
+ expect(container.textContent).toContain('devices.companionImport.diskFull');
+ expect(container.textContent).toContain('1 / 3');
+ expect(container.textContent).toContain('devices.companionImport.retry');
+ await click('devices.companionImport.open');
+ expect(h.created).toHaveBeenCalledWith({ collectionId: 'teammates', kind: 'bot', id: 'bot' });
+});
diff --git a/apps/mobile/src/i18n/locales/en/devices.json b/apps/mobile/src/i18n/locales/en/devices.json
index fa50e5cf1b..c0913d12bf 100644
--- a/apps/mobile/src/i18n/locales/en/devices.json
+++ b/apps/mobile/src/i18n/locales/en/devices.json
@@ -731,6 +731,24 @@
"previous": "Previous",
"next": "Next",
"chatSetup": "Your imported information is saved. We can start talking. Some items still need a login or a check; we can finish those whenever you are ready. Source automations stay unchanged until takeover.",
- "chatReady": "Your information has been imported. We can start talking."
+ "chatReady": "Your information has been imported. We can start talking.",
+ "partial": "Some content was not fully imported",
+ "details": "View import details",
+ "partlySaved": "Partially saved",
+ "savedNeedsSetup": "Saved; setup or activation remains",
+ "notSaved": "Not saved",
+ "databaseDriver": "The database driver could not load. Update or repair Cindy, then retry.",
+ "databaseUnavailable": "The source database could not be read. Original data is unchanged; retry after repair.",
+ "fileTooLarge": "A file or this import exceeds the read limit. Content was not truncated.",
+ "memoryMetadata": "The memory summary or title exceeds storage requirements.",
+ "memoryWrite": "Memory writing or integrity verification failed. You can retry.",
+ "memoryChanged": "The saved memory was changed and has not been overwritten.",
+ "attachmentUnsupported": "This attachment format is not supported yet. The original remains at the source.",
+ "diskFull": "Disk space is insufficient. Free space, then retry.",
+ "permissionDenied": "Permission to read or save this item is missing. Fix permissions, then retry.",
+ "setupDeferred": "Continue sign-in and verification in the teammate chat.",
+ "automationInvalid": "The automation definition could not be converted; it was not created.",
+ "itemFailed": "This item is unfinished. Retry or view import details.",
+ "chatPartial": "Your teammate is created, but some content was not fully saved. The items below still need attention; other content and chat remain available."
}
}
diff --git a/apps/mobile/src/i18n/locales/ja/devices.json b/apps/mobile/src/i18n/locales/ja/devices.json
index 8b10de27a5..3fcb25b2c3 100644
--- a/apps/mobile/src/i18n/locales/ja/devices.json
+++ b/apps/mobile/src/i18n/locales/ja/devices.json
@@ -731,6 +731,24 @@
"previous": "前のページ",
"next": "次のページ",
"chatSetup": "取り込める情報を保存しました。すぐに会話を始められます。ログインや確認が必要な項目は、都合のよいときに進めましょう。引き継ぎが完了するまで、元の自動化の状態は変わりません。",
- "chatReady": "情報をインポートしました。会話を始められます。"
+ "chatReady": "情報をインポートしました。会話を始められます。",
+ "partial": "一部の内容は完全にインポートされていません",
+ "details": "インポートの詳細",
+ "partlySaved": "一部のみ保存済み",
+ "savedNeedsSetup": "保存済み・設定または有効化が必要",
+ "notSaved": "未保存",
+ "databaseDriver": "データベースドライバーを読み込めません。Cindy を更新または修復して再試行してください。",
+ "databaseUnavailable": "元のデータベースを読み込めません。元データは変更されていません。修復後に再試行できます。",
+ "fileTooLarge": "ファイルまたはインポート全体が読み取り上限を超えています。内容は切り捨てていません。",
+ "memoryMetadata": "メモリの概要またはタイトルが保存要件を満たしていません。",
+ "memoryWrite": "メモリの保存または整合性確認に失敗しました。再試行できます。",
+ "memoryChanged": "保存済みのメモリが変更されているため、上書きしていません。",
+ "attachmentUnsupported": "この添付形式にはまだ対応していません。元ファイルはインポート元に残っています。",
+ "diskFull": "ディスク容量が不足しています。空きを確保して再試行してください。",
+ "permissionDenied": "読み取りまたは保存の権限がありません。権限を修正して再試行してください。",
+ "setupDeferred": "パートナーとのチャットでログインと確認を続けられます。",
+ "automationInvalid": "自動化の定義を変換できず、作成されていません。",
+ "itemFailed": "この項目は未完了です。再試行するか詳細を確認してください。",
+ "chatPartial": "パートナーは作成されましたが、一部の情報は完全に保存されていません。以下の項目は対応が必要です。他の情報とチャットは利用できます。"
}
}
diff --git a/apps/mobile/src/i18n/locales/ko/devices.json b/apps/mobile/src/i18n/locales/ko/devices.json
index 304be98ad6..f2609b90a6 100644
--- a/apps/mobile/src/i18n/locales/ko/devices.json
+++ b/apps/mobile/src/i18n/locales/ko/devices.json
@@ -731,6 +731,24 @@
"previous": "이전 페이지",
"next": "다음 페이지",
"chatSetup": "가져올 수 있는 자료를 저장했어요. 바로 대화를 시작할 수 있어요. 로그인이나 확인이 필요한 항목은 편할 때 마무리하면 돼요. 인계가 끝날 때까지 기존 자동화 상태는 그대로 유지돼요.",
- "chatReady": "정보를 가져왔습니다. 이제 대화를 시작할 수 있어요."
+ "chatReady": "정보를 가져왔습니다. 이제 대화를 시작할 수 있어요.",
+ "partial": "일부 내용을 완전히 가져오지 못했습니다",
+ "details": "가져오기 세부 정보",
+ "partlySaved": "일부만 저장됨",
+ "savedNeedsSetup": "저장됨 · 설정 또는 활성화 필요",
+ "notSaved": "저장되지 않음",
+ "databaseDriver": "데이터베이스 드라이버를 불러올 수 없습니다. Cindy를 업데이트하거나 복구한 뒤 다시 시도하세요.",
+ "databaseUnavailable": "원본 데이터베이스를 읽을 수 없습니다. 원본은 변경되지 않았으며 복구 후 다시 시도할 수 있습니다.",
+ "fileTooLarge": "파일 또는 전체 자료가 읽기 한도를 초과했습니다. 내용을 잘라서 가져오지 않았습니다.",
+ "memoryMetadata": "기억 요약 또는 제목이 저장 요건에 맞지 않습니다.",
+ "memoryWrite": "기억 저장 또는 무결성 확인에 실패했습니다. 다시 시도할 수 있습니다.",
+ "memoryChanged": "저장된 기억이 변경되어 덮어쓰지 않았습니다.",
+ "attachmentUnsupported": "아직 지원하지 않는 첨부 형식입니다. 원본 파일은 소스에 남아 있습니다.",
+ "diskFull": "디스크 공간이 부족합니다. 공간을 확보한 뒤 다시 시도하세요.",
+ "permissionDenied": "읽기 또는 저장 권한이 없습니다. 권한을 수정한 뒤 다시 시도하세요.",
+ "setupDeferred": "파트너 채팅에서 로그인과 확인을 계속할 수 있습니다.",
+ "automationInvalid": "자동화 정의를 변환할 수 없어 생성되지 않았습니다.",
+ "itemFailed": "아직 완료되지 않은 항목입니다. 다시 시도하거나 세부 정보를 확인하세요.",
+ "chatPartial": "파트너가 생성되었지만 일부 자료는 완전히 저장되지 않았습니다. 아래 항목은 추가 처리가 필요하며 다른 내용과 채팅은 계속 사용할 수 있습니다."
}
}
diff --git a/apps/mobile/src/i18n/locales/zh-CN/devices.json b/apps/mobile/src/i18n/locales/zh-CN/devices.json
index 1b1e6c1188..cf9654c6d2 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json
@@ -731,6 +731,24 @@
"previous": "上一页",
"next": "下一页",
"chatSetup": "已保存可导入的资料,可以开始交流了。部分内容还需要登录或检查,你方便时我们再继续。接管前,原来的自动化保持原状。",
- "chatReady": "资料已经导入,可以开始交流了。"
+ "chatReady": "资料已经导入,可以开始交流了。",
+ "partial": "部分内容未完整导入",
+ "details": "查看导入详情",
+ "partlySaved": "仅部分保存",
+ "savedNeedsSetup": "已保存,尚未启用或完成设置",
+ "notSaved": "未保存",
+ "databaseDriver": "数据库驱动无法加载,请更新或修复 Cindy 后重试。",
+ "databaseUnavailable": "无法读取来源数据库,原数据未改动。修复后可重试。",
+ "fileTooLarge": "文件或本次资料超过读取上限,未截断导入。",
+ "memoryMetadata": "记忆摘要或标题不符合存储要求。",
+ "memoryWrite": "记忆写入或完整性检查失败,可重试。",
+ "memoryChanged": "已保存的记忆发生变化,未覆盖。",
+ "attachmentUnsupported": "此附件格式暂不支持,原文件保留在来源。",
+ "diskFull": "磁盘空间不足,释放空间后可重试。",
+ "permissionDenied": "没有权限读取或保存此项,修复权限后可重试。",
+ "setupDeferred": "可在伙伴对话中继续登录与验证。",
+ "automationInvalid": "自动化定义无法转换,尚未创建。",
+ "itemFailed": "此项未完成,可重试并查看导入详情。",
+ "chatPartial": "伙伴已创建,但部分资料未完整保存。以下项目仍需处理;其他内容和对话可以正常使用。"
}
}
diff --git a/apps/mobile/src/i18n/locales/zh-TW/devices.json b/apps/mobile/src/i18n/locales/zh-TW/devices.json
index f279f61dd1..d499de1f23 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json
@@ -731,6 +731,24 @@
"previous": "上一頁",
"next": "下一頁",
"chatSetup": "已儲存可匯入的資料,可以開始交流了。部分內容還需要登入或檢查,你方便時我們再繼續。接管前,原來的自動化保持原狀。",
- "chatReady": "資料已經匯入,可以開始交流了。"
+ "chatReady": "資料已經匯入,可以開始交流了。",
+ "partial": "部分內容未完整匯入",
+ "details": "查看匯入詳情",
+ "partlySaved": "僅部分儲存",
+ "savedNeedsSetup": "已儲存,尚未啟用或完成設定",
+ "notSaved": "未儲存",
+ "databaseDriver": "資料庫驅動程式無法載入,請更新或修復 Cindy 後重試。",
+ "databaseUnavailable": "無法讀取來源資料庫,原資料未變更。修復後可重試。",
+ "fileTooLarge": "檔案或本次資料超過讀取上限,未截斷匯入。",
+ "memoryMetadata": "記憶摘要或標題不符合儲存要求。",
+ "memoryWrite": "記憶寫入或完整性檢查失敗,可重試。",
+ "memoryChanged": "已儲存的記憶發生變更,未覆寫。",
+ "attachmentUnsupported": "此附件格式暫不支援,原檔案保留在來源。",
+ "diskFull": "磁碟空間不足,釋放空間後可重試。",
+ "permissionDenied": "沒有權限讀取或儲存此項,修復權限後可重試。",
+ "setupDeferred": "可在夥伴對話中繼續登入與驗證。",
+ "automationInvalid": "自動化定義無法轉換,尚未建立。",
+ "itemFailed": "此項未完成,可重試並查看匯入詳情。",
+ "chatPartial": "夥伴已建立,但部分資料未完整儲存。以下項目仍需處理;其他內容和對話可以正常使用。"
}
}
diff --git a/apps/mobile/src/session/CompanionImportSheet.tsx b/apps/mobile/src/session/CompanionImportSheet.tsx
index 0f5fe5bd72..66d3ea4681 100644
--- a/apps/mobile/src/session/CompanionImportSheet.tsx
+++ b/apps/mobile/src/session/CompanionImportSheet.tsx
@@ -3,7 +3,7 @@ import { Pressable, ScrollView, StyleSheet, Switch, View } from 'react-native';
import { randomUUID } from 'expo-crypto';
import { useTranslation } from 'react-i18next';
import { parseRemoteActionInvokeRequest, REMOTE_RESOURCE_GET_CHANNEL, REMOTE_RESOURCE_PROTOCOL_VERSION, type RemoteResourceRef } from '@cindy/device-link';
-import { COMPANION_IMPORT_CHUNK_PRIMITIVE, compactCompanionImportSelection, areCompanionImportEntriesSelected, toggleCompanionImportEntries, companionImportCategories, remoteCompanionImportApi, type CompanionImportPreview, type CompanionImportResult, type CompanionImportSelection, type CompanionImportSource } from '@cindy/maker-shared/companion-import';
+import { COMPANION_IMPORT_CHUNK_PRIMITIVE, companionImportReasonKey, companionImportErrorCode, compactCompanionImportSelection, areCompanionImportEntriesSelected, toggleCompanionImportEntries, companionImportCategories, remoteCompanionImportApi, type CompanionImportPreview, type CompanionImportResult, type CompanionImportSelection, type CompanionImportSource } from '@cindy/maker-shared/companion-import';
import { Text, TextInput } from '@/components/AppText';
import { MainWindowActionButton } from '@/components/MobilePrimitives';
import { useDeviceLink } from '@/device-link/DeviceLinkContext';
@@ -33,14 +33,17 @@ export function CompanionImportSheet({ visible, onClose, onClosed, deviceId, dev
const [avatar, setAvatar] = useState('');
const [takeover, setTakeover] = useState(true);
const [busy, setBusy] = useState(false);
- const [error, setError] = useState(false);
+ const [error, setError] = useState<string>();
+ const [details, setDetails] = useState(false);
+ const [detailPage, setDetailPage] = useState(0);
const [result, setResult] = useState<CompanionImportResult>();
+ useEffect(() => setDetailPage(0), [result]);
const alive = useRef(true); const lock = useRef(false);
const intent = useRef<CompanionImportSelection | undefined>(undefined);
- useEffect(() => { alive.current = true; void api.sources().then(value => { if (alive.current) setSources(value); }).catch(() => { if (alive.current) setError(true); }); return () => { alive.current = false; }; }, [api]);
+ useEffect(() => { alive.current = true; void api.sources().then(value => { if (alive.current) setSources(value); }).catch(cause => { if (alive.current) setError(companionImportErrorCode(cause) ?? 'IMPORT_ITEM_FAILED'); }); return () => { alive.current = false; }; }, [api]);
const act = async (fn: () => Promise<void>) => {
if (lock.current || !online) return;
- lock.current = true; setBusy(true); setError(false);
+ lock.current = true; setBusy(true); setError(undefined);
try { await fn(); } catch (cause) {
// Only definitive creation/preflight rejections unlock editing. An ambiguous ACK
// keeps the same request ID and is reconciled before any retry.
@@ -54,7 +57,7 @@ export function CompanionImportSheet({ visible, onClose, onClosed, deviceId, dev
// Host restarts invalidate source IDs too. Reuse the existing source step.
try { const refreshed = await api.sources(); if (alive.current) setSources(refreshed); } catch { /* Existing source buttons allow another attempt. */ }
}
- if (alive.current) setError(true);
+ if (alive.current) setError(companionImportErrorCode(cause) ?? 'IMPORT_ITEM_FAILED');
}
finally { lock.current = false; if (alive.current) setBusy(false); }
};
@@ -91,19 +94,33 @@ export function CompanionImportSheet({ visible, onClose, onClosed, deviceId, dev
const selectedSet = new Set(selected);
const locked = busy || !!intent.current || !online;
const saved = !!result?.saved || result?.status === 'complete';
+ const outstanding = result?.checks.filter(check => check.status === 'needs-attention') ?? [];
+ const savedIds = new Set(result?.savedEntryIds);
+ const incomplete = result?.savedEntryIds ? selected.some(id => !savedIds.has(id)) : outstanding.some(check => check.message === 'IMPORT_ITEM_FAILED');
const finished = result && result.status !== 'running';
const entries = preview?.entries.filter(entry => entry.category === expanded) ?? [];
const filtered = entries.filter(entry => `${entry.name} ${entry.description ?? ''}`.toLocaleLowerCase().includes(query.toLocaleLowerCase()));
return <CompanionSheet visible={visible} title={tr('title')} onClose={() => { if (!busy || result) onClose(); }} onClosed={onClosed} preventDismiss={busy && !result}>
<ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={styles.content}>
- {!online || error ? <Text accessibilityRole="alert" style={styles.note}>{!online ? t('devices.companionProfile.offline', { deviceName }) : tr('error')}</Text> : null}
+ {!online || error ? <Text accessibilityRole="alert" style={styles.note}>{!online ? t('devices.companionProfile.offline', { deviceName }) : tr(companionImportReasonKey(error))}</Text> : null}
{finished && saved ? <>
- <Text style={styles.label}>{tr('complete')}</Text>
+ <Text style={styles.label}>{tr(incomplete ? 'partial' : 'complete')}</Text>
{companionImportCategories.map(category => {
const ids = new Set(preview?.entries.filter(entry => entry.category === category).map(entry => entry.id));
const count = result.savedEntryIds ? result.savedEntryIds.filter(id => ids.has(id)).length : result.checks.filter(check => ids.has(check.entryId) && check.status !== 'needs-attention').length;
- return ids.size ? <View key={category} style={styles.row}><Text style={[styles.label, styles.expand]}>{tr(category)}</Text><Text style={styles.count}>{count}</Text></View> : null;
+ return ids.size ? <View key={category} style={styles.row}><Text style={[styles.label, styles.expand]}>{tr(category)}</Text><Text style={styles.count}>{count} / {selected.filter(id => ids.has(id)).length}</Text></View> : null;
})}
+ {outstanding.length ? <>
+ <MainWindowActionButton action={{ label: `${tr('details')} · ${outstanding.length}`, onPress: () => { setDetails(!details); setDetailPage(0); } }} />
+ {details ? <>
+ {outstanding.slice(detailPage * 20, (detailPage + 1) * 20).map(check => <View key={check.entryId}>
+ <Text style={styles.label}>{preview?.entries.find(entry => entry.id === check.entryId)?.name ?? tr('itemAttention')}</Text>
+ <Text style={styles.note}>{tr(check.progress?.saved ? 'partlySaved' : savedIds.has(check.entryId) ? 'savedNeedsSetup' : 'notSaved')} · {tr(companionImportReasonKey(check.message))}</Text>
+ {check.progress ? <Text style={styles.count}>{check.progress.saved} / {check.progress.total}</Text> : null}
+ </View>)}
+ {outstanding.length > 20 ? <View style={styles.row}><MainWindowActionButton action={{ label: tr('previous'), disabled: detailPage === 0, onPress: () => setDetailPage(detailPage - 1) }} /><Text style={styles.count}>{detailPage + 1} / {Math.ceil(outstanding.length / 20)}</Text><MainWindowActionButton action={{ label: tr('next'), disabled: (detailPage + 1) * 20 >= outstanding.length, onPress: () => setDetailPage(detailPage + 1) }} /></View> : null}
+ </> : null}
+ </> : null}
</> : result?.status === 'running' ? <><Text style={styles.label}>{tr('running')}</Text><Text style={styles.count}>{result.checks.length} / {selected.length}</Text></> : !preview ? <>
{sources?.map(source => <MainWindowActionButton key={source.id} action={{ label: `${source.name} · ${source.kind === 'hermes' ? 'Hermes' : 'OpenClaw'}`, disabled: busy || !online, onPress: () => void choose(source.id) }} />)}
{error && !sources ? <MainWindowActionButton action={{ label: tr('retry'), disabled: busy || !online, onPress: () => void act(async () => { const value = await api.sources(); if (alive.current) setSources(value); }) }} /> : null}
@@ -126,7 +143,7 @@ export function CompanionImportSheet({ visible, onClose, onClosed, deviceId, dev
})}
{preview.entries.some(entry => entry.category === 'automations' && selectedSet.has(entry.id)) ? <View style={styles.row}><Text style={[styles.note, styles.expand]}>{tr('takeover')}</Text><Switch accessibilityLabel={tr('takeover')} value={takeover} disabled={locked} onValueChange={setTakeover} /></View> : null}
</>}
- {finished && !saved ? <MainWindowActionButton action={{ label: tr('retry'), busy, disabled: busy || !online, onPress: () => void submit() }} /> : null}
+ {finished && (!saved || incomplete) ? <MainWindowActionButton action={{ label: tr('retry'), busy, disabled: busy || !online, onPress: () => void submit() }} /> : null}
{finished ? <MainWindowActionButton action={{ label: tr('open'), disabled: !result.canonicalSessionId, onPress: () => { onCreated({ collectionId: 'teammates', kind: 'bot', id: result.botId }); onClose(); } }} /> : preview && !expanded ? <MainWindowActionButton action={{ label: tr('submit'), busy, disabled: busy || !online || !name.trim() || !avatar, onPress: () => void submit() }} /> : null}
</ScrollView>
</CompanionSheet>;
diff --git a/packages/maker-core/src/memory/storage.ts b/packages/maker-core/src/memory/storage.ts
index 5aac3a7b49..1bd3b300a8 100644
--- a/packages/maker-core/src/memory/storage.ts
+++ b/packages/maker-core/src/memory/storage.ts
@@ -390,7 +390,8 @@ export class MemoryStorage {
);
}
- const fileText = matter.stringify(nextBody, nextFrontmatter);
+ if (opts.preserveBody) nextFrontmatter.bodyLength = nextBody.length;
+ const fileText = matter.stringify({ content: nextBody }, nextFrontmatter);
// tryReadRaw 的 await 窗口后、真正写盘前复核 owner scope (review #2388
// Codex 8th P1): 边界不得把 shard 写入旧 owner 根。
this.beforeFileWrite?.();
@@ -678,7 +679,12 @@ function parseRawShard(raw: string, filenameForErr: string): ParsedShard {
type: data.type,
updatedAt: typeof data.updatedAt === 'string' ? data.updatedAt : new Date().toISOString(),
},
- body: parsed.content.trim(),
+ // gray-matter appends one newline. Remove only that exact serialization
+ // suffix; an external edit must never be truncated to a stale length.
+ body: Number.isSafeInteger(data.bodyLength) && data.bodyLength! >= 0
+ ? (parsed.content.length === data.bodyLength! + 1 && parsed.content.endsWith('\n')
+ ? parsed.content.slice(0, -1) : parsed.content)
+ : parsed.content.trim(),
};
}
diff --git a/packages/maker-core/src/memory/types.ts b/packages/maker-core/src/memory/types.ts
index 90bfed6a67..ad521f5608 100644
--- a/packages/maker-core/src/memory/types.ts
+++ b/packages/maker-core/src/memory/types.ts
@@ -52,6 +52,8 @@ export interface MemoryFrontmatter {
type: MemoryType;
/** ISO 8601 string */
updatedAt: string;
+ /** Exact imported body length in UTF-16 units; absent on legacy/authored shards. */
+ bodyLength?: number;
}
/** 解析后的内存记录 (storage.list / read 返回) */
@@ -61,7 +63,7 @@ export interface MemoryRecord {
/** 去掉 <type>_ 前缀和 .md 后缀, e.g. 'response_style' */
slug: string;
frontmatter: MemoryFrontmatter;
- /** body 不含 frontmatter, 已 trim */
+ /** Body excludes storage frontmatter; imports retain their original whitespace. */
body: string;
/** 文件大小 (bytes), 用作 size warning 判断 */
sizeBytes: number;
@@ -81,6 +83,8 @@ export interface WriteOptions {
body: string;
/** 'create' 撞名拒绝; 'update' 覆盖; 'append' 追加。默认 'create' */
mode?: WriteMode;
+ /** Host import preserves whitespace and nested source frontmatter verbatim. */
+ preserveBody?: boolean;
}
export type WriteWarning = 'shard-size-exceeded' | 'index-size-exceeded';
diff --git a/packages/maker-shared/src/__tests__/companionImport.test.ts b/packages/maker-shared/src/__tests__/companionImport.test.ts
index 5805e4b848..b85ff5e0e3 100644
--- a/packages/maker-shared/src/__tests__/companionImport.test.ts
+++ b/packages/maker-shared/src/__tests__/companionImport.test.ts
@@ -1,5 +1,5 @@
import { expect, it, vi } from 'vitest';
-import { COMPANION_IMPORT_CHUNK_LENGTH, compactCompanionImportSelection, remoteCompanionImportApi, areCompanionImportEntriesSelected, toggleCompanionImportEntries, type CompanionImportEntry, type CompanionImportPreview } from '../companionImport.js';
+import { companionImportErrorCode, companionImportReasonKey, COMPANION_IMPORT_CHUNK_LENGTH, compactCompanionImportSelection, remoteCompanionImportApi, areCompanionImportEntriesSelected, toggleCompanionImportEntries, type CompanionImportEntry, type CompanionImportPreview } from '../companionImport.js';
const entries: CompanionImportEntry[] = [
{ id: 'work', name: 'Work', category: 'connections', selected: false, exclusiveWith: ['personal'] },
{ id: 'personal', name: 'Personal', category: 'connections', selected: false, exclusiveWith: ['work'] },
@@ -58,3 +58,12 @@ it.each(['token', 'offset', 'total', 'missing', 'disconnect'])('rejects %s drift
await expect(api.preview('source')).rejects.toThrow(mode === 'disconnect' ? 'DISCONNECTED' : 'INVALID_IMPORT_RESPONSE');
expect(read).toHaveBeenCalledTimes(2);
});
+
+
+it('keeps concrete import failures through IPC wrappers without displaying private exception text', () => {
+ const error = { code: 'INVALID_PARAMS', message: '[INVALID_PARAMS] SOURCE_DATABASE_DRIVER_UNAVAILABLE private path' };
+ expect(companionImportErrorCode(error)).toBe('SOURCE_DATABASE_DRIVER_UNAVAILABLE');
+ expect(companionImportReasonKey(companionImportErrorCode(error))).toBe('databaseDriver');
+ expect(companionImportReasonKey('PRIVATE_UNKNOWN')).toBe('itemFailed');
+ expect(companionImportErrorCode(new Error('private source contents'))).toBeUndefined();
+});
diff --git a/packages/maker-shared/src/companionImport.ts b/packages/maker-shared/src/companionImport.ts
index 1c0b5e511b..5980a63ec1 100644
--- a/packages/maker-shared/src/companionImport.ts
+++ b/packages/maker-shared/src/companionImport.ts
@@ -51,6 +51,8 @@ export interface CompanionImportCheck {
entryId: string;
status: 'copied' | 'verified' | 'needs-attention' | 'taken-over' | 'paused';
message?: string;
+ /** Fully written parts before an item failure; absent for old receipts. */
+ progress?: { saved: number; total: number };
}
export interface CompanionImportResult {
@@ -197,3 +199,29 @@ export function remoteCompanionImportApi(
status,
};
}
+
+/** Stable public reason categories, shared by Desktop/Mobile. Never display raw exceptions. */
+export function companionImportReasonKey(code?: string): string {
+ const keys: Record<string, string> = {
+ SOURCE_DATABASE_DRIVER_UNAVAILABLE: 'databaseDriver', SOURCE_DATABASE_UNAVAILABLE: 'databaseUnavailable',
+ SOURCE_DATABASE_INVALID: 'databaseUnavailable', SOURCE_DATABASE_TOO_LARGE: 'fileTooLarge',
+ MEMORY_DESCRIPTION_TOO_LONG: 'memoryMetadata', MEMORY_TITLE_TOO_LONG: 'memoryMetadata', MEMORY_METADATA_INVALID: 'memoryMetadata',
+ MEMORY_CONTENT_TOO_LARGE: 'fileTooLarge', MEMORY_WRITE_FAILED: 'memoryWrite', MEMORY_CHANGED: 'memoryChanged',
+ MEMORY_STORAGE_UNAVAILABLE: 'memoryWrite', MEMORY_ATTACHMENT_UNSUPPORTED: 'attachmentUnsupported',
+ SOURCE_FILE_TOO_LARGE: 'fileTooLarge', SOURCE_SNAPSHOT_TOO_LARGE: 'fileTooLarge', SOURCE_ITEM_TOO_LARGE: 'fileTooLarge',
+ IMPORT_DISK_FULL: 'diskFull', IMPORT_PERMISSION_DENIED: 'permissionDenied',
+ IMPORT_SETUP_DEFERRED: 'setupDeferred', SOURCE_TOOL_POLICY_NEEDS_MAPPING: 'toolMapping', AUTOMATION_MODEL_NEEDS_MAPPING: 'modelMapping',
+ AUTOMATION_CONTEXT_NEEDS_MAPPING: 'contextMapping', AUTOMATION_WORKDIR_NEEDS_MAPPING: 'contextMapping',
+ SOURCE_AUTOMATION_INVALID: 'automationInvalid', AUTOMATION_TRIGGER_NEEDS_ADAPTER: 'automationInvalid',
+ AUTOMATION_DATA_READ_FAILED: 'readFailed', AUTOMATION_READ_NOT_VERIFIED: 'readFailed',
+ NATIVE_AUTH_REFRESH_REQUIRED: 'authRefresh', AUTOMATION_DEPENDENCY_NOT_SELECTED: 'missingSelection',
+ };
+ return code && keys[code] || 'itemFailed';
+}
+export function companionImportErrorCode(error: unknown): string | undefined {
+ const value = error as { code?: unknown; message?: unknown } | null;
+ const pattern = /\b(?:SOURCE|IMPORT|MEMORY|CREDENTIAL|AUTOMATION|PROFILE|PREVIEW|SELECTION)_[A-Z_]+\b/;
+ const candidate = typeof value?.code === 'string' && pattern.test(value.code) ? value.code
+ : typeof value?.message === 'string' ? value.message.match(pattern)?.[0] : undefined;
+ return candidate && /^[A-Z][A-Z_]+$/.test(candidate) ? candidate : undefined;
+}