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 complete imports and defer setup to chat

zqchrise692b89806c3
diff --git a/apps/desktop/src/main/bot-import/README.md b/apps/desktop/src/main/bot-import/README.md
index 12acb4a52c..48b99aa711 100644
--- a/apps/desktop/src/main/bot-import/README.md
+++ b/apps/desktop/src/main/bot-import/README.md
@@ -34,7 +34,8 @@ Mobile can select automations during import and request host-owned takeover.
Reopening creation after dismissing import starts with the normal creation form;
reconnecting an open import preserves its current selection and request.
Import adds category/item selection, including
-unselecting defaults; unused skills start unselected. Both platforms use semantic
+unselecting defaults; every discovered skill starts selected. The summary has five flat
+category rows; category details use search and 20-row pages. Both platforms use semantic
theme tokens. No new native Mobile dependencies or fingerprint inputs are added.
Every supplied avatar uses the existing companion image validation before any
receipt or credential checkpoint is written. An empty supplied image is invalid;
@@ -59,17 +60,26 @@ omitting it retains normal companion defaults, and a rejected request can be cor
These files remain individually deselectable; deselecting a subtree dependency
prevents that automation's takeover, leaving its source running. Helper code
contributes environment dependencies and bounded verification planning text.
- A shared 128 MiB / 4096-file read budget bounds each source snapshot, including
+ A shared 128 MiB read budget bounds each source snapshot, including
config includes, documents, credentials, scripts and all referenced skill trees.
Additional selected skill resources use the same cumulative limit before any
- import writes. Exceeding it fails explicitly without truncation; the existing
- form unlocks on a definitive pre-import limit rejection. Fingerprints hash raw
+ import writes. An unreadable/oversized selected resource retains a per-item failure
+ for retry; healthy items and the conversation are saved. No item is truncated. Fingerprints hash raw
file bytes, and encrypted checkpoints use base64 while still reading legacy
numeric-array checkpoints.
- Before the first receipt/checkpoint/profile write, selected skills also use the
- existing store validation: at most 100 skills and a 64 KiB SKILL.md entrypoint,
- measured after any publication guidance is appended. Invalid selections return
- the existing editable-form error without leaving a partial companion.
+ Skill count, source entry count, resource file count and cron row count have no
+ fixed quota. Imported SKILL.md files preserve their full body rather than using
+ the interactive skill editor's 64 KiB authoring limit. Individual file and total
+ in-memory snapshot byte bounds remain; this is not an unlimited-byte importer.
+ Skills disabled at the source are saved outside the active native skills folder
+ and stay disabled when read or edited.
+- Skill discovery follows grouped Hermes directories, configured external roots,
+ native directory links and disabled lists. OpenClaw discovery covers workspace,
+ workspace `.agents`, personal/managed/workshop, installed bundled, extra and
+ enabled plugin manifest roots, with native precedence and symlink trust rules.
+ Nested archive/environment/support directories are excluded. Names and skillKey
+ overrides are resolved before deduplication; skill-owned credential alternatives
+ are selected separately so credential ambiguity cannot deselect a skill.
- Selected variables, MCP env/headers, source credentials and automation assets
use the existing account encrypted credential store. The teammate folder has
a non-secret `environment.json` binding. Variable/connection names in that file
@@ -226,9 +236,10 @@ omitting it retains normal companion defaults, and a rejected request can be cor
with the final successful history entry. Failed result saves retry persistence
without rerunning; recovery of an already exhausted counter also disables the
routine. Ordinary unchanged-monitor skips remain eligible for the next trigger.
- Pure-script output appears in the canonical teammate chat. Explicit Telegram
- source destinations use the selected original bot credential; they do not
- change Cindy's official/personal bot implementations.
+ All newly imported output goes to the canonical teammate chat. Source delivery
+ channels and failure delivery destinations do not gate selection or verification.
+ Existing imported bindings that already carry Telegram destinations retain their
+ legacy delivery behavior; no existing routine is silently rerouted.
Each confirmed target/message chunk advances progress in the same encrypted
automation binding. A retry or next occurrence resumes the captured output and
destinations before rerunning the model/script; counters commit only after all
@@ -239,7 +250,7 @@ Copying and field conversion do not call a model. The optional takeover check
uses the teammate's current model to plan bounded read-only probes, then the
host executes real MCP/HTTP reads and validates response data. The planner sees
variable names and redacted task/script text and Skill/file identifiers, not credential values. HTTP checks
-reject redirects; Telegram checks read identity/destination without test sends.
+reject redirects. Legacy Telegram bindings still check identity/destination without test sends.
The MCP server's `readOnlyHint` only filters planning candidates; it does not
authorize execution. Each planned MCP/HTTP call and literal monitor GET uses the companion's existing
Auto/Ask/Full Access policy with its exact connection, tool and arguments. Auto
@@ -281,10 +292,10 @@ query values in encoded/decoded forms, even when they are absent from `.env`.
The same known-credential mask applies to prior output, legacy prepared retries,
script output, planning text and the final imported delivery boundary. Requests
still use the private original URL; redacted output retains normal change detection.
-Verified delivery-only credentials are excluded from data-read dependencies, so
-local reminders can retain their Telegram destination. Variables also referenced
+Legacy delivery-only credentials are excluded from data-read dependencies. New
+imports have no source delivery dependency and local reminders use teammate chat. Variables also referenced
by the task or its skills still require data verification.
-Telegram destinations without an explicit source account bind only when exactly
+For legacy bindings, Telegram destinations without an explicit source account bind only when exactly
one source account is available. Multiple candidates or a missing explicit account
use the existing `DELIVERY_NEEDS_ADAPTER` state and keep the source task running;
being able to reach a chat does not identify the intended sending bot.
@@ -293,6 +304,23 @@ runtime interpreter parses the selected script without executing business action
This checks availability and syntax, not a full business execution; scripts with
external data still require actual read evidence.
+## Save first, finish setup in chat
+
+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;
+ordinary cron jobs named heartbeat are still imported.
+
+The owner-scoped `companion_connections.import_setup` tool lists remaining checks
+in pages, retries from the encrypted checkpoint, and permits explicit adoption of
+Cindy model/tool settings for selected entries with `use_cindy_settings`. That
+operation does not activate anything or waive context/workdir/data checks. Login
+uses the real existing account/plugin connection UI; credentials are never requested
+in chat. Ordinary conversation remains available while setup is deferred.
+
## Handover and compatibility
An initial non-secret receipt indexes the request before any encrypted checkpoint
@@ -358,9 +386,18 @@ Remote Resource boundary so the existing form can be edited and resubmitted.
Expired or changed previews clear the frozen intent and refresh the existing
source step on Desktop and Mobile; a new preview gets a fresh request.
Mobile validates the complete action through the existing Remote Resource parser
-before freezing its request. A payload exceeding the 64 KiB input budget stays
-editable so the user can adjust the portrait/selection; no oversized write is sent.
-The wire format and limits are unchanged. Unexpected/ambiguous failures still
+before freezing its request. New hosts advertise `selectionRanges`; new clients can
+encode exact selections as inclusive immutable preview-index ranges. Selected-only
+checkpoints retain the original indexes. Old hosts receive the existing ID arrays;
+old clients can continue using ID arrays on a new host. The 64 KiB wire action
+budget is unchanged; 10,000 selected entries need one range, not 10,000 IDs.
+Previously released controllers retain their own 2,000-entry preview/result limits;
+large catalogs require an updated controller as well as host. A new controller with
+an old host retains the old ID-array/inline-check behavior and retry/open actions;
+it does not claim deferred setup when the host has not saved it. Existing receipts
+without range indexes, deferred-setup flags or saved counts remain resumable, and
+their existing delivery bindings are retained rather than rewritten on upgrade.
+Unexpected/ambiguous failures still
retain the original request for reconciliation.
The optional public credential-alternative IDs are additive: older clients may
ignore them, but the host still rejects a conflicting selection before writing.
@@ -374,8 +411,7 @@ subscription authentication path. Preserving a source profile does not mean its
OAuth refresh is supported or its subscription can be used by another harness.
The preview/result explicitly retains and identifies configurations requiring
an adapter: native subscription OAuth refresh, source-specific tool policies,
-per-job model/context/workspace overrides, staggered schedules, and delivery
-channels other than explicit Telegram/local chat. Their selected source values
+per-job model/context/workspace overrides and staggered schedules. Their selected source values
are retained privately, the affected automation stays at the source, and its
imported routine cannot execute with silently weakened semantics. Missing
selected dependencies and failed data probes behave the same way.
diff --git a/apps/desktop/src/main/bot-import/__tests__/connectionProvider.test.ts b/apps/desktop/src/main/bot-import/__tests__/connectionProvider.test.ts
index a189a423a2..d143edd39f 100644
--- a/apps/desktop/src/main/bot-import/__tests__/connectionProvider.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/connectionProvider.test.ts
@@ -7,6 +7,7 @@ import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv
import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
vi.mock('@cindy/mcps', () => ({ resolveLiziMcpSessionContext: () => ({ sessionId: 'fixture-session' }) }));
+vi.mock('../host.js', () => ({ continueCompanionImport: vi.fn(), getCompanionImportResult: vi.fn(), useCindyImportSettings: vi.fn() }));
vi.mock('../runtime.js', () => ({ readCompanionSessionEnvironment: vi.fn() }));
import { readCompanionSessionEnvironment } from '../runtime.js';
import { createCompanionConnectionsProvider } from '../connectionProvider.js';
@@ -399,3 +400,33 @@ readline.createInterface({input:process.stdin}).on('line', line => {
await withImportedConnection(mcp[2]!, {}, () => {}, async () => { throw new Error('fixture cleanup'); }, { identity: scope.identity, signal: new AbortController().signal }).catch(() => {});
}
});
+
+it('offers paginated private import setup only in the owning companion and masks credential-bearing names', async () => {
+ const { getCompanionImportResult, continueCompanionImport } = await import('../host.js');
+ const secret = 'fixture-name-secret';
+ const checks = Array.from({ length: 23 }, (_, index) => ({ entryId: `entry-${index}`, status: 'needs-attention' as const, message: 'IMPORT_SETUP_DEFERRED' }));
+ const result = { requestId: 'fixture-request-setup', botId: 'bot', status: 'needs-attention' as const, checks, saved: true };
+ vi.mocked(getCompanionImportResult).mockResolvedValue(result);
+ vi.mocked(continueCompanionImport).mockResolvedValue(result);
+ const assertOwner = vi.fn();
+ vi.mocked(readCompanionSessionEnvironment).mockResolvedValue({ identity: 'fixture', botId: 'bot', userData: '/fixture', assertOwner,
+ environment: { version: 1, env: { API_KEY: secret }, mcp: [], credentials: [], pendingImport: {
+ selection: { previewId: 'p', requestId: result.requestId, name: 'Ada', entryIds: [], takeover: true, deferSetup: true },
+ snapshotJson: JSON.stringify({ source: {}, fingerprint: 'fixture', items: checks.map(check => ({ view: { id: check.entryId, name: `Job ${secret}`, category: 'automations', selected: true } })) }),
+ } } });
+ const config = createCompanionConnectionsProvider().toClaudeSdkConfig!({} as never) as { instance: McpServer };
+ const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
+ const client = new Client({ name: 'fixture', version: '1' });
+ await config.instance.connect(serverTransport); await client.connect(clientTransport);
+ try {
+ expect((await client.listTools()).tools.some(tool => tool.name === 'import_setup')).toBe(true);
+ const first = await client.callTool({ name: 'import_setup', arguments: { operation: 'status' } });
+ const text = (first.content as Array<{ text: string }>)[0]!.text;
+ expect(text).not.toContain(secret);
+ expect(JSON.parse(text)).toMatchObject({ total: 23, nextOffset: 20 });
+ expect(JSON.parse(text).items).toHaveLength(20);
+ await client.callTool({ name: 'import_setup', arguments: { operation: 'retry', offset: 20 } });
+ expect(continueCompanionImport).toHaveBeenCalledWith('bot', '/fixture', assertOwner);
+ expect(assertOwner).toHaveBeenCalled();
+ } finally { await client.close(); await config.instance.close(); }
+});
diff --git a/apps/desktop/src/main/bot-import/__tests__/files.test.ts b/apps/desktop/src/main/bot-import/__tests__/files.test.ts
index ca7e1e832a..d6b13d1300 100644
--- a/apps/desktop/src/main/bot-import/__tests__/files.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/files.test.ts
@@ -1,5 +1,5 @@
import { expect, it, vi } from 'vitest';
-import { createImportBudget, deserializeImportSnapshot, readImportFile, serializeImportSnapshot, snapshotFingerprint } from '../files.js';
+import { createImportBudget, deserializeImportSnapshot, readImportFile, readImportTree, serializeImportSnapshot, snapshotFingerprint } from '../files.js';
import type { ImportSnapshot } from '../types.js';
import { promises as fs } from 'node:fs';
import os from 'node:os';
@@ -42,3 +42,13 @@ it('hashes binary contents and checkpoints compactly without invoking Buffer.toJ
expect(stringifyBuffer).not.toHaveBeenCalled();
} finally { stringifyBuffer.mockRestore(); }
});
+
+it('reads every resource in a skill with more than 4096 small files', async () => {
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-import-many-files-'));
+ try {
+ for (let index = 0; index < 4100; index++) await fs.writeFile(path.join(root, `resource-${index}.txt`), `Resource ${index}`);
+ const files = await readImportTree(root, undefined, createImportBudget());
+ expect(files).toHaveLength(4100);
+ expect(files.find(file => file.name === 'resource-4099.txt')?.bytes.toString()).toBe('Resource 4099');
+ } finally { await fs.rm(root, { recursive: true, force: true }); }
+});
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 0139b33f76..ecc1c11ff2 100644
--- a/apps/desktop/src/main/bot-import/__tests__/host.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
@@ -83,7 +83,7 @@ beforeEach(async () => {
vi.mocked(decodeBotAvatarImage).mockReset();
vi.mocked(discoverImportSources).mockReset().mockImplementation(async () => [h.snapshot.source]);
vi.mocked(inspectImportSource).mockReset().mockImplementation(async () => h.snapshot);
- vi.mocked(createImportSourceReader).mockReset().mockImplementation(() => ({ readName: h.readName }) as never);
+ vi.mocked(createImportSourceReader).mockReset().mockImplementation(() => ({ readName: h.readName, readRedactions: async () => previewImportRedactions(h.snapshot.items) }) as never);
h.readName.mockReset().mockImplementation(async source => redactEnvironmentValues(source.name, previewImportRedactions(h.snapshot.items)));
const values = h.secretValues; values.clear();
h.store = createCompanionEnvironmentStore({ read: key => values.get(key) ?? null, write: (key, value) => {
@@ -709,8 +709,8 @@ it('keeps the source paused and execution deferred when the ready marker write f
}, 10000);
-it.each(['count', 'entrypoint', 'projected-entrypoint', 'captured-entrypoint'])('rejects skill %s limits before storing a checkpoint or creating a companion, then accepts a corrected selection', async mode => {
- const count = mode === 'count' ? 101 : 1;
+it.each(['count', 'entrypoint', 'projected-entrypoint', 'captured-entrypoint'])('imports skill %s beyond the old authoring and count quotas', async mode => {
+ const count = mode === 'count' ? 142 : 1;
h.snapshot.items = Array.from({ length: count }, (_, index) => ({
view: { id: `skill-${index}`, category: 'skills' as const, name: `skill-${index}`, selected: true }, filesComplete: true,
files: [{ name: 'SKILL.md', bytes: Buffer.alloc(mode === 'entrypoint' ? 65537 : mode === 'projected-entrypoint' ? 65536 : 10, 'a'), executable: false }],
@@ -727,18 +727,12 @@ it.each(['count', 'entrypoint', 'projected-entrypoint', 'captured-entrypoint'])(
const [source] = await listCompanionImportSources('fixture');
const preview = await previewCompanionImport(source!.id, 'fixture');
const selection = { requestId: `fixture-skill-limit-${mode}`, previewId: preview.id, name: 'Ada', entryIds: h.snapshot.items.map(item => item.view.id), takeover: false };
- await expect(startCompanionImport(selection, 'fixture')).rejects.toThrow('INVALID_SELECTION');
- expect(createBotProfile).not.toHaveBeenCalled();
- expect(h.secretValues.size).toBe(0);
- expect(await getCompanionImportResult(selection.requestId)).toBeUndefined();
- await expect(fs.access(path.join(h.root, 'companion-imports'))).rejects.toThrow();
- // The same preview remains editable; existing INVALID_SELECTION handling clears intent.
- const entryIds = mode === 'count' ? ['skill-0'] : [];
- await startCompanionImport({ ...selection, requestId: `${selection.requestId}-retry`, entryIds }, 'fixture');
- await vi.waitFor(async () => expect((await getCompanionImportResult(`${selection.requestId}-retry`))?.status).toBe('complete'));
+ await startCompanionImport(selection, 'fixture');
+ await vi.waitFor(async () => expect((await getCompanionImportResult(selection.requestId))?.status).toBe('complete'));
+ expect(createBotProfile).toHaveBeenCalledOnce();
});
-it.each(['oversized', 'symlink'])('rejects a lazily selected %s resource before a receipt, then imports after deselection', async mode => {
+it.each(['oversized', 'symlink'])('retains a failed %s skill for retry while saving the companion and healthy content', async mode => {
const directory = path.join(h.root, 'source-skill');
await fs.mkdir(directory);
if (mode === 'oversized') {
@@ -754,12 +748,15 @@ it.each(['oversized', 'symlink'])('rejects a lazily selected %s resource before
const [source] = await listCompanionImportSources('fixture');
const preview = await previewCompanionImport(source!.id, 'fixture');
const selection = { requestId: `fixture-capture-${mode}`, previewId: preview.id, name: 'Ada', entryIds: ['skill'], takeover: false };
- await expect(startCompanionImport(selection, 'fixture')).rejects.toThrow(mode === 'oversized' ? 'SOURCE_FILE_TOO_LARGE' : 'SOURCE_LINK_OUTSIDE_FOLDER');
- expect(createBotProfile).not.toHaveBeenCalled(); expect(h.secretValues.size).toBe(0);
- expect(await getCompanionImportResult(selection.requestId)).toBeUndefined();
- await expect(fs.access(path.join(h.root, 'companion-imports'))).rejects.toThrow();
- await startCompanionImport({ ...selection, requestId: `${selection.requestId}-retry`, entryIds: [] }, 'fixture');
- await vi.waitFor(async () => expect((await getCompanionImportResult(`${selection.requestId}-retry`))?.status).toBe('complete'));
+ await startCompanionImport(selection, 'fixture');
+ await vi.waitFor(async () => expect((await getCompanionImportResult(selection.requestId))?.saved).toBe(true));
+ expect(createBotProfile).toHaveBeenCalled();
+ expect((await getCompanionImportResult(selection.requestId))?.checks).toContainEqual({ entryId: 'skill', status: 'needs-attention', message: mode === 'oversized' ? 'SOURCE_FILE_TOO_LARGE' : 'SOURCE_LINK_OUTSIDE_FOLDER' });
+ expect(h.secretValues.size).toBeGreaterThan(0);
+ // A corrected resource can finish under the same request; no second companion is needed.
+ await fs.rm(path.join(directory, mode === 'oversized' ? 'resource.bin' : 'linked'), { recursive: true });
+ await startCompanionImport(selection, 'fixture');
+ await vi.waitFor(async () => expect((await getCompanionImportResult(selection.requestId))?.status).toBe('complete'));
});
it('replaces previous previews for the same controller and keeps the latest usable', async () => {
@@ -838,3 +835,47 @@ it.each(['readback', 'binding'] as const)('cleans an unbound first checkpoint af
expect(values.size).toBe(0); expect(remove).toHaveBeenCalledTimes(2);
expect(h.created).toBe(false);
});
+
+it('adopts Cindy settings only for explicitly selected items and still requires takeover verification', async () => {
+ const { useCindyImportSettings, continueCompanionImport } = await import('../host.js');
+ h.snapshot.items = [{ view: { id: 'task', name: 'Report', category: 'automations', selected: true, enabled: true, issues: ['SOURCE_TOOL_POLICY_NEEDS_MAPPING', 'AUTOMATION_MODEL_NEEDS_MAPPING', 'AUTOMATION_CONTEXT_NEEDS_MAPPING'] },
+ automation: { sourceId: 'source-task', fingerprint: 'fixture', original: {}, input: { name: 'Report', prompt: 'Read data', enabled: false, triggers: [{ id: 'time', kind: 'interval', intervalMs: 60000 }] } } }];
+ const [source] = await listCompanionImportSources('fixture');
+ const preview = await previewCompanionImport(source!.id, 'fixture');
+ const selection = { requestId: 'fixture-cindy-settings', previewId: preview.id, name: 'Ada', entryIds: ['task'], takeover: true, deferSetup: true };
+ await startCompanionImport(selection, 'fixture');
+ await vi.waitFor(async () => expect((await getCompanionImportResult(selection.requestId))?.saved).toBe(true));
+ const result = (await getCompanionImportResult(selection.requestId))!;
+ await expect(useCindyImportSettings(result.botId, h.root, ['unknown'], () => {})).rejects.toThrow('INVALID_SELECTION');
+ await useCindyImportSettings(result.botId, h.root, ['task'], () => {});
+ await continueCompanionImport(result.botId, h.root, () => {});
+ await vi.waitFor(async () => expect((await getCompanionImportResult(selection.requestId))?.checks).toContainEqual({ entryId: 'task', status: 'needs-attention', message: 'AUTOMATION_CONTEXT_NEEDS_MAPPING' }));
+});
+
+it('refreshes masks and encrypted originals when a previously failed credential-bearing resource is repaired', async () => {
+ const directory = path.join(h.root, 'source-skill');
+ const outside = path.join(h.root, 'outside');
+ await fs.mkdir(directory); await fs.mkdir(outside); await fs.writeFile(path.join(outside, 'read.txt'), 'outside');
+ await fs.symlink(outside, path.join(directory, 'escape'), process.platform === 'win32' ? 'junction' : 'dir');
+ const secret = 'fixture-unselected-resource-secret';
+ h.snapshot.items = [
+ { view: { id: 'skill', name: 'report', category: 'skills', selected: true }, sourceDirectory: directory, files: [{ name: 'SKILL.md', bytes: Buffer.from('# Report'), executable: false }], filesComplete: false, envDependencies: { names: [], entries: [] } },
+ { view: { id: 'unselected', name: 'PRIVATE', category: 'connections', selected: false }, env: { PRIVATE: secret } },
+ ];
+ const [source] = await listCompanionImportSources('fixture');
+ const preview = await previewCompanionImport(source!.id, 'fixture');
+ const selection = { requestId: 'fixture-repaired-private-skill', previewId: preview.id, name: 'Ada', entryIds: ['skill'], takeover: false, deferSetup: true };
+ await startCompanionImport(selection, 'fixture');
+ await vi.waitFor(async () => expect((await getCompanionImportResult(selection.requestId))?.saved).toBe(true));
+ await fs.rm(path.join(directory, 'escape'), { recursive: true });
+ await fs.writeFile(path.join(directory, 'read.txt'), `Token ${secret}`);
+ await startCompanionImport(selection, 'fixture');
+ await vi.waitFor(async () => expect((await getCompanionImportResult(selection.requestId))?.status).toBe('complete'));
+ const result = (await getCompanionImportResult(selection.requestId))!;
+ expect(await fs.readFile(path.join(h.root, 'bots', result.botId, 'skills/report/read.txt'), 'utf8')).not.toContain(secret);
+ const environment = (await h.store.read(h.root, result.botId, () => {}))!;
+ expect(environment.env).toEqual({});
+ const original = environment.skillFiles?.report?.find(file => file.name === 'read.txt');
+ expect(Buffer.from(original!.bytes, 'base64').toString()).toContain(secret);
+ expect(Object.values(environment.contentRedactions ?? {})).toContain(secret);
+});
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 b8492a85f4..ed65495aa5 100644
--- a/apps/desktop/src/main/bot-import/__tests__/openclawCronWorker.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/openclawCronWorker.test.ts
@@ -18,13 +18,15 @@ it.each(['esm', 'cjs'] as const)('reads committed WAL jobs for exactly the selec
insert.run('store', 'main', null, 1, JSON.stringify({ id: 'mine', enabled: true }), JSON.stringify({ lastRunAtMs: 123 }));
insert.run('store', 'other', null, 2, JSON.stringify({ id: 'other' }), '{}');
insert.run('other-store', 'main', null, 3, JSON.stringify({ id: 'other-store' }), '{}');
+ const extra = Array.from({ length: 1100 }, (_, index) => ({ id: `extra-${index}` }));
+ db.transaction(() => { for (const [index, job] of extra.entries()) insert.run('store', 'main', null, index + 4, JSON.stringify(job), '{}'); })();
const source = await fs.readFile(new URL('../openclawCronWorker.ts', import.meta.url), 'utf8');
const module = path.join(root, format === 'cjs' ? 'worker.cjs' : 'worker.mjs');
await fs.writeFile(module, transformSync(source, { loader: 'ts', format, platform: 'node', target: 'node22', logLevel: 'silent' }).code);
const worker = new Worker(module, { workerData: { database, storeKey: 'store', agentId: 'main', defaultAgent: true, modulePath: createRequire(import.meta.url).resolve('better-sqlite3') } });
try {
const reply = await new Promise<unknown>((resolve, reject) => { worker.once('message', resolve); worker.once('error', reject); });
- expect(reply).toEqual({ ok: true, jobs: [{ id: 'mine', enabled: true, state: { lastRunAtMs: 123 } }] });
- expect(db.prepare('SELECT COUNT(*) AS count FROM cron_jobs').get()).toEqual({ count: 3 });
+ expect(reply).toEqual({ ok: true, jobs: [{ id: 'mine', enabled: true, state: { lastRunAtMs: 123 } }, ...extra.map(job => ({ ...job, state: {} }))] });
+ expect(db.prepare('SELECT COUNT(*) AS count FROM cron_jobs').get()).toEqual({ count: 1103 });
} finally { await worker.terminate(); db.close(); }
});
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 5632bac5c1..465ce185f8 100644
--- a/apps/desktop/src/main/bot-import/__tests__/sources.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/sources.test.ts
@@ -45,7 +45,7 @@ it.each([
}
});
-it('shares one byte budget across referenced skill trees without truncating a snapshot', async () => {
+it('retains an over-budget skill for retry without dropping healthy siblings', async () => {
await write('.hermes/config.yaml', 'name: Ada\n');
for (const name of ['first', 'second']) {
await write(`.hermes/skills/${name}/SKILL.md`, `---\nname: ${name}\n---\nRead data.txt`);
@@ -58,7 +58,9 @@ it('shares one byte budget across referenced skill trees without truncating a sn
expect(snapshot.items.find(item => item.view.name === 'first')?.files?.find(file => file.name === 'data.txt')?.bytes.length).toBe(2048);
expect(snapshot.items.find(item => item.view.name === 'second')?.files).toHaveLength(1);
await write('.hermes/cron/jobs.json', jobs(['first', 'second']));
- await expect(inspectImportSource(source!, reader, createImportBudget(3000))).rejects.toThrow('SOURCE_SNAPSHOT_TOO_LARGE');
+ const partial = await inspectImportSource(source!, reader, createImportBudget(3000));
+ expect(partial.items.find(item => item.view.name === 'second')?.captureIssue).toBe('SOURCE_SNAPSHOT_TOO_LARGE');
+ expect(partial.items.find(item => item.view.name === 'first')?.files).toHaveLength(2);
});
it('counts configuration includes and memory against the same source budget', async () => {
@@ -66,7 +68,8 @@ it('counts configuration includes and memory against the same source budget', as
await write('.openclaw/extra.json', JSON.stringify({ name: 'x'.repeat(1000) }));
await write('.openclaw/workspace/MEMORY.md', 'x'.repeat(1000));
const reader = deps(); const [source] = await discoverImportSources(reader);
- await expect(inspectImportSource(source!, reader, createImportBudget(1500))).rejects.toThrow('SOURCE_SNAPSHOT_TOO_LARGE');
+ const partial = await inspectImportSource(source!, reader, createImportBudget(1500));
+ expect(partial.items.find(item => item.view.name === 'MEMORY.md')?.captureIssue).toBe('SOURCE_SNAPSHOT_TOO_LARGE');
});
it.each([123, '', ' ', 'invalid\0path'])('rejects malformed stdio cwd %j before import', async cwd => {
@@ -152,7 +155,7 @@ describe('installed agent imports', () => {
expect(JSON.stringify(mcp)).not.toContain('fake-selected-secret');
expect(JSON.stringify(telegram)).not.toContain('12345:fake-telegram-token');
});
- it('preserves personality and memory, defaults to used skills and resolves environment without shell evaluation', async () => {
+ it('preserves personality and memory, defaults to all skills and resolves environment without shell evaluation', async () => {
await write('.hermes/config.yaml', 'name: Ada\n');
await write('.hermes/SOUL.md', 'Calm, direct, and patient.');
await write('.hermes/memories/USER.md', 'Prefers concise answers.');
@@ -167,7 +170,7 @@ describe('installed agent imports', () => {
expect(result.items.find(item => item.role === 'identity')?.text).toBe('Calm, direct, and patient.');
expect(result.items.find(item => item.role === 'user')?.text).toContain('concise');
expect(result.items.find(item => item.view.name === 'report')?.view.selected).toBe(true);
- expect(result.items.find(item => item.view.name === 'unused')?.view.selected).toBe(false);
+ expect(result.items.find(item => item.view.name === 'unused')?.view.selected).toBe(true);
expect(result.items.find(item => item.env?.LITERAL)?.env?.LITERAL).toBe('$(never-run)');
expect(JSON.stringify(result.items.map(item => item.view))).not.toContain('not-a-real-secret');
const automation = result.items.find(item => item.automation)!;
@@ -367,3 +370,68 @@ it('still rejects cycles across concurrent include branches with the shared pars
await write('.hermes/b.yaml', '$include: a.yaml');
await expect(discoverImportSources(deps())).rejects.toThrow('SOURCE_CONFIG_INCLUDE_CYCLE');
});
+
+it('discovers 142 grouped Hermes skills and all memory documents, excluding archives and skill support folders', async () => {
+ await write('.hermes/config.yaml', 'skills:\n external_dirs: [../extra-skills]\n disabled: [skill-1]\nheartbeat:\n enabled: true\n');
+ for (let i = 0; i < 142; i++) {
+ await write(`.hermes/skills/group-${i % 13}/skill-${i}/SKILL.md`, `---\nname: skill-${i}\n---\nInstructions ${i}`);
+ }
+ for (let i = 0; i < 2100; i++) await write(`.hermes/memories/note-${i}.md`, `Memory ${i}`);
+ await write('.hermes/skills/.archive/old/SKILL.md', 'archived');
+ await write('.hermes/skills/group-0/skill-0/references/example/SKILL.md', 'example');
+ await write('extra-skills/category/extra/SKILL.md', '---\nname: extra\n---\nExtra');
+ await write('extra-skills/duplicate/SKILL.md', '---\nname: skill-0\n---\nShadow');
+ await write('.hermes/cron/jobs.json', JSON.stringify([{ id: 'heartbeat-job', name: 'heartbeat-main', prompt: 'Check', schedule: { kind: 'interval', minutes: 5 } }]));
+ const reader = deps(); const [source] = await discoverImportSources(reader);
+ const snapshot = await inspectImportSource(source!, reader);
+ const skills = snapshot.items.filter(item => item.view.category === 'skills');
+ expect(skills).toHaveLength(143);
+ expect(skills.every(item => item.view.selected)).toBe(true);
+ expect(skills.find(item => item.view.name === 'skill-1')?.view.enabled).toBe(false);
+ expect(snapshot.items.filter(item => item.view.category === 'memory')).toHaveLength(2100);
+ expect(snapshot.items.filter(item => item.automation).map(item => item.view.name)).toEqual(['heartbeat-main']);
+ expect(validateImportSelection({ requestId: 'large-hermes-import', previewId: 'p', name: 'Ada', entryIds: snapshot.items.map(item => item.view.id), takeover: false }, snapshot)).toHaveLength(snapshot.items.length);
+});
+
+it('uses OpenClaw declared names, skillKey, grouped roots and plugin sources in native precedence order', async () => {
+ await write('.openclaw/openclaw.json', JSON.stringify({ skills: { load: { extraDirs: ['../extra-skills'] }, entries: { 'auth-key': { enabled: false, env: { SERVICE_TOKEN: 'fixture-token' } } } }, plugins: { load: { paths: ['../my-plugin'] } } }));
+ await write('.openclaw/workspace/skills/category/renamed/SKILL.md', '---\nname: report\nmetadata:\n openclaw:\n skillKey: auth-key\n---\nWorkspace');
+ await write('.openclaw/skills/report/SKILL.md', '---\nname: report\n---\nShadow');
+ await write('.openclaw/workspace/.agents/skills/project/SKILL.md', '# Project');
+ await write('.agents/skills/personal/SKILL.md', '# Personal');
+ await write('extra-skills/extra/SKILL.md', '# Extra');
+ await write('my-plugin/openclaw.plugin.json', JSON.stringify({ id: 'sample', skills: ['skills'] }));
+ await write('my-plugin/skills/example/SKILL.md', '# Plugin');
+ const reader = deps(); const [source] = await discoverImportSources(reader);
+ const snapshot = await inspectImportSource(source!, reader);
+ const skills = snapshot.items.filter(item => item.view.category === 'skills');
+ expect(skills.map(item => item.view.name)).toEqual(['report', 'project', 'personal', 'extra', 'example']);
+ expect(skills[0]?.view).toMatchObject({ selected: true, enabled: false });
+ expect(skills[0]?.files?.[0]?.bytes.toString()).toContain('Workspace');
+ expect(snapshot.items.find(item => item.env?.SERVICE_TOKEN)?.view.selected).toBe(true);
+});
+
+it('follows trusted skill directory links without following resource escapes or cycles', async () => {
+ await write('.hermes/config.yaml', 'name: Ada');
+ await write('shared/report/SKILL.md', '---\nname: report\n---\nRead report');
+ await fs.mkdir(path.join(home, '.hermes/skills'), { recursive: true });
+ try { await fs.symlink(path.join(home, 'shared/report'), path.join(home, '.hermes/skills/report'), 'junction'); }
+ catch (error) { if (['EPERM', 'ENOTSUP'].includes((error as NodeJS.ErrnoException).code ?? '')) return; throw error; }
+ await fs.symlink(path.join(home, '.hermes/skills'), path.join(home, '.hermes/skills/loop'), 'junction');
+ const reader = deps(); const [source] = await discoverImportSources(reader);
+ const snapshot = await inspectImportSource(source!, reader);
+ expect(snapshot.items.filter(item => item.view.category === 'skills')).toHaveLength(1);
+ expect(snapshot.items[0]?.sourceDirectory).toBe(await fs.realpath(path.join(home, 'shared/report')));
+});
+
+it('retains unmapped skill authentication privately without deselecting the skill', async () => {
+ const secret = 'fixture-skill-key-without-env';
+ await write('.openclaw/openclaw.json', JSON.stringify({ skills: { entries: { report: { apiKey: secret } } } }));
+ await write('.openclaw/workspace/skills/report/SKILL.md', '---\nname: report\n---\nReport');
+ const reader = deps(); const [source] = await discoverImportSources(reader);
+ const snapshot = await inspectImportSource(source!, reader);
+ const skill = snapshot.items.find(item => item.view.category === 'skills')!;
+ expect(skill.view).toMatchObject({ selected: true, issues: ['MISSING_ENVIRONMENT_REFERENCE'] });
+ expect(skill.credential).toEqual({ format: 'source-skill-auth', value: { apiKey: secret } });
+ expect(JSON.stringify(skill.view)).not.toContain(secret);
+});
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 ada64123cd..9426ff23e8 100644
--- a/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts
@@ -6,6 +6,7 @@ import { transferCompanion, type ImportReceipt, type TransferDeps } from '../tra
import { CompanionImportError, type ImportSnapshot } from '../types.js';
import type { CompanionImportSelection } from '@cindy/maker-shared/companion-import';
import { normalizeAutomation } from '../sourceAutomations.js';
+import { fingerprint } from '../files.js';
const snapshot: ImportSnapshot = { source: { kind: 'hermes', agentId: 'default', name: 'Ada', root: '/fixture/hermes', workspace: '/fixture/work', configFile: '/fixture/hermes/config.yaml' }, fingerprint: 'fixture', items: [
{ view: { id: 'memory', category: 'memory', name: 'memory', selected: true }, text: 'Keep this' },
@@ -88,24 +89,15 @@ it.each([
const { deps } = harness();
const items = [...candidates, task];
const result = await transferCompanion({ ...snapshot, source, items }, { ...selection, entryIds: items.map(item => item.view.id) }, deps);
- // Both accounts could pass the fake reachability check; ambiguity must stop before it.
- if (candidates.length > 1) {
- expect(task.automation?.deliveries).toEqual([]);
- expect(result.checks.find(check => check.entryId === task.view.id)).toMatchObject({ status: 'needs-attention', message: 'DELIVERY_NEEDS_ADAPTER' });
- expect(deps.verifyAutomation).not.toHaveBeenCalled();
- expect(deps.pauseSource).not.toHaveBeenCalled();
- expect(deps.enableRoutine).not.toHaveBeenCalled();
- } else {
- expect(task.automation?.deliveries).toEqual([{ connectionId: 'work', chatId: '123' }]);
- expect(result.status).toBe('complete');
- expect(deps.pauseSource).toHaveBeenCalledOnce();
- expect(deps.enableRoutine).toHaveBeenCalledOnce();
- }
+ expect(task.automation?.deliveries).toEqual([]);
+ expect(result.status).toBe('complete');
+ expect(deps.pauseSource).toHaveBeenCalledOnce();
+ expect(deps.enableRoutine).toHaveBeenCalledOnce();
expect(vi.mocked(deps.saveEnvironment).mock.calls[0]![1]).toEqual(items);
}
});
-it.each(['personal', 'missing'])('binds an explicit Telegram account %s without falling back to another bot', async accountId => {
+it.each(['personal', 'missing'])('uses local delivery even when the source names Telegram account %s', async accountId => {
const source = { ...snapshot.source, kind: 'openclaw' as const };
const accounts = ['work', 'personal'].map(account => ({
view: { id: account, name: account, category: 'connections' as const, selected: true },
@@ -115,15 +107,33 @@ it.each(['personal', 'missing'])('binds an explicit Telegram account %s without
const { deps } = harness();
const items = [...accounts, task];
await transferCompanion({ ...snapshot, source, items }, { ...selection, entryIds: items.map(item => item.view.id) }, deps);
- if (accountId === 'personal') {
- expect(task.automation?.deliveries).toEqual([{ connectionId: 'personal', chatId: '123' }]);
- expect(deps.pauseSource).toHaveBeenCalledOnce();
- } else {
- expect(task.view.issues).toContain('DELIVERY_NEEDS_ADAPTER');
- expect(task.automation?.deliveries).toEqual([]);
- expect(deps.pauseSource).not.toHaveBeenCalled();
- expect(deps.enableRoutine).not.toHaveBeenCalled();
- }
+ expect(task.automation?.deliveries).toEqual([]);
+ expect(task.view.issues ?? []).not.toContain('DELIVERY_NEEDS_ADAPTER');
+ expect(deps.pauseSource).toHaveBeenCalledOnce();
+
+});
+
+it.each(['created', 'source-paused'] as const)('resumes a pre-upgrade %s receipt without recreating content or replacing its delivery binding', async phase => {
+ const { deps } = harness();
+ const legacy = structuredClone(snapshot);
+ legacy.items = legacy.items.filter(item => selection.entryIds.includes(item.view.id));
+ legacy.items.find(item => item.automation)!.automation!.deliveries = [{ connectionId: 'telegram', chatId: '123' }];
+ await deps.saveReceipt({
+ selectionHash: fingerprint([selection.name, undefined, selection.entryIds.toSorted(), true, legacy.source.kind, legacy.source.agentId, legacy.source.root]),
+ result: { requestId: selection.requestId, botId: 'existing-bot', canonicalSessionId: 'chat', status: 'needs-attention', checks: [{ entryId: 'memory', status: 'copied' }, { entryId: 'task', status: 'needs-attention' }] },
+ copied: ['memory'], environmentSaved: true, checkpointSaved: true, companionCreated: true,
+ routines: { task: { id: 'existing-routine', phase } },
+ });
+ const result = await transferCompanion(legacy, selection, deps);
+ expect(result).toMatchObject({ botId: 'existing-bot', status: 'complete', saved: true });
+ // The host reconciles creation idempotently under the original bot ID.
+ expect(deps.createCompanion).toHaveBeenCalledWith('existing-bot', selection);
+ expect(deps.importItem).not.toHaveBeenCalled();
+ expect(deps.saveCheckpoint).not.toHaveBeenCalled();
+ expect(deps.saveEnvironment).not.toHaveBeenCalled();
+ expect(deps.createRoutine).not.toHaveBeenCalled();
+ expect(deps.pauseSource).toHaveBeenCalledTimes(phase === 'created' ? 1 : 0);
+ expect(deps.enableRoutine).toHaveBeenCalledWith('existing-bot', 'existing-routine', expect.objectContaining({ automation: expect.objectContaining({ deliveries: [{ connectionId: 'telegram', chatId: '123' }] }) }));
});
describe('companion takeover transaction', () => {
@@ -223,8 +233,8 @@ it('checkpoints full selected skills before acknowledging or copying and resumes
expect(durable?.items.find(item => item.view.id === 'skill')?.files?.map(file => file.name)).toEqual(['scripts/query.py', 'SKILL.md']);
});
vi.mocked(deps.importItem).mockRejectedValueOnce(new Error('process interrupted'));
- await expect(transferCompanion(source, input, deps)).rejects.toThrow('process interrupted');
- expect(receipt()?.result.status).toBe('running');
+ expect((await transferCompanion(source, input, deps)).status).toBe('needs-attention');
+ expect(receipt()?.result.checks).toContainEqual({ entryId: 'memory', status: 'needs-attention', message: 'IMPORT_ITEM_FAILED' });
expect(durable).toBeDefined();
await fs.rm(root, { recursive: true, force: true });
vi.mocked(deps.verifyAutomation).mockImplementation(async () => {
@@ -258,3 +268,46 @@ it('takes over with either credential profile, blocks missing credentials, and r
expect(conflict.deps.saveCheckpoint).not.toHaveBeenCalled();
expect(conflict.receipt()).toBeUndefined();
});
+
+it('finishes saving before any login or read probe, then resumes takeover from chat', async () => {
+ const { deps, receipt } = harness();
+ const input = { ...selection, deferSetup: true };
+ const saved = await transferCompanion(snapshot, input, deps);
+ expect(saved.saved).toBe(true);
+ expect(saved.canonicalSessionId).toBe('chat');
+ expect(saved.checks).toContainEqual({ entryId: 'task', status: 'needs-attention', message: 'IMPORT_SETUP_DEFERRED' });
+ expect(deps.verifyAutomation).not.toHaveBeenCalled();
+ expect(deps.pauseSource).not.toHaveBeenCalled();
+ expect(receipt()?.checkpointSaved).toBe(true);
+ expect((await transferCompanion(snapshot, input, deps, false, true)).status).toBe('complete');
+ expect(deps.createRoutine).toHaveBeenCalledOnce();
+ expect(deps.pauseSource).toHaveBeenCalledOnce();
+});
+
+it('restores compact selections from a selected-only checkpoint without changing their meaning', async () => {
+ const { deps } = harness();
+ const indexed = { ...snapshot, items: snapshot.items.map((item, sourceIndex) => ({ ...item, sourceIndex })) };
+ const input: CompanionImportSelection = { ...selection, entryIds: [], entryRanges: [[0, 0], [2, 3]], deferSetup: true };
+ const first = await transferCompanion(indexed, input, deps);
+ expect(first.savedEntryIds).toEqual(['memory', 'env', 'task']);
+ const saved = vi.mocked(deps.saveCheckpoint).mock.calls[0]![1];
+ expect(saved.map(item => item.sourceIndex)).toEqual([0, 2, 3]);
+ expect((await transferCompanion({ ...indexed, items: saved }, input, deps, false, true)).status).toBe('complete');
+ expect(deps.importItem).toHaveBeenCalledTimes(1);
+});
+
+it.each(([[[0, 2], [2, 3]], [[-1, 0]], [[3, 2]], [[0, 99999]]] as Array<Array<[number, number]>>).map(entryRanges => ({ entryRanges })))('rejects invalid compact ranges $entryRanges before creating a companion', async ({ entryRanges }) => {
+ const { deps } = harness();
+ const indexed = { ...snapshot, items: snapshot.items.map((item, sourceIndex) => ({ ...item, sourceIndex })) };
+ await expect(transferCompanion(indexed, { ...selection, entryIds: [], entryRanges }, deps)).rejects.toThrow();
+ expect(deps.createCompanion).not.toHaveBeenCalled();
+});
+
+it('saves healthy content and a conversation when a single routine cannot be created', async () => {
+ const { deps } = harness();
+ vi.mocked(deps.createRoutine).mockRejectedValue(new Error('fixture write failed'));
+ const result = await transferCompanion(snapshot, { ...selection, deferSetup: true }, deps);
+ expect(result).toMatchObject({ saved: true, canonicalSessionId: 'chat', savedEntryIds: ['memory', 'env'] });
+ expect(result.checks).toContainEqual({ entryId: 'task', status: 'needs-attention', message: 'IMPORT_ITEM_FAILED' });
+ expect(deps.pauseSource).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/main/bot-import/__tests__/verification.test.ts b/apps/desktop/src/main/bot-import/__tests__/verification.test.ts
index 6e66b6d8dc..c09f2a5d5e 100644
--- a/apps/desktop/src/main/bot-import/__tests__/verification.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/verification.test.ts
@@ -178,7 +178,7 @@ it('rejects an oversized monitor response and cancels its body', async () => {
expect(cancel).toHaveBeenCalledOnce();
});
-it.each(['hermes', 'openclaw'] as const)('allows a %s reminder with a verified Telegram destination without skipping data or delivery checks', async kind => {
+it.each(['hermes', 'openclaw'] as const)('routes a %s reminder locally without probing its former Telegram destination', async kind => {
const token = '12345:fixture-private-token';
const selected: ImportItem[] = [
{ view: { id: 'token', name: 'TELEGRAM_BOT_TOKEN', category: 'connections', selected: true }, env: { TELEGRAM_BOT_TOKEN: token } },
@@ -203,20 +203,20 @@ it.each(['hermes', 'openclaw'] as const)('allows a %s reminder with a verified T
deliver: 'telegram:123', delivery: { mode: 'announce', channel: 'telegram', to: '123' },
}, selected, 'UTC')], selected)[0]!;
const item = reminder('Remind me to stretch');
- expect(item.view.dependsOn).toEqual(['telegram']);
+ expect(item.view.dependsOn).toEqual([]);
expect((await verifyImportedAutomation('/fixture', 'bot', item, () => {}, selected)).verified).toBe(true);
- expect(fetch.mock.calls.map(([url]) => new URL(url).pathname.split('/').at(-1))).toEqual(['getMe', 'getChat']);
+ expect(fetch).not.toHaveBeenCalled();
expect(oneShot.mock.calls[0]![1]).not.toContain('TELEGRAM_BOT_TOKEN');
expect(oneShot.mock.calls[0]![1]).not.toContain(token);
// A variable also used for data is still required, even if delivery uses it too.
for (const prompt of ['Read Telegram data using TELEGRAM_BOT_TOKEN', 'Read DATA_URL']) {
expect((await verifyImportedAutomation('/fixture', 'bot', reminder(prompt), () => {}, selected)).verified).toBe(false);
}
- // Delivery validation remains mandatory and must precede planning.
+ // An unavailable former destination does not block local reminders.
oneShot.mockClear();
fetch.mockResolvedValue(Response.json({ ok: false }, { status: 403 }));
- expect((await verifyImportedAutomation('/fixture', 'bot', item, () => {}, selected)).verified).toBe(false);
- expect(oneShot).not.toHaveBeenCalled();
+ expect((await verifyImportedAutomation('/fixture', 'bot', item, () => {}, selected)).verified).toBe(true);
+ expect(fetch).not.toHaveBeenCalled();
});
it('finds a second-page read tool, redacts its catalog before planning and forwards its original identity privately', async () => {
diff --git a/apps/desktop/src/main/bot-import/connectionProvider.ts b/apps/desktop/src/main/bot-import/connectionProvider.ts
index da6ae6d37b..a2bc444bc4 100644
--- a/apps/desktop/src/main/bot-import/connectionProvider.ts
+++ b/apps/desktop/src/main/bot-import/connectionProvider.ts
@@ -6,7 +6,8 @@ import type { McpProvider } from '@cindy/maker-core';
import { resolveLiziMcpSessionContext } from '@cindy/mcps';
import { readCompanionSessionEnvironment } from './runtime.js';
import { IMPORTED_TOOL_LIMIT, listImportedTools, withImportedConnection } from './connections.js';
-import { fingerprint } from './files.js';
+import { deserializeImportSnapshotAsync, fingerprint } from './files.js';
+import { continueCompanionImport, getCompanionImportResult, useCindyImportSettings } from './host.js';
import { connectionRedactions, importedContentRedactions, publicConnectionName, redactImportedResult, redactImportedTool, restoreImportedArguments } from './connectionCatalog.js';
import { withImportedSkillResources } from './skillResources.js';
@@ -28,6 +29,9 @@ export function createCompanionConnectionsProvider(): McpProvider {
const scope = await resolve();
if (!scope) return { tools: [] };
const tools: Tool[] = [{ name: 'run_command', description: 'Run a command with this companion’s imported environment and API credentials. Use this for imported skills and data queries that require their original environment. This executes arbitrary shell code with private credentials and may write files or use the network; it requires the current task’s command authorization. Output masking is not a security sandbox.', annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }, inputSchema: { type: 'object', properties: { command: { type: 'string' } }, required: ['command'], additionalProperties: false } }];
+ if (scope.environment.pendingImport) tools.push({ name: 'import_setup',
+ description: 'Inspect this teammate’s remaining import setup, or retry saved checks after the user is ready. Import is already saved; keep ordinary chat available and let the user defer setup. For login use the relevant existing account/plugin connection card, never ask for secrets in chat. The retry operation may check data connections and hand over originally selected automations only after verification. Source jobs keep running until then. If the user explicitly chooses this teammate’s current model and tool settings instead of source-specific model/tool settings, use_cindy_settings accepts entryIds from status; this saves that choice and never enables a task or bypasses a data check. Other unsupported semantics remain pending. Inspect first; never claim a connection or handover succeeded without its result.',
+ inputSchema: { type: 'object', properties: { operation: { type: 'string', enum: ['status', 'retry', 'use_cindy_settings'] }, offset: { type: 'integer', minimum: 0 }, entryIds: { type: 'array', items: { type: 'string' } } }, required: ['operation'], additionalProperties: false } });
for (const connection of scope.environment.mcp.filter(connection => connection.enabled !== false)) {
const secrets = connectionRedactions(connection, scope.environment.env);
// Keep a failed or partially paginated catalog local to its connection.
@@ -52,6 +56,26 @@ export function createCompanionConnectionsProvider(): McpProvider {
server.server.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
const scope = await resolve();
if (!scope) throw new Error('Companion connection unavailable');
+ if (request.params.name === 'import_setup') {
+ const operation = request.params.arguments?.operation;
+ const offset = request.params.arguments?.offset ?? 0;
+ if (!['status', 'retry', 'use_cindy_settings'].includes(String(operation)) || !Number.isSafeInteger(offset) || Number(offset) < 0) throw new Error('Invalid import setup request');
+ const pending = scope.environment.pendingImport;
+ if (!pending) return { content: [{ type: 'text', text: JSON.stringify({ complete: true }) }] };
+ if (operation === 'use_cindy_settings') await useCindyImportSettings(scope.botId, scope.userData, request.params.arguments?.entryIds, scope.assertOwner);
+ const result = operation === 'retry'
+ ? await continueCompanionImport(scope.botId, scope.userData, scope.assertOwner)
+ : await getCompanionImportResult(pending.selection.requestId);
+ scope.assertOwner();
+ if (result && result.botId !== scope.botId) throw new Error('Companion import unavailable');
+ const remaining = result?.checks.filter(check => check.status === 'needs-attention') ?? [];
+ // Publish only names and host reason codes; the encrypted snapshot never leaves Main.
+ const snapshot = await deserializeImportSnapshotAsync(pending.snapshotJson, scope.assertOwner);
+ const names = new Map(snapshot.items.map(item => [item.view.id, item.view.name]));
+ const response = { status: result?.status, total: remaining.length, nextOffset: Number(offset) + 20 < remaining.length ? Number(offset) + 20 : undefined,
+ items: remaining.slice(Number(offset), Number(offset) + 20).map(check => ({ ...check, name: names.get(check.entryId) })) };
+ return { content: [{ type: 'text', text: redactEnvironmentValues(JSON.stringify(response), importedContentRedactions(scope.environment)) }] };
+ }
if (request.params.name === 'run_command') {
const command = request.params.arguments?.command;
if (typeof command !== 'string' || !command.trim() || command.length > 32000) throw new Error('Invalid command');
diff --git a/apps/desktop/src/main/bot-import/files.ts b/apps/desktop/src/main/bot-import/files.ts
index b9efaadb27..1909e65c45 100644
--- a/apps/desktop/src/main/bot-import/files.ts
+++ b/apps/desktop/src/main/bot-import/files.ts
@@ -6,19 +6,16 @@ import { CompanionImportError, type ImportFile, type ImportItem, type ImportSnap
const MAX_FILE_BYTES = 16 * 1024 * 1024;
const MAX_ITEM_BYTES = 128 * 1024 * 1024;
-const MAX_FILES = 4096;
export const MAX_SNAPSHOT_BYTES = 128 * 1024 * 1024;
/** Shared by every read contributing to one snapshot, before allocating bytes. */
export function createImportBudget(limit = MAX_SNAPSHOT_BYTES) {
let remaining = limit;
- let files = 0;
const reserve = (size: number) => {
if (!Number.isSafeInteger(size) || size < 0 || size > remaining) throw new CompanionImportError('SOURCE_SNAPSHOT_TOO_LARGE');
remaining -= size;
};
return { reserve, reserveFile(size: number) {
- if (++files > MAX_FILES) throw new CompanionImportError('SOURCE_TOO_MANY_FILES');
reserve(size);
} };
}
@@ -136,7 +133,7 @@ export async function optionalText(root: string, file: string, budget?: ImportRe
}
/** Only traverses the selected skill/document subtree; never copies a whole Agent home. */
-export async function readImportTree(root: string, include: (name: string) => boolean = () => true, budget?: ImportReadBudget): Promise<ImportFile[]> {
+export async function readImportTree(root: string, include: (name: string) => boolean = () => true, budget?: ImportReadBudget, onError?: (name: string, error: unknown) => void): Promise<ImportFile[]> {
const result: ImportFile[] = [];
const visited = new Set<string>();
let size = 0;
@@ -149,13 +146,18 @@ export async function readImportTree(root: string, include: (name: string) => bo
for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
if (entry.name === '.git' || entry.name === '__pycache__' || entry.name === '.DS_Store') continue;
const file = path.join(dir, entry.name);
- const target = entry.isSymbolicLink() ? await fs.stat(file) : entry;
- if (target.isDirectory()) await visit(file);
- else if (include(path.relative(root, file).split(path.sep).join('/'))) {
- const item = await readImportFile(root, file, budget);
- size += item.bytes.length;
- if (size > MAX_ITEM_BYTES || result.length >= MAX_FILES) throw new CompanionImportError('SOURCE_ITEM_TOO_LARGE');
- result.push(item);
+ try {
+ const target = entry.isSymbolicLink() ? await fs.stat(file) : entry;
+ if (target.isDirectory()) await visit(file);
+ else if (include(path.relative(root, file).split(path.sep).join('/'))) {
+ const item = await readImportFile(root, file, budget);
+ size += item.bytes.length;
+ if (size > MAX_ITEM_BYTES) throw new CompanionImportError('SOURCE_ITEM_TOO_LARGE');
+ result.push(item);
+ }
+ } catch (error) {
+ if (!onError) throw error;
+ onError(path.relative(root, file).split(path.sep).join('/'), error);
}
}
visited.delete(real);
diff --git a/apps/desktop/src/main/bot-import/host.ts b/apps/desktop/src/main/bot-import/host.ts
index 7c7fe4125c..7aa92da301 100644
--- a/apps/desktop/src/main/bot-import/host.ts
+++ b/apps/desktop/src/main/bot-import/host.ts
@@ -1,3 +1,5 @@
+import { createMessage } from '../localDb/ipc/messages.js';
+import { t } from '../i18n.js';
import { randomUUID } from 'node:crypto';
import { promises as fs } from 'node:fs';
import path from 'node:path';
@@ -12,7 +14,7 @@ import type { CompanionImportPreview, CompanionImportResult, CompanionImportSele
import { activeOwnerScopeKey, getActiveAppSession, isAppSessionBoundaryPending, ownerScopedUserDataPath } from '../appSessionState.js';
import { createBotCanonicalSession, createBotProfile, getBotMemoryService, getBotRemoteResourceSource, reconcileBotProfileFolder } from '../localDb/ipc/bots.js';
import { readBotProfileFolder, writeBotProfileFolder, BOT_PROFILE_TEXT_MAX_BYTES } from '../maker-ipc/botProfileFolder.js';
-import { importBotSkillFiles, normalizeBotSkillSlug, validateBotSkillFiles, BOT_SKILL_MAX_COUNT } from '../maker-ipc/botSkillStore.js';
+import { importBotSkillFiles, normalizeBotSkillSlug, validateBotSkillFiles } from '../maker-ipc/botSkillStore.js';
import { withBotProfileLocks } from '../maker-ipc/botProfileLock.js';
import { getRoutineEngine, routineTools, updateBotRoutineLifecycle } from '../routines/service.js';
import { previewImportRedactions, retainedImportRedactions, resolveImportReferences, selectedImportEnvironment, selectedImportRedactions } from './environmentSelection.js';
@@ -99,7 +101,8 @@ function retainPreview(id: string, entry: Owned<ImportSnapshot>) {
export async function previewCompanionImport(sourceId: string, controller: string): Promise<CompanionImportPreview> {
const scope = owner();
const source = owned(sources, sourceId, controller);
- const snapshot = await inspectImportSource(source, readers()); scope.assert();
+ const inspected = await inspectImportSource(source, readers()); scope.assert();
+ const snapshot = { ...inspected, items: inspected.items.map((item, index) => ({ ...item, sourceIndex: index })) };
if (snapshot.avatarImageBase64) {
const buffer = Buffer.from(snapshot.avatarImageBase64, 'base64');
validateBotAvatarBuffer(buffer);
@@ -110,7 +113,7 @@ export async function previewCompanionImport(sourceId: string, controller: strin
retainPreview(id, { owner: scope.scope, controller, value: snapshot, createdAt: Date.now() });
const secrets = previewImportRedactions(snapshot.items);
const redact = (text: string) => redactEnvironmentValues(text, secrets);
- return { id, source: { id: sourceId, kind: source.kind, name: redact(source.name) }, name: redact(source.name),
+ return { id, selectionRanges: true, source: { id: sourceId, kind: source.kind, name: redact(source.name) }, name: redact(source.name),
...(snapshot.avatarImageBase64 ? { avatarImageBase64: snapshot.avatarImageBase64 } : {}),
entries: snapshot.items.map(({ view }) => ({ ...view, name: redact(view.name),
...(view.description === undefined ? {} : { description: redact(view.description) }) })) };
@@ -284,7 +287,7 @@ export async function ensureImportedAutomationReady(root: string, botId: string,
if (!current || request?.expectedRevision !== undefined && request.expectedRevision !== current.revision
|| request?.input && JSON.stringify(parseRoutineInput({ ...request.input, enabled: false })) !== expectedInput)
throw new CompanionImportError('TARGET_AUTOMATION_CHANGED');
- await startCompanionImport(pending.selection, `routine:${routineId}`);
+ await startCompanionImport(pending.selection, `routine:${routineId}`, false, true);
await jobs.get(`${scope.scope}:${pending.selection.requestId}`);
assertOwner(); scope.assert();
await assertImportedAutomationReady(root, botId, routineId, assertOwner);
@@ -295,13 +298,18 @@ export async function ensureImportedAutomationReady(root: string, botId: string,
}
/** Main-owned work survives closing the import dialog. Repeated request IDs join the same work. */
-export async function startCompanionImport(selection: CompanionImportSelection, controller: string, reconcileOnly = false): Promise<CompanionImportResult> {
+export async function startCompanionImport(selection: CompanionImportSelection, controller: string, reconcileOnly = false, resumeSetup = false): Promise<CompanionImportResult> {
const scope = owner();
if (!selection || typeof selection.previewId !== 'string') throw new CompanionImportError('INVALID_SELECTION');
const rejected = await readReceipt(scope.root, selection.requestId); scope.assert();
+ if (rejected?.cancelled) return rejected.result;
if (rejected?.creationRejected) return withBotProfileLocks([rejected.result.botId], () => cleanRejectedCreation(scope.root, rejected, scope.assert));
let snapshot: ImportSnapshot;
- try { snapshot = owned(previews, selection.previewId, controller); }
+ try {
+ // Once accepted, the durable selected snapshot is authoritative, including failed captures.
+ if (rejected?.checkpointSaved && rejected.result.status !== 'complete') throw new CompanionImportError('PREVIEW_EXPIRED');
+ snapshot = owned(previews, selection.previewId, controller);
+ }
catch (error) {
if (!(error instanceof CompanionImportError) || error.code !== 'PREVIEW_EXPIRED') throw error;
const receipt = await readReceipt(scope.root, selection.requestId); scope.assert();
@@ -311,28 +319,34 @@ export async function startCompanionImport(selection: CompanionImportSelection,
snapshot = await deserializeImportSnapshotAsync(pending.snapshotJson, scope.assert);
}
const selected = validateImportSelection(selection, snapshot);
- if (selected.filter(item => item.view.category === 'skills').length > BOT_SKILL_MAX_COUNT) throw new CompanionImportError('INVALID_SELECTION');
if (selection.avatarImageBase64 !== undefined) {
try { decodeBotAvatarImage(selection.avatarImageBase64); } catch { throw new CompanionImportError('INVALID_SELECTION'); }
}
- const contentSecrets = snapshot.publicationRedactions ?? Object.fromEntries([...new Set([
- ...Object.values(previewImportRedactions(snapshot.items)), ...Object.values(selectedImportRedactions(selected)),
- ])].map((value, index) => [`content_credential_${index}`, value]));
+ // A failed resource is read afresh on retry. Refresh masking metadata as well,
+ // without retaining unselected credential values that never occur in selected content.
+ const freshMasks = snapshot.publicationRedactions && selected.some(item => item.captureIssue)
+ ? await createImportSourceReader(readers()).readRedactions(snapshot.source) : {};
+ scope.assert();
+ const contentSecrets = snapshot.publicationRedactions ? { ...snapshot.publicationRedactions }
+ : Object.fromEntries(Object.values(previewImportRedactions(snapshot.items)).map((value, index) => [`content_credential_${index}`, value]));
+ const knownValues = new Set(Object.values(contentSecrets));
+ let nextMask = 0;
+ for (const value of [...Object.values(selectedImportRedactions(selected)), ...Object.values(freshMasks)]) {
+ if (knownValues.has(value)) continue;
+ while (`content_retry_${nextMask}` in contentSecrets) nextMask++;
+ contentSecrets[`content_retry_${nextMask++}`] = value;
+ knownValues.add(value);
+ }
const redactText = (text: string) => redactEnvironmentValues(text, contentSecrets);
const publicRoutine = (input: RoutineInput): RoutineInput => ({ ...input, name: redactText(input.name), prompt: redactText(input.prompt) });
- let retainedRedactions = snapshot.publicationRedactions;
// Resource capture finishes before saveCheckpoint; retain only selected embedded values.
- const publicationRedactions = (items: ImportSnapshot['items']) => retainedRedactions ??= retainedImportRedactions(items, contentSecrets);
+ const publicationRedactions = (items: ImportSnapshot['items']) => retainedImportRedactions(items, contentSecrets);
const skillSlug = (item: ImportSnapshot['items'][number]) => {
- const original = path.basename(item.sourceDirectory ?? item.view.name);
+ const original = item.view.name;
if (redactText(original) !== original) return `import-${fingerprint(item.view.id).slice(0, 16)}`;
const normalized = normalizeBotSkillSlug(original);
return normalized === original ? original : `${normalized?.slice(0, 35) || 'import'}-${fingerprint(item.view.id).slice(0, 8)}`;
};
- for (const role of ['identity', 'user', 'instructions'] as const) {
- const text = redactText(selected.filter(item => item.role === role).map(item => item.text).join('\n\n'));
- if (Buffer.byteLength(text, 'utf8') > BOT_PROFILE_TEXT_MAX_BYTES) throw new CompanionImportError('PROFILE_TEXT_TOO_LARGE');
- }
const prior = await readReceipt(scope.root, selection.requestId); scope.assert();
if (prior?.cancelled) return prior.result;
if (!prior) {
@@ -348,12 +362,12 @@ export async function startCompanionImport(selection: CompanionImportSelection,
// Capturing lazily selected resources may grow even a rejected selection.
const cached = previews.get(selection.previewId);
if (cached?.value === snapshot) retainPreview(selection.previewId, cached);
- try {
- for (const item of items.filter(item => item.view.category === 'skills')) {
+ for (const item of items.filter(item => item.view.category === 'skills' && !item.captureIssue)) {
+ try {
const slug = skillSlug(item);
validateBotSkillFiles(slug, projectImportedSkill(item.files ?? [], slug, contentSecrets).files);
- }
- } catch { throw new CompanionImportError('INVALID_SELECTION'); }
+ } catch { item.captureIssue = 'IMPORT_ITEM_FAILED'; }
+ }
},
readReceipt: requestId => readReceipt(scope.root, requestId),
saveReceipt: receipt => saveReceipt(scope.root, receipt),
@@ -379,10 +393,20 @@ export async function startCompanionImport(selection: CompanionImportSelection,
async importItem(botId, item) {
if (item.view.category === 'skills') {
const slug = skillSlug(item);
- await importBotSkillFiles(scope.root, botId, slug, projectImportedSkill(item.files ?? [], slug, contentSecrets).files, scope.assert);
- } else if (item.text && item.view.category === 'memory') {
+ const projected = projectImportedSkill(item.files ?? [], slug, contentSecrets);
+ await importBotSkillFiles(scope.root, botId, slug, projected.files, scope.assert, item.view.enabled !== false);
+ } else if (item.text && (item.view.category === 'memory' || item.view.category === 'personality')) {
await getBotMemoryService().importDocument(botId, item.view.id, redactText(item.view.name), redactText(item.text), item.role === 'user' ? 'user' : 'reference');
}
+ if (prior?.environmentSaved) await companionEnvironmentStore.update(scope.root, botId, scope.assert, environment => {
+ if (item.text !== undefined) { environment.documents ??= {}; environment.documents[item.view.id] = item.text; }
+ if (item.view.category === 'skills') {
+ const slug = skillSlug(item);
+ const originals = projectImportedSkill(item.files ?? [], slug, contentSecrets).originals;
+ if (originals) { environment.skillFiles ??= {}; environment.skillFiles[slug] = originals; }
+ }
+ environment.contentRedactions = { ...environment.contentRedactions, ...publicationRedactions([item]) };
+ });
},
async saveCheckpoint(botId, items) {
const previous = await companionEnvironmentStore.read(scope.root, botId, scope.assert);
@@ -420,12 +444,15 @@ export async function startCompanionImport(selection: CompanionImportSelection,
pendingImport: previous?.pendingImport ?? { selection, snapshotJson: await serializeImportSnapshotAsync({ ...snapshot, avatarImageBase64: selection.avatarImageBase64, items, publicationRedactions: publicationRedactions(items) }, scope.assert) },
automations: previous?.automations ?? {},
}, scope.assert);
- const roleText = (role: 'identity' | 'user' | 'instructions') => redactText(items.filter(item => item.role === role).map(item => item.text).join('\n\n'));
+ const roleText = (role: 'identity' | 'user' | 'instructions') => {
+ const text = redactText(items.filter(item => item.role === role).map(item => item.text).join('\n\n'));
+ return Buffer.byteLength(text, 'utf8') <= BOT_PROFILE_TEXT_MAX_BYTES ? text : `The imported ${role} documents are preserved in your personal memory. Search and read those original documents when applying the imported profile.`;
+ };
const folder = await readBotProfileFolder(scope.root, botId); scope.assert();
await writeBotProfileFolder(scope.root, botId, {
config: { ...folder.config, mcpMode: 'allowlist', mcpServers: [...new Set([
...(Array.isArray(folder.config.mcpServers) ? folder.config.mcpServers : []),
- ...(items.some(item => item.mcp || item.env) || Object.keys(skillFiles).length ? ['companion_connections'] : []),
+ 'companion_connections',
])] },
...(roleText('identity') ? { identitySource: roleText('identity') } : {}),
...(roleText('user') ? { userContextSource: roleText('user') } : {}),
@@ -448,7 +475,7 @@ export async function startCompanionImport(selection: CompanionImportSelection,
environment.automations[creationId] ??= { kind: snapshot.source.kind,
handover: item.view.enabled ? 'pending' : 'ready',
original: item.automation!.original, sourceId: item.automation!.sourceId, sourceRoot: snapshot.source.root, deliveries: item.automation!.deliveries,
- issues: [...(item.view.issues ?? []), ...(item.view.dependsOn?.some(id => !selection.entryIds.includes(id)) ? ['AUTOMATION_DEPENDENCY_NOT_SELECTED'] : [])] };
+ issues: [...(item.view.issues ?? []), ...(item.view.dependsOn?.some(id => !selected.some(item => item.view.id === id)) ? ['AUTOMATION_DEPENDENCY_NOT_SELECTED'] : [])] };
});
const routine = await routineTools.createOnce(botId, publicRoutine(input), creationId); scope.assert();
return routine.id;
@@ -499,12 +526,17 @@ export async function startCompanionImport(selection: CompanionImportSelection,
const botId = `import_${fingerprint(selection.requestId).slice(0, 24)}`;
const result = await withBotProfileLocks([botId], async () => {
scope.assert();
- const result = await transferCompanion(snapshot, selection, transferDeps, reconcileOnly || pass > 0);
+ const result = await transferCompanion(snapshot, selection, transferDeps, reconcileOnly || pass > 0, resumeSetup);
if (result.status === 'running' && pass >= 2) {
const receipt = await readReceipt(scope.root, selection.requestId); scope.assert();
if (receipt) { receipt.result.status = 'needs-attention'; await saveReceipt(scope.root, receipt); }
result.status = 'needs-attention';
}
+ if (selection.deferSetup && result.saved && result.canonicalSessionId) {
+ await createMessage(result.canonicalSessionId, { clientId: `companion-import:${selection.requestId}`, role: 'assistant',
+ content: t(`bots.import.${result.checks.some(check => check.status === 'needs-attention') ? 'chatSetup' : 'chatReady'}`) });
+ scope.assert();
+ }
if (result.status === 'complete') await companionEnvironmentStore.update(scope.root, result.botId, scope.assert, env => { delete env.pendingImport; });
return result;
});
@@ -549,3 +581,49 @@ async function accepted(task: Promise<CompanionImportResult>, root: string, requ
})();
return Promise.race([task, receipt]);
}
+
+/** Continue only this companion's durable request; no source discovery or new selection. */
+export async function continueCompanionImport(botId: string, root: string, assertOwner: () => void) {
+ const scope = owner();
+ assertOwner();
+ if (scope.root !== root) throw new CompanionImportError('OWNER_CHANGED');
+ const environment = await companionEnvironmentStore.read(root, botId, assertOwner);
+ const pending = environment?.pendingImport;
+ if (!pending) return undefined;
+ if (`import_${fingerprint(pending.selection.requestId).slice(0, 24)}` !== botId) throw new CompanionImportError('INVALID_COMPANION');
+ await startCompanionImport(pending.selection, `companion:${botId}`, false, true);
+ return getCompanionImportResult(pending.selection.requestId);
+}
+
+/** Explicit adoption of Cindy's runtime settings; source scheduling/data checks still apply. */
+export async function useCindyImportSettings(botId: string, root: string, entryIds: unknown, assertOwner: () => void): Promise<void> {
+ const scope = owner(); assertOwner();
+ if (scope.root !== root) throw new CompanionImportError('OWNER_CHANGED');
+ if (!Array.isArray(entryIds) || !entryIds.length || entryIds.some(id => typeof id !== 'string')) throw new CompanionImportError('INVALID_SELECTION');
+ await withBotProfileLocks([botId], async () => {
+ const environment = await companionEnvironmentStore.read(root, botId, assertOwner);
+ const pending = environment?.pendingImport;
+ if (!pending || `import_${fingerprint(pending.selection.requestId).slice(0, 24)}` !== botId) throw new CompanionImportError('INVALID_COMPANION');
+ const snapshot = await deserializeImportSnapshotAsync(pending.snapshotJson, assertOwner);
+ const selected = new Set(entryIds);
+ const items = snapshot.items.filter(item => selected.has(item.view.id));
+ if (items.length !== selected.size || items.some(item => !item.automation && !['source-model', 'source-tools'].includes(item.credential?.format ?? ''))) throw new CompanionImportError('INVALID_SELECTION');
+ const mappings = new Set(['SOURCE_TOOL_POLICY_NEEDS_MAPPING', 'AUTOMATION_MODEL_NEEDS_MAPPING']);
+ for (const item of items) item.view.issues = item.view.issues?.filter(issue => !mappings.has(issue));
+ const encoded = await serializeImportSnapshotAsync(snapshot, assertOwner);
+ await companionEnvironmentStore.update(root, botId, assertOwner, current => {
+ if (!current.pendingImport || current.pendingImport.selection.requestId !== pending.selection.requestId) throw new CompanionImportError('SELECTION_CHANGED');
+ current.pendingImport.snapshotJson = encoded;
+ for (const item of items) {
+ const binding = current.automations?.[fingerprint([pending.selection.requestId, item.view.id])];
+ if (binding) binding.issues = binding.issues?.filter(issue => !mappings.has(issue));
+ }
+ });
+ const receipt = await readReceipt(root, pending.selection.requestId); assertOwner();
+ if (receipt) {
+ receipt.result.checks = receipt.result.checks.map(check => selected.has(check.entryId) && mappings.has(check.message ?? '')
+ ? { ...check, status: items.find(item => item.view.id === check.entryId)?.automation ? 'needs-attention' : 'copied', message: 'IMPORT_SETUP_DEFERRED' } : check);
+ await saveReceipt(root, receipt);
+ }
+ });
+}
diff --git a/apps/desktop/src/main/bot-import/importProvider.ts b/apps/desktop/src/main/bot-import/importProvider.ts
index 349cebb75b..5f7adb86a7 100644
--- a/apps/desktop/src/main/bot-import/importProvider.ts
+++ b/apps/desktop/src/main/bot-import/importProvider.ts
@@ -15,7 +15,7 @@ export function createCompanionImportProvider(): McpProvider {
const server = new McpServer({ name: 'companion_import', version: '1.0.0' });
server.tool('import_agent', 'Import a selected local Hermes/OpenClaw agent into a teammate. Discover sources, preview selectable metadata, then import only IDs explicitly selected by the user. Secrets remain on the host. For takeover, the user must request taking over the automations. Poll status by the same requestId; never invent a new requestId after a lost reply.', {
operation: z.enum(['sources', 'preview', 'start', 'status']), sourceId: z.string().optional(),
- selection: z.object({ previewId: z.string(), requestId: z.string(), name: z.string(), avatarImageBase64: z.string().min(1).max(2_000_000).optional(), entryIds: z.array(z.string()), takeover: z.boolean() }).optional(),
+ selection: z.object({ previewId: z.string(), requestId: z.string(), name: z.string(), avatarImageBase64: z.string().min(1).max(2_000_000).optional(), entryIds: z.array(z.string()), takeover: z.boolean(), deferSetup: z.boolean().default(true), entryRanges: z.array(z.tuple([z.number().int().nonnegative(), z.number().int().nonnegative()])).optional() }).optional(),
requestId: z.string().optional(),
}, async input => {
const session = resolveLiziMcpSessionContext(context);
diff --git a/apps/desktop/src/main/bot-import/openclawCronWorker.ts b/apps/desktop/src/main/bot-import/openclawCronWorker.ts
index 3009cfbfe2..2170709d7f 100644
--- a/apps/desktop/src/main/bot-import/openclawCronWorker.ts
+++ b/apps/desktop/src/main/bot-import/openclawCronWorker.ts
@@ -15,8 +15,8 @@ try {
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))
- ORDER BY sort_order LIMIT 1001`).all(storeKey, agentId, defaultAgent ? 1 : 0) as Array<{ job_json: string; state_json: string }>;
- if (rows.length > 1000 || rows.reduce((n, row) => n + row.job_json.length + row.state_json.length, 0) > 16 * 1024 * 1024) throw new Error('limit');
+ ORDER BY sort_order`).all(storeKey, agentId, defaultAgent ? 1 : 0) as Array<{ job_json: string; state_json: string }>;
+ if (rows.reduce((n, row) => n + row.job_json.length + row.state_json.length, 0) > 16 * 1024 * 1024) throw new Error('limit');
parentPort?.postMessage({ ok: true, jobs: rows.map(row => ({ ...JSON.parse(row.job_json), state: JSON.parse(row.state_json) })) });
} catch {
// SQL errors may include source paths/content; only a stable code crosses back.
diff --git a/apps/desktop/src/main/bot-import/skills.ts b/apps/desktop/src/main/bot-import/skills.ts
new file mode 100644
index 0000000000..99cd46dd89
--- /dev/null
+++ b/apps/desktop/src/main/bot-import/skills.ts
@@ -0,0 +1,149 @@
+import { promises as fs } from 'node:fs';
+import path from 'node:path';
+import yaml from 'js-yaml';
+import { fingerprint, inside, readImportFile, readImportTree, type ImportReadBudget } from './files.js';
+import { CompanionImportError, object, string, type ImportItem, type ImportSource } from './types.js';
+
+/** Discovery roots are derived on the host from the selected source, never from IPC paths. */
+interface SkillRoot { directory: string; links: 'any' | string[]; bundled?: boolean }
+const ignored = new Set(['.git', '.github', '.hub', '.archive', '_archive', '.venv', 'venv', 'node_modules', 'site-packages', '__pycache__', '.tox', '.nox', '.pytest_cache', '.mypy_cache', '.ruff_cache']);
+const strings = (value: unknown): string[] => Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string' && !!v.trim()) : [];
+
+/** Resolve only path configuration; never expand credentials into public names. */
+function sourcePath(value: string, base: string, home: string, env: NodeJS.ProcessEnv) {
+ const expanded = value.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}|\$([A-Za-z_][A-Za-z0-9_]*)/g, (match, a, b) => env[a ?? b] ?? match);
+ return path.resolve(base, expanded === '~' ? home : expanded.startsWith('~/') ? path.join(home, expanded.slice(2)) : expanded);
+}
+
+async function readJson(file: string): Promise<Record<string, unknown>> {
+ try { return object(JSON.parse(await fs.readFile(file, 'utf8'))); }
+ catch (error) { if (['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '') || error instanceof SyntaxError) return {}; throw error; }
+}
+
+/** Locate the installed package through its executable; don't run source code during discovery. */
+async function openClawInstall(env: NodeJS.ProcessEnv): Promise<string | undefined> {
+ const candidates = (env.PATH ?? '').split(path.delimiter).filter(Boolean).flatMap(dir => [path.join(dir, 'openclaw'), path.join(dir, 'node_modules', 'openclaw', 'package.json')]);
+ for (const candidate of candidates) {
+ let real: string;
+ try { real = await fs.realpath(candidate); } catch { continue; }
+ let dir = path.dirname(real);
+ for (let depth = 0; depth < 5; depth++) {
+ if ((await readJson(path.join(dir, 'package.json'))).name === 'openclaw') return dir;
+ const parent = path.dirname(dir); if (parent === dir) break; dir = parent;
+ }
+ }
+}
+
+async function rootsFor(source: ImportSource, values: Record<string, unknown>, home: string, env: NodeJS.ProcessEnv): Promise<SkillRoot[]> {
+ const config = object(values.skills);
+ const resolve = (v: string) => sourcePath(v, source.root, home, env);
+ if (source.kind === 'hermes') return [path.join(source.root, 'skills'), ...strings(config.external_dirs).map(resolve)].map(directory => ({ directory, links: 'any' }));
+ const load = object(config.load);
+ const trusted = await Promise.all(strings(load.allowSymlinkTargets).map(async v => fs.realpath(resolve(v)).catch(() => resolve(v))));
+ const roots: SkillRoot[] = [
+ { directory: path.join(source.workspace, 'skills'), links: trusted },
+ { directory: path.join(source.workspace, '.agents', 'skills'), links: trusted },
+ ...(path.resolve(source.root) === path.join(home, '.openclaw') ? [{ directory: path.join(home, '.agents', 'skills'), links: 'any' as const }] : []),
+ { directory: path.join(source.root, 'skills'), links: 'any' },
+ { directory: path.join(source.root, 'agents', source.agentId, 'agent', 'workshop-skills'), links: trusted },
+ ];
+ const install = await openClawInstall(env);
+ if (install) roots.push({ directory: path.join(install, 'skills'), links: trusted, bundled: true });
+ for (const directory of strings(load.extraDirs).map(resolve)) roots.push({ directory, links: trusted });
+ // A plugin's manifest declares its skill roots. Disabled plugins stay out of the catalog.
+ const plugins = object(values.plugins);
+ if (plugins.enabled !== false) {
+ const locations = [...strings(object(plugins.load).paths).map(resolve),
+ ...Object.values(object(plugins.installs)).flatMap(value => string(object(value).installPath) ? [resolve(string(object(value).installPath))] : [])];
+ for (const parent of [path.join(source.root, 'extensions'), ...(install ? [path.join(install, 'extensions')] : [])]) {
+ try { for (const entry of await fs.readdir(parent, { withFileTypes: true })) if (entry.isDirectory()) locations.push(path.join(parent, entry.name)); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; }
+ }
+ for (const location of new Set(locations)) {
+ const manifest = await readJson(path.join(location, 'openclaw.plugin.json'));
+ const id = string(manifest.id) || path.basename(location);
+ if (object(object(plugins.entries)[id]).enabled === false || strings(plugins.deny).includes(id)) continue;
+ if (Array.isArray(plugins.allow) && !strings(plugins.allow).includes(id)) continue;
+ for (const folder of strings(manifest.skills)) {
+ const directory = path.resolve(location, folder);
+ if (inside(location, directory)) roots.push({ directory, links: trusted });
+ }
+ }
+ }
+ return roots;
+}
+
+/** Follow native precedence by declared name; grouped layouts stop at a skill entrypoint. */
+export async function discoverImportSkills(source: ImportSource, values: Record<string, unknown>, home: string, env: NodeJS.ProcessEnv, budget: ImportReadBudget, used = new Set<string>()): Promise<ImportItem[]> {
+ const items: ImportItem[] = [];
+ const names = new Set<string>();
+ const visited = new Set<string>();
+ const config = object(values.skills);
+ const disabled = new Set(strings(config.disabled));
+ const platformDisabled = object(config.platform_disabled);
+ for (const name of strings(platformDisabled.cli)) disabled.add(name);
+ for (const root of await rootsFor(source, values, home, env)) {
+ let realRoot: string;
+ try { realRoot = await fs.realpath(root.directory); }
+ catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue; throw error; }
+ async function visit(directory: string, depth: number): Promise<void> {
+ const real = await fs.realpath(directory);
+ if (visited.has(real)) return;
+ if (root.links !== 'any' && !inside(realRoot, real) && !root.links.some(allowed => inside(allowed, real))) return;
+ visited.add(real);
+ let manifest;
+ try { manifest = await readImportFile(real, path.join(real, 'SKILL.md'), budget); }
+ catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
+ const name = path.basename(directory);
+ items.push({ view: { id: `skill-${fingerprint(real).slice(0, 20)}`, category: 'skills', name, selected: true }, sourceDirectory: real,
+ filesComplete: false, captureIssue: error instanceof CompanionImportError ? error.code : 'IMPORT_ITEM_FAILED' });
+ return;
+ }
+ }
+ if (manifest?.bytes.toString('utf8').trim()) {
+ const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(manifest.bytes.toString('utf8'));
+ let info: Record<string, unknown> = {};
+ try { if (front) info = object(yaml.load(front[1]!)); } catch { /* Keep the original file for native loader diagnostics. */ }
+ const name = string(info.name) || path.basename(directory);
+ if (names.has(name)) return;
+ if (root.bundled && Array.isArray(config.allowBundled) && !strings(config.allowBundled).includes(name)) return;
+ names.add(name);
+ const metadata = object(object(info.metadata).openclaw ?? object(info.metadata).clawdbot ?? object(info.metadata).hermes);
+ const settings = object(object(config.entries)[string(metadata.skillKey) || name]);
+ const enabled = source.kind === 'hermes' ? !disabled.has(name) : settings.enabled !== false;
+ const item: ImportItem = { view: { id: `skill-${fingerprint(name).slice(0, 20)}`, category: 'skills', name,
+ description: string(info.description).slice(0, 280), selected: true, enabled },
+ sourceDirectory: real, sourceAlias: path.basename(directory), files: [manifest], filesComplete: false };
+ {
+ item.env = Object.fromEntries(Object.entries(object(settings.env)).filter(([key, value]) => /^[A-Za-z_][A-Za-z0-9_]*$/.test(key) && typeof value === 'string')) as Record<string, string>;
+ const primary = string(metadata.primaryEnv);
+ if (typeof settings.apiKey === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(primary)) item.env[primary] = settings.apiKey;
+ else if (settings.apiKey) {
+ item.view.issues = ['MISSING_ENVIRONMENT_REFERENCE'];
+ item.credential = { format: 'source-skill-auth', value: { apiKey: settings.apiKey } };
+ }
+ }
+ if (used.has(name) || used.has(path.basename(directory))) {
+ try {
+ item.files = [manifest, ...await readImportTree(real, name => name !== 'SKILL.md', budget)];
+ item.filesComplete = true;
+ } catch (error) { item.captureIssue = error instanceof CompanionImportError ? error.code : 'IMPORT_ITEM_FAILED'; }
+ }
+ items.push(item); return;
+ }
+ if (source.kind === 'openclaw' && depth >= 6) return;
+ for (const entry of (await fs.readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name))) {
+ if (ignored.has(entry.name) || entry.name.startsWith('.')) continue;
+ const child = path.join(directory, entry.name);
+ if (entry.isDirectory()) await visit(child, depth + 1);
+ else if (entry.isSymbolicLink()) {
+ try { if ((await fs.stat(child)).isDirectory()) await visit(child, depth + 1); }
+ catch (error) { if (!['ENOENT', 'ELOOP'].includes((error as NodeJS.ErrnoException).code ?? '')) throw error; }
+ }
+ }
+ }
+ await visit(root.directory, 0);
+ }
+ return items;
+}
diff --git a/apps/desktop/src/main/bot-import/sourceAutomations.ts b/apps/desktop/src/main/bot-import/sourceAutomations.ts
index 868f6274b2..fc3348852d 100644
--- a/apps/desktop/src/main/bot-import/sourceAutomations.ts
+++ b/apps/desktop/src/main/bot-import/sourceAutomations.ts
@@ -3,7 +3,6 @@ import { fingerprint } from './files.js';
import { object, string, type ImportItem, type ImportSource } from './types.js';
import path from 'node:path';
import { importedScriptName, isImportedScriptDependency } from './scripts.js';
-import { importDelivery } from './delivery.js';
/** Runtime counters are not configuration; changes to them must not invalidate a handover. */
export function automationFingerprint(job: Record<string, unknown>): string {
@@ -36,15 +35,12 @@ export function normalizeAutomation(source: ImportSource, job: Record<string, un
});
const scriptItems = items.filter(item => item.asset && isImportedScriptDependency(item.asset.name, scriptNames));
const skillItems = items.filter(item => item.view.category === 'skills'
- && (selectedSkills.has(item.view.name) || !!item.sourceDirectory && selectedSkills.has(path.basename(item.sourceDirectory))));
+ && (selectedSkills.has(item.view.name) || !!item.sourceAlias && selectedSkills.has(item.sourceAlias) || !!item.sourceDirectory && selectedSkills.has(path.basename(item.sourceDirectory))));
const searchText = [prompt, ...scriptItems.map(item => item.asset!.bytes.toString('utf8')), ...skillItems.flatMap(item => (item.files ?? []).filter(file => /\.(md|py|js|mjs|sh|ts|json|yaml|yml|toml)$/i.test(file.name)).map(file => file.bytes.toString('utf8')))].join('\n');
const dependsOn = items.filter(item =>
skillItems.includes(item) ||
item.mcp && searchText.includes(item.mcp.name) || scriptItems.includes(item)).map(item => item.view.id);
const environmentNames = [...new Set(items.flatMap(item => Object.keys(item.env ?? {})))].filter(key => new RegExp(`\\b${key}\\b`).test(searchText));
- const delivery = importDelivery(source, job, items);
- dependsOn.push(...delivery.deliveries.map(item => item.connectionId));
- issues.push(...delivery.issues);
if (scriptNames.some(name => !scriptItems.some(item => item.asset!.name === name))) issues.push('AUTOMATION_SCRIPT_MISSING');
if (job.no_agent === true && !job.script) issues.push('AUTOMATION_SCRIPT_MISSING');
// These source-specific semantics are retained verbatim and require an explicit adapter.
@@ -54,7 +50,6 @@ export function normalizeAutomation(source: ImportSource, job: Record<string, un
if (job.model || job.provider || job.base_url || payload.model || job.reasoning_effort || payload.thinking
|| items.some(item => item.credential?.format === 'source-model')) issues.push('AUTOMATION_MODEL_NEEDS_MAPPING');
if (job.workdir && path.resolve(string(job.workdir)) !== path.resolve(source.workspace)) issues.push('AUTOMATION_WORKDIR_NEEDS_MAPPING');
- if (job.failure_deliver && job.failure_deliver !== job.deliver) issues.push('DELIVERY_NEEDS_ADAPTER');
if (!sourceId || !name) issues.push('SOURCE_AUTOMATION_INVALID');
// These are explicit source features, not guessed equivalent prompt instructions.
if (Number(schedule.staggerMs) > 0) issues.push('AUTOMATION_STAGGER_NEEDS_ADAPTER');
@@ -68,6 +63,6 @@ export function normalizeAutomation(source: ImportSource, job: Record<string, un
description: string(job.schedule_display) || string(schedule.expr) || (trigger?.kind === 'once' && Number.isFinite(trigger.at) ? new Date(trigger.at).toISOString() : ''),
dependsOn, ...(issues.length ? { issues } : {}) },
envDependencies: { names: environmentNames, entries: dependsOn },
- automation: { sourceId, input, original: job, deliveries: delivery.deliveries, fingerprint: automationFingerprint(job) },
+ automation: { sourceId, input, original: job, deliveries: [], fingerprint: automationFingerprint(job) },
};
}
diff --git a/apps/desktop/src/main/bot-import/sources.ts b/apps/desktop/src/main/bot-import/sources.ts
index be958df93b..cbd844c21e 100644
--- a/apps/desktop/src/main/bot-import/sources.ts
+++ b/apps/desktop/src/main/bot-import/sources.ts
@@ -7,6 +7,7 @@ import { redactEnvironmentValues } from './process.js';
import yaml from 'js-yaml';
import { parse as parseEnv } from 'dotenv';
import { createImportBudget, fingerprint, optionalText, readImportFile, readImportTree, snapshotFingerprint, type ImportReadBudget } from './files.js';
+import { discoverImportSkills } from './skills.js';
import { normalizeAutomation } from './sourceAutomations.js';
import { CompanionImportError, object, string, type ImportItem, type ImportSnapshot, type ImportSource } from './types.js';
@@ -101,7 +102,7 @@ export async function discoverImportSources(deps: SourceReaderDeps, reader = cre
if (!/^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$/.test(id)) throw new CompanionImportError('SOURCE_AGENT_INVALID');
results.push({ kind: 'openclaw', agentId: id, name: string(row.name) || string(object(row.identity).name) || id,
root: clawRoot, configFile,
- workspace: sourcePath(deps.home, string(row.workspace) || string(defaults.workspace) || path.join(clawRoot, id === 'main' ? 'workspace' : `workspace-${id}`), clawRoot) });
+ workspace: sourcePath(deps.home, deps.env.OPENCLAW_WORKSPACE_DIR || string(row.workspace) || string(defaults.workspace) || path.join(clawRoot, id === 'main' ? 'workspace' : `workspace-${id}`), clawRoot) });
}
}
return results;
@@ -110,15 +111,26 @@ export async function discoverImportSources(deps: SourceReaderDeps, reader = cre
function entryId(prefix: string, name: string): string { return `${prefix}-${fingerprint(name).slice(0, 20)}`; }
async function document(items: ImportItem[], root: string, name: string, role: ImportItem['role'], category: 'personality' | 'memory', budget: ImportReadBudget) {
- const text = await optionalText(root, path.join(root, name), budget);
- if (!text?.trim()) return;
- items.push({ view: { id: entryId(category, name), category, name, selected: true }, text, role });
+ try {
+ const text = await optionalText(root, path.join(root, name), budget);
+ if (!text?.trim()) return;
+ items.push({ view: { id: entryId(category, name), category, name, selected: true }, text, role });
+ } catch (error) {
+ items.push({ view: { id: entryId(category, name), category, name, selected: true }, role,
+ sourceFile: { root, file: path.join(root, name) }, captureIssue: error instanceof CompanionImportError ? error.code : 'IMPORT_ITEM_FAILED' });
+ }
}
async function memoryDocuments(items: ImportItem[], root: string, prefix: string, budget: ImportReadBudget) {
if (!(await directories(root)).includes(prefix)) return;
- const files = await readImportTree(path.join(root, prefix), name => /\.md$/i.test(name), budget);
+ const directory = path.join(root, prefix);
+ const failed = (name: string, error: unknown) => items.push({ view: { id: entryId('memory', `${prefix}/${name}`), category: 'memory', name, selected: true },
+ sourceFile: { root: directory, file: path.join(directory, name) }, captureIssue: error instanceof CompanionImportError ? error.code : 'IMPORT_ITEM_FAILED' });
+ let files;
+ try { files = await readImportTree(directory, name => /\.md$/i.test(name), budget, failed); }
+ catch (error) { failed(prefix, error); return; }
for (const file of files.filter(file => /\.md$/i.test(file.name))) {
+ if (!file.bytes.toString('utf8').trim()) continue;
items.push({ view: { id: entryId('memory', `${prefix}/${file.name}`), category: 'memory', name: file.name, selected: true },
text: file.bytes.toString('utf8'), role: /(^|\/)USER\.md$/i.test(file.name) ? 'user' : undefined });
}
@@ -200,29 +212,6 @@ function scalarEnvHeaders(value: unknown): Record<string, string> {
return Object.fromEntries(Object.entries(object(value)).filter((entry): entry is [string, string] => typeof entry[1] === 'string'));
}
-async function skills(items: ImportItem[], roots: string[], used: Set<string>, budget: ImportReadBudget) {
- const names = new Set<string>();
- for (const root of roots) {
- for (const slug of await directories(root)) {
- if (names.has(slug)) continue;
- const dir = path.join(root, slug);
- let manifest;
- try { manifest = await readImportFile(dir, path.join(dir, 'SKILL.md'), budget); }
- catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue; throw error; }
- const text = manifest.bytes.toString('utf8');
- if (!text) continue;
- names.add(slug);
- let info: Record<string, unknown> = {};
- const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text);
- if (front) try { info = object(yaml.load(front[1]!)); } catch { /* Raw skill is retained, and its native loader reports syntax errors. */ }
- const name = string(info.name) || slug;
- const referenced = used.has(slug) || used.has(name);
- items.push({ view: { id: entryId('skill', slug), category: 'skills', name, description: string(info.description).slice(0, 280), selected: referenced },
- sourceDirectory: dir, files: referenced ? [manifest, ...await readImportTree(dir, name => name !== 'SKILL.md', budget)] : [manifest], filesComplete: referenced });
- }
- }
-}
-
function sourceConfiguration(items: ImportItem[], source: ImportSource, values: Record<string, unknown>) {
const row = source.kind === 'openclaw' ? agentRows(values).find(row => row.id === source.agentId) ?? {} : values;
const tools = source.kind === 'openclaw' ? { ...(values.tools ? { global: values.tools } : {}), ...(row.tools ? { agent: row.tools } : {}) } : object(values.tools);
@@ -244,7 +233,7 @@ export function createImportSourceReader(deps: SourceReaderDeps, budget = create
return pending;
};
const readConfig = (root: string, file: string) => config(root, file, budget, [], readText, configs);
- const readName = async (source: ImportSource): Promise<string> => {
+ const readRedactions = async (source: ImportSource): Promise<Record<string, string>> => {
const values = await readConfig(path.dirname(source.configFile), source.configFile);
const items: ImportItem[] = [];
// Skill credential settings live in config; no manifest/resource read is
@@ -257,9 +246,9 @@ export function createImportSourceReader(deps: SourceReaderDeps, budget = create
}
await connections(items, source, values, deps, budget, readText);
sourceConfiguration(items, source, values);
- return redactEnvironmentValues(source.name, previewImportRedactions(items));
+ return previewImportRedactions(items);
};
- return { readText: (root: string, file: string) => readText(root, file, budget), readConfig, readName };
+ return { readText: (root: string, file: string) => readText(root, file, budget), readConfig, readRedactions, readName: async (source: ImportSource) => redactEnvironmentValues(source.name, await readRedactions(source)) };
}
/** Snapshot immutable bytes once, then give the client only a safe selection projection. */
@@ -306,20 +295,13 @@ export async function inspectImportSource(source: ImportSource, deps: SourceRead
jobs = (Array.isArray(data.jobs) ? data.jobs : []).map(object).filter(job => (job.agentId ?? (defaultAgent ? source.agentId : undefined)) === source.agentId);
}
}
- const usedSkills = new Set(jobs.flatMap(job => [string(job.skill), ...(Array.isArray(job.skills) ? job.skills.map(string) : [])]).filter(Boolean));
- const skillRoots = source.kind === 'hermes' ? [path.join(source.root, 'skills')] : [path.join(workspace, 'skills'), path.join(source.root, 'skills')];
- await skills(items, skillRoots, usedSkills, budget);
- for (const item of items.filter(item => item.view.category === 'skills')) {
- const slug = path.basename(item.sourceDirectory!);
- const settings = object(object(object(values.skills).entries)[slug]);
- if (settings.env) item.env = scalarEnv(settings.env);
- if (settings.enabled === false) item.view.selected = false;
- const front = /^---\r?\n([\s\S]*?)\r?\n---/.exec(item.files?.find(file => file.name === 'SKILL.md')?.bytes.toString('utf8') ?? '');
- let metadata: Record<string, unknown> = {};
- try { if (front) metadata = object(object(yaml.load(front[1]!)).metadata); } catch { /* The original skill loader reports malformed frontmatter. */ }
- const primaryEnv = string(object(metadata.openclaw ?? metadata.clawdbot ?? metadata.hermes).primaryEnv);
- if (typeof settings.apiKey === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(primaryEnv)) item.env = { ...item.env, [primaryEnv]: settings.apiKey };
- else if (settings.apiKey) item.view.issues = ['MISSING_ENVIRONMENT_REFERENCE'];
+ items.push(...await discoverImportSkills(source, values, deps.home, deps.env, budget, new Set(jobs.flatMap(job => [string(job.skill), ...(Array.isArray(job.skills) ? job.skills.map(string) : [])]).filter(Boolean))));
+ // Credential alternatives must not deselect the skill that owns them.
+ for (const item of [...items]) if (item.view.category === 'skills' && item.env && Object.keys(item.env).length) {
+ const id = entryId('skill-env', item.view.id);
+ items.push({ view: { id, category: 'connections', name: item.view.name, selected: true }, env: item.env });
+ item.envDependencies = { names: Object.keys(item.env), entries: [] };
+ delete item.env;
}
await connections(items, source, values, deps, budget);
if (source.kind === 'hermes' && (await directories(source.root)).includes('scripts')) {
@@ -331,13 +313,8 @@ export async function inspectImportSource(source: ImportSource, deps: SourceRead
}
const row = source.kind === 'openclaw' ? agentRows(values).find(row => row.id === source.agentId) ?? {} : values;
sourceConfiguration(items, source, values);
- const heartbeat = source.kind === 'openclaw' ? object(row.heartbeat ?? object(object(values.agents).defaults).heartbeat) : object(values.heartbeat);
- if (Object.keys(heartbeat).length) {
- const heartbeatText = await optionalText(workspace, path.join(workspace, 'HEARTBEAT.md'), budget);
- items.push({ view: { id: entryId('automation', 'heartbeat'), name: 'Heartbeat', category: 'automations', selected: true, enabled: heartbeat.enabled !== false && heartbeat.every !== '0s', issues: ['AUTOMATION_TRIGGER_NEEDS_ADAPTER'] }, automation: { sourceId: 'heartbeat', original: { ...heartbeat, ...(heartbeatText ? { prompt: heartbeatText } : {}) }, fingerprint: fingerprint(heartbeat) } });
- }
+ // Native heartbeat is not a portable scheduled job. Ordinary jobs named heartbeat remain below.
for (const job of jobs) items.push(normalizeAutomation(source, job, items, string(values.timezone) || deps.env.TZ || Intl.DateTimeFormat().resolvedOptions().timeZone));
- if (items.length > 2000) throw new CompanionImportError('SOURCE_TOO_MANY_ITEMS');
const identity = items.find(item => item.view.name === 'IDENTITY.md')?.text ?? '';
const avatar = string(object(row.identity).avatar) || string(row.avatar) || /^\s*[-*]?\s*\*{0,2}Avatar\*{0,2}:\s*(.+)$/im.exec(identity)?.[1]?.trim() || '';
let avatarImageBase64: string | undefined;
diff --git a/apps/desktop/src/main/bot-import/transfer.ts b/apps/desktop/src/main/bot-import/transfer.ts
index 23e27aeef8..7e3e2988a7 100644
--- a/apps/desktop/src/main/bot-import/transfer.ts
+++ b/apps/desktop/src/main/bot-import/transfer.ts
@@ -1,6 +1,6 @@
import type { CompanionImportResult, CompanionImportSelection } from '@cindy/maker-shared/companion-import';
import type { RoutineInput } from '@cindy/maker-scheduler';
-import { createImportBudget, fingerprint, readImportTree, reserveSnapshotItems } from './files.js';
+import { createImportBudget, fingerprint, readImportFile, readImportTree, reserveSnapshotItems } from './files.js';
import { CompanionImportError, type ImportItem, type ImportSnapshot } from './types.js';
import { resolveImportEnvironmentDependencies, selectedImportEnvironment } from './environmentSelection.js';
@@ -39,22 +39,34 @@ export interface TransferDeps {
}
export function validateImportSelection(value: CompanionImportSelection, snapshot: ImportSnapshot): ImportItem[] {
- if (!value || typeof value.requestId !== 'string' || !/^[A-Za-z0-9_-]{16,100}$/.test(value.requestId) || typeof value.name !== 'string' || !value.name.trim() || value.name.length > 200 || typeof value.takeover !== 'boolean'
- || !Array.isArray(value.entryIds) || value.entryIds.some(id => typeof id !== 'string') || value.entryIds.length > 2000 || new Set(value.entryIds).size !== value.entryIds.length
+ if (!value || typeof value.requestId !== 'string' || !/^[A-Za-z0-9_-]{16,100}$/.test(value.requestId) || typeof value.name !== 'string' || !value.name.trim() || value.name.length > 200 || typeof value.takeover !== 'boolean' || value.deferSetup !== undefined && typeof value.deferSetup !== 'boolean'
+ || !Array.isArray(value.entryIds) || value.entryIds.some(id => typeof id !== 'string') || new Set(value.entryIds).size !== value.entryIds.length
|| value.avatarImageBase64 !== undefined && (typeof value.avatarImageBase64 !== 'string' || !value.avatarImageBase64.length || value.avatarImageBase64.length > 2_000_000))
throw new CompanionImportError('INVALID_SELECTION');
const selected = new Set(value.entryIds);
- const items = snapshot.items.filter(item => selected.has(item.view.id));
- if (items.length !== selected.size) throw new CompanionImportError('SELECTION_CHANGED');
+ let ranges: Array<[number, number]> | undefined;
+ if (value.entryRanges !== undefined) {
+ if (value.entryIds.length || !Array.isArray(value.entryRanges)) throw new CompanionImportError('INVALID_SELECTION');
+ let previous = -1;
+ for (const range of value.entryRanges) {
+ if (!Array.isArray(range) || range.length !== 2 || !range.every(Number.isSafeInteger) || range[0] <= previous || range[1] < range[0]) throw new CompanionImportError('INVALID_SELECTION');
+ previous = range[1];
+ }
+ ranges = value.entryRanges;
+ }
+ const items = snapshot.items.filter(item => ranges ? item.sourceIndex !== undefined && ranges.some(([first, last]) => item.sourceIndex! >= first && item.sourceIndex! <= last) : selected.has(item.view.id));
+ const count = ranges ? ranges.reduce((sum, [first, last]) => sum + last - first + 1, 0) : selected.size;
+ if (!Number.isSafeInteger(count) || items.length !== count) throw new CompanionImportError('SELECTION_CHANGED');
selectedImportEnvironment(items);
return resolveImportEnvironmentDependencies(items);
}
/** One receipt is shared by GUI, remote actions and command callers. Writes are serialized by the host. */
-export async function transferCompanion(snapshot: ImportSnapshot, selection: CompanionImportSelection, deps: TransferDeps, reconcileOnly = false): Promise<CompanionImportResult> {
+export async function transferCompanion(snapshot: ImportSnapshot, selection: CompanionImportSelection, deps: TransferDeps, reconcileOnly = false, resumeSetup = false): Promise<CompanionImportResult> {
const items = validateImportSelection(selection, snapshot);
deps.assertOwner();
- const selectionHash = fingerprint([selection.name, selection.avatarImageBase64, selection.entryIds.toSorted(), selection.takeover, snapshot.source.kind, snapshot.source.agentId, snapshot.source.root]);
+ const selectedIds = items.map(item => item.view.id);
+ const selectionHash = fingerprint([selection.name, selection.avatarImageBase64, selectedIds.toSorted(), selection.takeover, snapshot.source.kind, snapshot.source.agentId, snapshot.source.root]);
const existing = await deps.readReceipt(selection.requestId);
deps.assertOwner();
if (existing && existing.selectionHash !== selectionHash) throw new CompanionImportError('REQUEST_ALREADY_USED');
@@ -73,15 +85,31 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com
receipt.result.checks = receipt.result.checks.filter(item => item.entryId !== 'import');
// Capture only selected resources, then publish a non-secret request index
// before storing credentials. Acceptance still waits for the full checkpoint.
- if (!receipt.checkpointSaved) {
+ if (!receipt.checkpointSaved || items.some(item => item.captureIssue)) {
const budget = createImportBudget();
reserveSnapshotItems(snapshot.items, budget);
for (const item of items) {
+ if (item.captureIssue && item.sourceDirectory && item.filesComplete && !receipt.copied.includes(item.view.id)) {
+ item.files = undefined; item.filesComplete = false;
+ }
+ if (item.captureIssue && item.sourceFile) {
+ try {
+ item.text = (await readImportFile(item.sourceFile.root, item.sourceFile.file, budget)).bytes.toString('utf8');
+ delete item.captureIssue;
+ } catch (error) { item.captureIssue = error instanceof CompanionImportError ? error.code : 'IMPORT_ITEM_FAILED'; }
+ deps.assertOwner();
+ }
if (item.sourceDirectory && !item.filesComplete) {
const captured = item.files ?? [];
const names = new Set(captured.map(file => file.name));
- item.files = [...captured, ...await readImportTree(item.sourceDirectory, name => !names.has(name), budget)];
- item.filesComplete = true;
+ try {
+ item.files = [...captured, ...await readImportTree(item.sourceDirectory, name => !names.has(name), budget)];
+ item.filesComplete = true;
+ delete item.captureIssue;
+ } catch (error) {
+ deps.assertOwner();
+ item.captureIssue = error instanceof CompanionImportError ? error.code : 'IMPORT_ITEM_FAILED';
+ }
deps.assertOwner();
}
}
@@ -100,10 +128,16 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com
for (const item of items.filter(item => item.view.category !== 'automations' && item.view.category !== 'connections')) {
if (receipt.copied.includes(item.view.id)) continue;
deps.assertOwner();
- await deps.importItem(botId, item, snapshot);
- deps.assertOwner();
- receipt.copied.push(item.view.id);
- check(item.view.id, 'copied');
+ try {
+ if (item.captureIssue) throw new CompanionImportError(item.captureIssue);
+ await deps.importItem(botId, item, snapshot);
+ deps.assertOwner();
+ receipt.copied.push(item.view.id);
+ 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');
+ }
await save();
}
if (!receipt.environmentSaved) {
@@ -113,19 +147,19 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com
await save();
}
for (const item of items.filter(item => item.view.category === 'connections')) {
- const issue = item.view.dependsOn?.some(id => !selection.entryIds.includes(id)) ? 'AUTOMATION_DEPENDENCY_NOT_SELECTED' : item.view.issues?.[0];
+ const issue = item.view.dependsOn?.some(id => !selectedIds.includes(id)) ? 'AUTOMATION_DEPENDENCY_NOT_SELECTED' : item.view.issues?.[0];
check(item.view.id, issue ? 'needs-attention' : 'copied', issue);
}
receipt.result.canonicalSessionId = await deps.createConversation(botId);
await save();
- const selected = new Set(selection.entryIds);
+ const selected = new Set(selectedIds);
const byId = new Map(items.map(item => [item.view.id, item]));
const missingDependency = (id: string, visited = new Set<string>()): boolean => {
if (!selected.has(id)) return true;
if (visited.has(id)) return false;
visited.add(id);
const item = byId.get(id);
- return !!item?.view.issues?.length || !!item?.view.dependsOn?.some(child => missingDependency(child, visited));
+ return !!item?.captureIssue || item?.view.enabled === false && (item.view.category === 'skills' || !!item.mcp) || receipt.result.checks.some(check => check.entryId === id && check.status === 'needs-attention') || !!item?.view.issues?.length || !!item?.view.dependsOn?.some(child => missingDependency(child, visited));
};
for (const item of items.filter(item => item.automation)) {
// Background reconciliation repairs only interrupted work. A definitive
@@ -140,26 +174,41 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com
}
let record = receipt.routines[item.view.id];
if (!record) {
- const id = await deps.createRoutine(botId, { ...automation.input, enabled: false }, fingerprint([selection.requestId, item.view.id]), item);
- deps.assertOwner();
- record = receipt.routines[item.view.id] = { id, phase: 'created' };
- await save();
- }
- if (item.view.issues?.length) {
- check(item.view.id, 'needs-attention', item.view.issues[0]); await save(); continue;
+ try {
+ const id = await deps.createRoutine(botId, { ...automation.input, enabled: false }, fingerprint([selection.requestId, item.view.id]), item);
+ deps.assertOwner();
+ record = receipt.routines[item.view.id] = { id, phase: 'created' };
+ await save();
+ } catch (error) {
+ deps.assertOwner();
+ check(item.view.id, 'needs-attention', error instanceof CompanionImportError ? error.code : 'IMPORT_ITEM_FAILED');
+ await save(); continue;
+ }
}
if (record.phase === 'complete') { check(item.view.id, item.view.enabled && selection.takeover ? 'taken-over' : 'paused'); continue; }
if (!item.view.enabled || !selection.takeover) {
record.phase = 'complete'; check(item.view.id, 'paused'); await save(); continue;
}
+ if (item.view.issues?.length) {
+ check(item.view.id, 'needs-attention', item.view.issues[0]); await save(); continue;
+ }
+ if (selection.deferSetup && !resumeSetup && record.phase === 'created') {
+ check(item.view.id, 'needs-attention', 'IMPORT_SETUP_DEFERRED'); await save(); continue;
+ }
if (item.view.dependsOn?.some(id => missingDependency(id))) {
check(item.view.id, 'needs-attention', 'AUTOMATION_DEPENDENCY_NOT_SELECTED'); await save(); continue;
}
if (record.phase === 'created') {
- const verification = await deps.verifyAutomation(botId, item);
- deps.assertOwner();
- if (!verification.verified) { check(item.view.id, 'needs-attention', verification.reason ?? 'AUTOMATION_READ_NOT_VERIFIED'); await save(); continue; }
- record.phase = 'verified'; check(item.view.id, 'verified'); await save();
+ try {
+ const verification = await deps.verifyAutomation(botId, item);
+ deps.assertOwner();
+ if (!verification.verified) { check(item.view.id, 'needs-attention', verification.reason ?? 'AUTOMATION_READ_NOT_VERIFIED'); await save(); continue; }
+ record.phase = 'verified'; check(item.view.id, 'verified'); await save();
+ } catch (error) {
+ deps.assertOwner();
+ check(item.view.id, 'needs-attention', error instanceof CompanionImportError ? error.code : 'AUTOMATION_READ_NOT_VERIFIED');
+ await save(); continue;
+ }
}
try {
if (record.phase === 'verified' || record.phase === 'pausing-source') {
@@ -186,6 +235,11 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Com
await save();
}
}
+ receipt.result.savedEntryIds = [...new Set([...receipt.copied,
+ ...items.filter(item => item.view.category === 'connections' && receipt.environmentSaved).map(item => item.view.id),
+ ...Object.keys(receipt.routines),
+ ])];
+ receipt.result.saved = true;
receipt.result.status = Object.values(receipt.routines).some(item => item.phase === 'pausing-source' || item.phase === 'source-paused') ? 'running'
: receipt.result.checks.some(check => check.status === 'needs-attention') ? 'needs-attention' : 'complete';
await save();
diff --git a/apps/desktop/src/main/bot-import/types.ts b/apps/desktop/src/main/bot-import/types.ts
index ce4a43d0d4..74ce03061b 100644
--- a/apps/desktop/src/main/bot-import/types.ts
+++ b/apps/desktop/src/main/bot-import/types.ts
@@ -38,10 +38,17 @@ export interface ImportedDelivery { connectionId: string; chatId: string; thread
/** Private, host-only content. Do not serialize this into IPC, logs or model messages. */
export interface ImportItem {
view: CompanionImportEntry;
+ /** Stable index in the originating preview, retained in selected-only checkpoints. */
+ sourceIndex?: number;
files?: ImportFile[];
sourceDirectory?: string;
+ sourceAlias?: string;
+ /** Failed individual document read; retained for an explicit retry. */
+ sourceFile?: { root: string; file: string };
/** Selected skill resources have been captured for copying, verification and restart. */
filesComplete?: boolean;
+ /** Item-level capture failure retained for a later retry, without discarding healthy siblings. */
+ captureIssue?: string;
text?: string;
role?: 'identity' | 'user' | 'instructions';
env?: Record<string, string>;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botSkillStore.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botSkillStore.test.ts
index 33b7895dd0..b62218efb3 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/botSkillStore.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/botSkillStore.test.ts
@@ -10,7 +10,6 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import {
BOT_SKILL_MAX_BODY_BYTES,
- BOT_SKILL_MAX_COUNT,
BotSkillStoreError,
botSkillRootDir,
botSkillsDir,
@@ -165,11 +164,11 @@ describe('saveBotSkill — 形成', () => {
).rejects.toMatchObject({ errorCode: 'SKILL_NAME_UNUSABLE' });
});
- it('caps how many skills one Bot can accumulate', async () => {
+ it('preserves more than 142 skills and allows continued learning', async () => {
// Capture this test's directory so a timed-out continuation cannot use a later fixture.
const testUserDataDir = userDataDir;
// Seed existing files directly: saving each one repeatedly scans the growing directory.
- for (let index = 0; index < BOT_SKILL_MAX_COUNT - 1; index += 1) {
+ for (let index = 0; index < 142 - 1; index += 1) {
const slug = `skill-${index}`;
const skillDir = path.join(botSkillsDir(testUserDataDir, 'bot-1'), slug);
await fs.mkdir(skillDir, { recursive: true });
@@ -180,13 +179,13 @@ describe('saveBotSkill — 形成', () => {
updatedAt: '2026-08-19T00:00:00.000Z',
}));
}
- const lastSkill = { ...SAMPLE, name: `skill-${BOT_SKILL_MAX_COUNT - 1}` };
+ const lastSkill = { ...SAMPLE, name: `skill-${142 - 1}` };
expect((await saveBotSkill(testUserDataDir, 'bot-1', lastSkill)).created).toBe(true);
await expect(
saveBotSkill(testUserDataDir, 'bot-1', { ...SAMPLE, name: 'one-too-many' }),
- ).rejects.toMatchObject({ errorCode: 'SKILL_LIMIT_REACHED' });
+ ).resolves.toMatchObject({ created: true });
expect((await saveBotSkill(testUserDataDir, 'bot-1', lastSkill)).created).toBe(false);
- expect(await listBotSkills(testUserDataDir, 'bot-1')).toHaveLength(BOT_SKILL_MAX_COUNT);
+ expect(await listBotSkills(testUserDataDir, 'bot-1')).toHaveLength(143);
});
it('never lets a slug escape the per-bot skills dir', async () => {
@@ -306,3 +305,14 @@ it('imports real skill resources and preserves a user edit when the import is re
await expect(importBotSkillFiles(userDataDir, 'bot-1', 'imported', files, () => {})).rejects.toThrow('Imported skill was edited');
expect(await fs.readFile(path.join(folder, 'templates/report.txt'), 'utf8')).toBe('User changed it');
});
+
+it('retains a disabled imported skill without mounting or re-enabling it when edited', async () => {
+ await importBotSkillFiles(userDataDir, 'bot-1', 'disabled', [{ name: 'SKILL.md', bytes: Buffer.from('# Original'), executable: false }], () => {}, false);
+ expect(await listBotSkills(userDataDir, 'bot-1', false)).toEqual([]);
+ expect(await listBotSkills(userDataDir, 'bot-1')).toMatchObject([{ slug: 'disabled', enabled: false }]);
+ const updated = await saveBotSkill(userDataDir, 'bot-1', { ...SAMPLE, slug: 'disabled' });
+ expect(updated.record.enabled).toBe(false);
+ expect(await listBotSkills(userDataDir, 'bot-1', false)).toEqual([]);
+ expect(await deleteBotSkill(userDataDir, 'bot-1', 'disabled')).toBe(true);
+ expect(await listBotSkills(userDataDir, 'bot-1')).toEqual([]);
+});
diff --git a/apps/desktop/src/main/maker-ipc/botSkillService.ts b/apps/desktop/src/main/maker-ipc/botSkillService.ts
index f8bd4c1e21..d7d95ab6e9 100644
--- a/apps/desktop/src/main/maker-ipc/botSkillService.ts
+++ b/apps/desktop/src/main/maker-ipc/botSkillService.ts
@@ -50,6 +50,7 @@ function toWire(item: BotSkillSummary): BotSkillWireSummary {
name: item.name,
description: item.description,
updatedAt: item.updatedAt,
+ ...(item.enabled === false ? { enabled: false } : {}),
};
}
@@ -291,7 +292,7 @@ export async function collectBotOwnSkillMounts(
}> {
const boundary = captureOwnerBoundary(deps);
const userDataDir = await skillHomeOf(deps, botId, boundary);
- const skills = await listBotSkills(userDataDir, botId);
+ const skills = await listBotSkills(userDataDir, botId, false);
const baseline = await collectTeammateGuideMount(userDataDir);
assertOwnerBoundary(deps, boundary);
return {
diff --git a/apps/desktop/src/main/maker-ipc/botSkillStore.ts b/apps/desktop/src/main/maker-ipc/botSkillStore.ts
index 7d29fa9e25..b3706b940f 100644
--- a/apps/desktop/src/main/maker-ipc/botSkillStore.ts
+++ b/apps/desktop/src/main/maker-ipc/botSkillStore.ts
@@ -27,7 +27,7 @@
* 绝不退化成随机名(用户在设置页看到的必须是他能认出来的东西)。
* - 所有对外入口都用 `resolveSkillDir` 解析并断言落在自己的 `skills/` 下,
* `../` 一类穿越在这一步被挡掉,不依赖调用方先做净化。
- * - 单个技能正文与技能条数都有硬上限:模型可以自己写,但不能把用户磁盘写满。
+ * - 单次生成正文有界;存储容量不按技能条数限制。
*/
import { promises as fs } from 'node:fs';
@@ -50,6 +50,8 @@ export interface BotSkillRecord {
dirPath: string;
/** SKILL.md 的绝对路径。 */
filePath: string;
+ /** Imported disabled skills are retained outside the native plugin scan. */
+ enabled?: boolean;
}
/** list 只需要元信息时用的轻量形态(不读正文,省 IO)。 */
@@ -59,8 +61,6 @@ export const BOT_SKILL_MAX_NAME_CHARS = 64;
export const BOT_SKILL_MAX_DESCRIPTION_CHARS = 280;
/** 单个 SKILL.md 正文上限。技能是「怎么做」的清单,不是知识库。 */
export const BOT_SKILL_MAX_BODY_BYTES = 64 * 1024;
-/** 每个伙伴的技能条数上限。超过就必须先删旧的,避免无声膨胀。 */
-export const BOT_SKILL_MAX_COUNT = 100;
export interface BotSkillWriteInput {
name: string;
@@ -137,8 +137,8 @@ export function normalizeBotSkillSlug(value: string): string | null {
}
/** 解析并断言目标目录仍在这个伙伴的 `skills/` 下 —— 路径穿越在这里止步。 */
-function resolveSkillDir(userDataDir: string, botId: string, slug: string): string {
- const root = path.resolve(botSkillsDir(userDataDir, botId));
+function resolveSkillDir(userDataDir: string, botId: string, slug: string, enabled = true): string {
+ const root = path.resolve(enabled ? botSkillsDir(userDataDir, botId) : path.join(botSkillRootDir(userDataDir, botId), 'disabled-skills'));
const resolved = path.resolve(root, slug);
const relative = path.relative(root, resolved);
if (
@@ -296,15 +296,17 @@ async function readSkillFilePath(skillDir: string): Promise<string | null> {
export async function listBotSkills(
userDataDir: string,
botId: string,
+ includeDisabled = true,
+ enabled = true,
): Promise<BotSkillSummary[]> {
- const dir = botSkillsDir(userDataDir, botId);
+ const dir = enabled ? botSkillsDir(userDataDir, botId) : path.join(botSkillRootDir(userDataDir, botId), 'disabled-skills');
let entries: string[];
try {
entries = (await fs.readdir(dir, { withFileTypes: true }))
.filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
.map((entry) => entry.name);
} catch {
- return [];
+ entries = [];
}
const out: BotSkillSummary[] = [];
for (const slug of entries.sort()) {
@@ -324,8 +326,10 @@ export async function listBotSkills(
updatedAt: parsed.updatedAt,
dirPath: skillDir,
filePath,
+ ...(enabled ? {} : { enabled: false }),
});
}
+ if (includeDisabled && enabled) out.push(...await listBotSkills(userDataDir, botId, false, false));
return out.sort((a, b) => a.name.localeCompare(b.name));
}
@@ -335,8 +339,10 @@ export async function readBotSkill(
botId: string,
slug: string,
): Promise<BotSkillRecord | null> {
- const skillDir = resolveSkillDir(userDataDir, botId, slug);
- const filePath = await readSkillFilePath(skillDir);
+ let skillDir = resolveSkillDir(userDataDir, botId, slug);
+ let filePath = await readSkillFilePath(skillDir);
+ let enabled = true;
+ if (!filePath) { enabled = false; skillDir = resolveSkillDir(userDataDir, botId, slug, false); filePath = await readSkillFilePath(skillDir); }
if (!filePath) return null;
const parsed = parseBotSkillFile(await readCompatibleBotSkillSource(filePath, slug));
return {
@@ -347,6 +353,7 @@ export async function readBotSkill(
body: parsed.body,
dirPath: skillDir,
filePath,
+ ...(enabled ? {} : { enabled: false }),
};
}
@@ -413,14 +420,6 @@ export async function seedBotSkillIfMissing(
const existing = await readBotSkill(userDataDir, botId, normalized.slug);
if (existing) return { record: existing, created: false };
- const skills = await listBotSkills(userDataDir, botId);
- if (skills.length >= BOT_SKILL_MAX_COUNT) {
- throw new BotSkillStoreError(
- 'SKILL_LIMIT_REACHED',
- `this Bot already has ${BOT_SKILL_MAX_COUNT} skills; delete one before adding another`,
- );
- }
-
await ensureLayout(userDataDir, botId);
const skillDir = resolveSkillDir(userDataDir, botId, normalized.slug);
await fs.mkdir(skillDir, { recursive: true });
@@ -460,16 +459,10 @@ export async function saveBotSkill(
input: BotSkillWriteInput,
): Promise<{ record: BotSkillRecord; created: boolean }> {
const { name, description, body, slug, updatedAt } = normalizeBotSkillWriteInput(input);
- const existing = await listBotSkills(userDataDir, botId);
- const created = !existing.some((item) => item.slug === slug);
- if (created && existing.length >= BOT_SKILL_MAX_COUNT) {
- throw new BotSkillStoreError(
- 'SKILL_LIMIT_REACHED',
- `this Bot already has ${BOT_SKILL_MAX_COUNT} skills; delete one before adding another`,
- );
- }
+ const previous = await readBotSkill(userDataDir, botId, slug);
+ const created = !previous;
await ensureLayout(userDataDir, botId);
- const skillDir = resolveSkillDir(userDataDir, botId, slug);
+ const skillDir = resolveSkillDir(userDataDir, botId, slug, previous?.enabled !== false);
await fs.mkdir(skillDir, { recursive: true });
const filePath = path.join(skillDir, 'SKILL.md');
// 只写 SKILL.md,不去删同目录的 skill.md:macOS / Windows 的文件系统大小写不敏感,
@@ -480,7 +473,7 @@ export async function saveBotSkill(
'utf8',
);
return {
- record: { slug, name, description, updatedAt, body, dirPath: skillDir, filePath },
+ record: { slug, name, description, updatedAt, body, dirPath: skillDir, filePath, ...(previous?.enabled === false ? { enabled: false } : {}) },
created,
};
}
@@ -491,7 +484,7 @@ export function validateBotSkillFiles(slug: string,
if (!normalizeBotSkillSlug(slug) || normalizeBotSkillSlug(slug) !== slug)
throw new BotSkillStoreError('INVALID_ARGS', 'Invalid imported skill');
const entrypoint = files.find(file => file.name === 'SKILL.md');
- if (!entrypoint || entrypoint.bytes.length > BOT_SKILL_MAX_BODY_BYTES)
+ if (!entrypoint || !entrypoint.bytes.length)
throw new BotSkillStoreError('SKILL_BODY_TOO_LARGE', 'Invalid skill entrypoint');
for (const file of files) {
if (file.name.includes('\\') || file.name.split('/').some(part => !part || part === '.' || part === '..') || path.isAbsolute(file.name))
@@ -501,15 +494,12 @@ export function validateBotSkillFiles(slug: string,
/** Import a selected real skill with its scripts/templates; keep the native SKILL.md bytes. */
export async function importBotSkillFiles(userDataDir: string, botId: string, slug: string,
- files: readonly { name: string; bytes: Buffer; executable: boolean }[], assertOwner: () => void): Promise<void> {
+ files: readonly { name: string; bytes: Buffer; executable: boolean }[], assertOwner: () => void, enabled = true): Promise<void> {
validateBotSkillFiles(slug, files);
- const existing = await listBotSkills(userDataDir, botId);
- assertOwner();
- if (!existing.some(skill => skill.slug === slug) && existing.length >= BOT_SKILL_MAX_COUNT)
- throw new BotSkillStoreError('SKILL_LIMIT_REACHED', 'Too many selected skills');
await ensureLayout(userDataDir, botId);
assertOwner();
- const target = resolveSkillDir(userDataDir, botId, slug);
+ const target = resolveSkillDir(userDataDir, botId, slug, enabled);
+ await fs.mkdir(path.dirname(target), { recursive: true });
const temporary = path.join(botSkillRootDir(userDataDir, botId), `.import-skill-${randomUUID()}`);
await fs.mkdir(temporary, { mode: 0o700 });
try {
@@ -545,12 +535,13 @@ export async function deleteBotSkill(
botId: string,
slug: string,
): Promise<boolean> {
- const skillDir = resolveSkillDir(userDataDir, botId, slug);
- try {
- if (!(await fs.stat(skillDir)).isDirectory()) return false;
- } catch {
- return false;
+ let deleted = false;
+ for (const enabled of [true, false]) {
+ const skillDir = resolveSkillDir(userDataDir, botId, slug, enabled);
+ try { if (!(await fs.stat(skillDir)).isDirectory()) continue; }
+ catch { continue; }
+ await fs.rm(skillDir, { recursive: true, force: true });
+ deleted = true;
}
- await fs.rm(skillDir, { recursive: true, force: true });
- return true;
+ return deleted;
}
diff --git a/apps/desktop/src/renderer/features/bots/BotImportForm.tsx b/apps/desktop/src/renderer/features/bots/BotImportForm.tsx
index 9e3d443529..93f3a22cb4 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 { areCompanionImportEntriesSelected, toggleCompanionImportEntries, companionImportIssueKey, companionImportCategories, type CompanionImportApi, type CompanionImportPreview, type CompanionImportResult, type CompanionImportSelection, type CompanionImportSource } from '@cindy/maker-shared/companion-import';
+import { 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';
@@ -20,6 +20,9 @@ export function BotImportForm({ api = window.electronAPI.companionImport, onBack
const [name, setName] = useState('');
const [portrait, setPortrait] = useState<string>();
const [initialPortrait] = useState(() => Math.floor(Math.random() * BOT_PORTRAIT_COUNT));
+ const [category, setCategory] = useState<CompanionImportCategory>();
+ const [query, setQuery] = useState('');
+ const [page, setPage] = useState(0);
const [takeover, setTakeover] = useState(true);
const [busy, setBusy] = useState(false);
const [error, setError] = useState(false);
@@ -58,7 +61,7 @@ export function BotImportForm({ api = window.electronAPI.companionImport, onBack
});
const submit = () => act(async () => {
if (!preview || !portrait) return;
- intent.current ??= { requestId: crypto.randomUUID(), previewId: preview.id, name: name.trim(), avatarImageBase64: portrait.split(',')[1], entryIds: selected, takeover };
+ intent.current ??= { requestId: crypto.randomUUID(), previewId: preview.id, name: name.trim(), avatarImageBase64: portrait.split(',')[1], ...compactCompanionImportSelection(preview, selected), takeover, deferSetup: true };
// A lost acknowledgement is reconciled before retrying the same host operation.
let next = await api.status(intent.current.requestId);
if (!next || next.status === 'needs-attention') next = await api.start(intent.current);
@@ -71,44 +74,76 @@ export function BotImportForm({ api = window.electronAPI.companionImport, onBack
if (alive.current && next) setResult(next);
});
const toggle = (ids: string[], value: boolean) => setSelected(current => toggleCompanionImportEntries(preview?.entries ?? [], current, ids, value));
+ const selectedSet = new Set(selected);
const locked = busy || !!intent.current;
- return <div className="space-y-5">
- <p className="text-13 text-[var(--text-secondary)]">{tr('description')}</p>
- {!preview ? <div className="space-y-2">
+ const saved = !!result?.saved || result?.status === 'complete';
+ 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()));
+ const openCategory = (next: CompanionImportCategory) => { setCategory(next); setQuery(''); setPage(0); };
+ const checkbox = (ids: string[], checked: boolean, label: string, partial = false) => <input type="checkbox" aria-label={label}
+ disabled={locked} checked={checked} ref={node => { if (node) node.indeterminate = partial; }} onChange={event => toggle(ids, event.target.checked)}
+ className="h-4 w-4 shrink-0 accent-[var(--text-primary)]" />;
+ 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>
+ <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>;
+ })}
+ </div>
+ </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>
+ </div> : !preview ? <div className="space-y-2">
{sources?.map(source => <Button key={source.id} variant="secondary" size="lg" className="w-full justify-between" disabled={busy} onClick={() => void choose(source)}>{source.name}<span>{source.kind === 'hermes' ? 'Hermes' : 'OpenClaw'}</span></Button>)}
+ {error && !sources ? <Button variant="secondary" disabled={busy} onClick={() => void act(async () => { const value = await api.sources(); if (alive.current) setSources(value); })}>{tr('retry')}</Button> : null}
{sources?.length === 0 ? <p className="text-13 text-[var(--text-secondary)]">{tr('empty')}</p> : null}
- </div> : <>
+ </div> : category ? <section className="space-y-3">
+ <div className="flex items-center justify-between gap-3"><h3 className="text-16 font-medium">{tr(category)}</h3>
+ <label className="flex items-center gap-2 text-13">{checkbox(categoryEntries.map(entry => entry.id), areCompanionImportEntriesSelected(categoryEntries, selected), tr('selectAll'))}{tr('selectAll')}</label></div>
+ <input type="search" aria-label={tr('search')} placeholder={tr('search')} value={query} onChange={event => { setQuery(event.target.value); setPage(0); }}
+ className="h-9 w-full rounded-full border border-[var(--border-default)] bg-[var(--confirm-bg)] px-3 text-14 text-[var(--text-primary)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]" />
+ <div className="divide-y divide-[var(--border-default)]">
+ {filtered.slice(page * 20, (page + 1) * 20).map(entry => <label key={entry.id} className="flex min-h-11 cursor-pointer items-start gap-3 py-3">
+ <span className="flex h-5 shrink-0 items-center">{checkbox([entry.id], selectedSet.has(entry.id), entry.name)}</span>
+ <span className="min-w-0 flex-1 break-words text-14">{entry.name}{entry.description ? <span className="mt-1 line-clamp-2 block text-13 text-[var(--text-secondary)]">{entry.description}</span> : null}</span>
+ {entry.enabled === false ? <span className="shrink-0 text-12 text-[var(--text-secondary)]">{tr('paused')}</span> : null}
+ </label>)}
+ </div>
+ {filtered.length > 20 ? <div className="flex items-center justify-between gap-3"><Button variant="secondary" disabled={page === 0} onClick={() => setPage(page - 1)}>{tr('previous')}</Button><span className="text-13 text-[var(--text-secondary)]">{page + 1} / {Math.ceil(filtered.length / 20)}</span><Button variant="secondary" disabled={(page + 1) * 20 >= filtered.length} onClick={() => setPage(page + 1)}>{tr('next')}</Button></div> : null}
+ </section> : <>
<div className="flex items-center gap-5">
<BotPortraitPicker value={portrait} onChange={setPortrait} disabled={locked} />
<label className="min-w-0 flex-1 text-13 text-[var(--text-secondary)]">{t('bots.creationName')}
<input autoFocus maxLength={200} value={name} disabled={locked} onChange={event => setName(event.target.value)} className="mt-2 h-11 w-full rounded-full border border-[var(--border-default)] bg-[var(--confirm-bg)] px-3 text-16 text-[var(--text-primary)] outline-none focus-visible:ring-2 focus-visible:ring-[var(--focus-ring)]" />
</label>
</div>
- <fieldset disabled={locked} className="divide-y divide-[var(--border-default)] rounded-xl border border-[var(--border-default)]">
- {companionImportCategories.map(category => {
- const entries = preview.entries.filter(item => item.category === category);
+ <div className="divide-y divide-[var(--border-default)]">
+ {companionImportCategories.map(group => {
+ const entries = preview.entries.filter(item => item.category === group);
if (!entries.length) return null;
- const count = entries.filter(item => selected.includes(item.id)).length;
+ const count = entries.filter(item => selectedSet.has(item.id)).length;
const allSelected = areCompanionImportEntriesSelected(entries, selected);
- return <div key={category} className="px-4 py-3">
- <div className="flex min-h-9 items-center gap-3">
- <input type="checkbox" aria-label={tr(category)} checked={allSelected} ref={node => { if (node) node.indeterminate = count > 0 && !allSelected; }} onChange={event => toggle(entries.map(item => item.id), event.target.checked)} className="h-4 w-4 accent-[var(--text-primary)]" />
- <details className="min-w-0 flex-1" open={category === 'automations'}><summary className="cursor-pointer py-2 text-14 font-medium">{tr(category)} <span className="font-normal text-[var(--text-secondary)]">{count} / {entries.length}</span></summary>
- <div className="max-h-64 overflow-y-auto">
- {entries.map(entry => <label key={entry.id} className="flex min-h-11 cursor-pointer items-start gap-3 py-2 text-13"><input type="checkbox" className="mt-1 h-4 w-4 shrink-0 accent-[var(--text-primary)]" checked={selected.includes(entry.id)} onChange={event => toggle([entry.id], event.target.checked)} /><span className="min-w-0 break-words">{entry.name}{entry.description ? <span className="mt-1 block text-[var(--text-secondary)]">{entry.description}</span> : null}{entry.enabled === false ? <span className="block text-[var(--text-secondary)]">{tr('paused')}</span> : null}{entry.issues?.length ? <span className="block text-[var(--text-secondary)]">{tr(companionImportIssueKey(entry.issues[0]))}</span> : null}</span></label>)}
- </div>
- </details>
- </div>
+ return <div key={group} className="flex min-h-12 items-center gap-3 py-1">
+ {checkbox(entries.map(item => item.id), allSelected, tr(group), count > 0 && !allSelected)}
+ <button type="button" disabled={locked} className="flex min-h-11 min-w-0 flex-1 items-center justify-between gap-3 text-left text-14" onClick={() => openCategory(group)}>
+ <span>{tr(group)}</span><span className="shrink-0 text-[var(--text-secondary)]">{count} / {entries.length} <span aria-hidden="true">›</span></span>
+ </button>
</div>;
})}
- </fieldset>
- {preview.entries.some(entry => entry.category === 'automations' && selected.includes(entry.id)) ? <label className="flex gap-3 text-13"><input type="checkbox" checked={takeover} disabled={locked} onChange={event => setTakeover(event.target.checked)} className="mt-1 h-4 w-4 accent-[var(--text-primary)]" /><span>{tr('takeover')}<span className="mt-1 block text-[var(--text-secondary)]">{tr('takeoverNote')}</span></span></label> : null}
+ </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 ? <p role="alert" className="text-13 text-[var(--text-danger)]">{duplicate ? t('bots.guided.duplicateName') : tr('error')}</p> : null}
- {result ? <div role="status" className="space-y-2 text-13"><p>{tr(result.status === 'running' ? 'running' : result.status === 'complete' ? 'complete' : 'attention')}</p>{result.checks.filter(check => check.status === 'needs-attention').map(check => <p key={check.entryId} className="text-[var(--text-secondary)]">{preview?.entries.find(entry => entry.id === check.entryId)?.name ?? tr('title')} · {tr(companionImportIssueKey(check.message))}{preview?.entries.find(entry => entry.id === check.entryId)?.category === 'automations' ? ` · ${tr('keptAtSource')}` : ''}</p>)}</div> : null}
- <div className="flex flex-wrap justify-between gap-3">
- <Button variant="secondary" size="lg" disabled={busy} onClick={onBack}>{tr('back')}</Button>
- {result && result.status !== 'running' ? <>{result.status === 'needs-attention' ? <Button variant="secondary" size="lg" disabled={busy} onClick={() => void submit()}>{t('bots.import.retry')}</Button> : null}<Button variant="cta" size="lg" disabled={!result.canonicalSessionId} onClick={() => onCreated(result.botId)}>{tr('open')}</Button></> : preview ? <Button variant="cta" size="lg" loading={busy} disabled={busy || !name.trim() || !portrait || duplicate} onClick={() => void submit()}>{tr('submit')}</Button> : null}
+ {(error || duplicate) && !saved ? <p role="alert" className="text-13 text-[var(--text-danger)]">{duplicate ? t('bots.guided.duplicateName') : tr('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}
</div>
</div>;
}
diff --git a/apps/desktop/src/renderer/features/bots/BotRosterView.tsx b/apps/desktop/src/renderer/features/bots/BotRosterView.tsx
index c00fbfd997..128ca6cbff 100644
--- a/apps/desktop/src/renderer/features/bots/BotRosterView.tsx
+++ b/apps/desktop/src/renderer/features/bots/BotRosterView.tsx
@@ -63,7 +63,7 @@ export function BotRosterView({ onCreated, onClose, restoreFocus, inline = false
const title = t(importing ? 'bots.import.title' : 'bots.guided.title');
const content = (
<>
- <div className="mb-8 flex items-center justify-between gap-4">
+ <div className="mb-8 flex shrink-0 items-center justify-between gap-4">
{inline ? (
<h1 className="text-20 font-medium">{title}</h1>
) : (
@@ -115,13 +115,13 @@ export function BotRosterView({ onCreated, onClose, restoreFocus, inline = false
);
if (inline)
return (
- <main className="flex h-full items-center justify-center bg-[var(--surface)] px-6 text-[var(--text-primary)]"><div className="w-full max-w-lg">{content}</div></main>
+ <main className="flex h-full items-center justify-center bg-[var(--surface)] px-6 text-[var(--text-primary)]"><div className={importing ? "flex max-h-[90vh] w-full max-w-lg flex-col" : "w-full max-w-lg"}>{content}</div></main>
);
return (
<Dialog.Root open onOpenChange={open => { if (!open && !creating) close(); }}><Dialog.Portal>
<Dialog.Overlay className="fixed inset-0 z-50 bg-[var(--overlay-modal)]" />
<Dialog.Content aria-describedby={undefined} onPointerDownOutside={(event) => event.preventDefault()} onCloseAutoFocus={event => { if (restoreFocus) { event.preventDefault(); restoreFocus(); } }}
- className="fixed left-1/2 top-1/2 z-50 max-h-[90vh] w-[calc(100vw-32px)] max-w-[520px] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-xl border border-[var(--border-default)] bg-[var(--surface)] p-6 text-[var(--text-primary)] outline-none sm:p-8">
+ className={`fixed left-1/2 top-1/2 z-50 max-h-[90vh] w-[calc(100vw-32px)] max-w-[520px] -translate-x-1/2 -translate-y-1/2 ${importing ? 'flex flex-col overflow-hidden' : 'overflow-y-auto'} rounded-xl border border-[var(--border-default)] bg-[var(--surface)] p-6 text-[var(--text-primary)] outline-none sm:p-8`}>
{content}
</Dialog.Content>
</Dialog.Portal></Dialog.Root>
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 dc2ad547e1..4624ea1132 100644
--- a/apps/desktop/src/renderer/features/bots/__tests__/botImport.test.tsx
+++ b/apps/desktop/src/renderer/features/bots/__tests__/botImport.test.tsx
@@ -73,13 +73,15 @@ it.each(['SOURCE_FILE_TOO_LARGE', 'SOURCE_ITEM_TOO_LARGE', 'SOURCE_LINK_OUTSIDE_
start: vi.fn<CompanionImportApi['start']>().mockRejectedValueOnce(new Error(`Error invoking remote method 'companion-import': Error: [${code}] Import rejected; INVALID_SELECTION PREVIEW_EXPIRED`)).mockImplementation(async input => ({ requestId: input.requestId, botId: 'bot', status: 'complete', checks: [] })) };
render(<BotImportForm api={api} onCreated={() => {}} onBack={() => {}} onBusy={() => {}} />);
fireEvent.click(await screen.findByRole('button', { name: /Ada.*Hermes/ }));
- fireEvent.click(await screen.findByText('bots.import.skills', { selector: 'summary' }));
+ fireEvent.click(await screen.findByRole('button', { name: /bots.import.skills/ }));
fireEvent.click(screen.getByLabelText('Optional skill'));
+ fireEvent.click(screen.getByRole('button', { name: 'bots.import.back' }));
fireEvent.click(screen.getByRole('button', { name: 'bots.import.submit' }));
await screen.findByRole('alert');
expect((screen.getByRole('textbox') as HTMLInputElement).disabled).toBe(['INTERNAL', 'IMPORT_FAILED'].includes(code));
- expect((screen.getByLabelText('Optional skill').closest('fieldset') as HTMLFieldSetElement).disabled).toBe(['INTERNAL', 'IMPORT_FAILED'].includes(code));
- if (!['INTERNAL', 'IMPORT_FAILED'].includes(code)) fireEvent.click(screen.getByLabelText('Optional skill'));
+ expect((screen.getByRole('checkbox', { name: 'bots.import.skills' }) as HTMLInputElement).disabled).toBe(['INTERNAL', 'IMPORT_FAILED'].includes(code));
+ if (!['INTERNAL', 'IMPORT_FAILED'].includes(code)) fireEvent.click(screen.getByRole('checkbox', { name: 'bots.import.skills' }));
+ fireEvent.click(screen.getByRole('button', { name: 'bots.import.back' }));
fireEvent.click(screen.getByRole('button', { name: 'bots.import.submit' }));
await screen.findByRole('button', { name: 'bots.import.open' });
const [first, second] = vi.mocked(api.start).mock.calls.map(call => call[0]);
@@ -135,13 +137,37 @@ it('uses the existing credential checkboxes as alternatives without selecting an
render(<BotImportForm api={api} onCreated={() => {}} onBack={() => {}} onBusy={() => {}} />);
fireEvent.click(await screen.findByRole('button', { name: /Ada.*Hermes/ }));
await screen.findByRole('button', { name: 'existing-portrait-picker' });
- fireEvent.click(screen.getByText('bots.import.connections', { selector: 'summary' }));
- fireEvent.click(screen.getByRole('checkbox', { name: 'bots.import.connections' }));
+ fireEvent.click(screen.getByRole('button', { name: /bots.import.connections/ }));
+ fireEvent.click(screen.getByRole('checkbox', { name: 'bots.import.selectAll' }));
expect((screen.getByLabelText('Work') as HTMLInputElement).checked).toBe(false);
fireEvent.click(screen.getByLabelText('Work'));
fireEvent.click(screen.getByLabelText('Personal'));
expect((screen.getByLabelText('Work') as HTMLInputElement).checked).toBe(false);
expect((screen.getByLabelText('Personal') as HTMLInputElement).checked).toBe(true);
+ fireEvent.click(screen.getByRole('button', { name: 'bots.import.back' }));
fireEvent.click(screen.getByRole('button', { name: 'bots.import.submit' }));
await waitFor(() => expect(api.start).toHaveBeenCalledWith(expect.objectContaining({ entryIds: ['personal'] })));
});
+
+it('shows 142 selected skills in a flat searchable paginated list and opens chat after deferred setup', async () => {
+ const entries = Array.from({ length: 142 }, (_, i) => ({ id: `skill-${i}`, category: 'skills' as const, name: `Skill ${i}`, 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: async input => ({ requestId: input.requestId, botId: 'bot', canonicalSessionId: 'chat', status: 'needs-attention', saved: true, savedEntryIds: entries.map(entry => entry.id), checks: [{ entryId: 'skill-0', status: 'needs-attention', message: 'NATIVE_AUTH_REFRESH_REQUIRED' }] }) };
+ const open = vi.fn();
+ const { container } = render(<BotImportForm api={api} onCreated={open} onBack={() => {}} onBusy={() => {}} />);
+ fireEvent.click(await screen.findByRole('button', { name: /Ada.*Hermes/ }));
+ fireEvent.click(await screen.findByRole('button', { name: /bots.import.skills/ }));
+ expect(screen.getAllByRole('checkbox')).toHaveLength(21);
+ expect(container.querySelector('details')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'bots.import.next' }));
+ expect(screen.getByLabelText('Skill 20')).toBeDefined();
+ fireEvent.change(screen.getByRole('searchbox'), { target: { value: 'Skill 141' } });
+ expect((screen.getByLabelText('Skill 141') as HTMLInputElement).checked).toBe(true);
+ fireEvent.click(screen.getByRole('button', { name: 'bots.import.back' }));
+ fireEvent.click(screen.getByRole('button', { name: 'bots.import.submit' }));
+ fireEvent.click(await screen.findByRole('button', { name: 'bots.import.open' }));
+ expect(open).toHaveBeenCalledWith('bot');
+ expect(screen.queryByRole('alert')).toBeNull();
+ expect(screen.queryByRole('button', { name: 'bots.import.retry' })).toBeNull();
+});
diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.json
index ac1035e8f1..84ec7940b6 100644
--- a/apps/desktop/src/renderer/i18n/locales/en/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json
@@ -8260,13 +8260,13 @@
"automations": "Automations",
"paused": "Keep paused",
"itemAttention": "Needs attention",
- "takeover": "Take over automations after verification",
+ "takeover": "Check and take over automations after import",
"takeoverNote": "Source tasks pause only after their data connections are verified. Unselected dependencies keep the source task running.",
"submit": "Import",
"back": "Back",
"open": "Open teammate",
"running": "Importing and checking connections…",
- "complete": "Import complete",
+ "complete": "Import saved",
"attention": "Some items need attention. See the details below.",
"error": "Import could not finish. Retry with the same selection.",
"keptAtSource": "Takeover is not complete",
@@ -8281,7 +8281,13 @@
"credentialFailed": "Credentials could not be saved securely.",
"scriptMissing": "A required script is missing.",
"sourceCommand": "The original Agent command is unavailable.",
- "readFailed": "The required data query has not been verified."
+ "readFailed": "The required data query has not been verified.",
+ "search": "Search",
+ "selectAll": "Select all",
+ "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."
}
},
"common": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.json
index 3e2e6a9a54..f664e46f96 100644
--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json
@@ -8258,13 +8258,13 @@
"automations": "自動化",
"paused": "停止状態を維持",
"itemAttention": "確認が必要",
- "takeover": "確認後に自動化を引き継ぐ",
+ "takeover": "インポート後に自動化を確認して引き継ぐ",
"takeoverNote": "データ接続を確認してから元のタスクを停止します。必要な項目を除外した場合、元のタスクは実行を続けます。",
"submit": "インポート",
"back": "戻る",
"open": "仲間を開く",
"running": "インポートと接続確認中…",
- "complete": "インポート完了",
+ "complete": "インポートを保存しました",
"attention": "確認が必要な項目があります。詳細をご確認ください。",
"error": "インポートできませんでした。同じ選択で再試行できます。",
"keptAtSource": "引き継ぎは未完了です",
@@ -8279,7 +8279,13 @@
"credentialFailed": "認証情報を安全に保存できませんでした。",
"scriptMissing": "必要なスクリプトがありません。",
"sourceCommand": "元の Agent の制御コマンドが見つかりません。",
- "readFailed": "このタスクに必要なデータ取得を確認できていません。"
+ "readFailed": "このタスクに必要なデータ取得を確認できていません。",
+ "search": "検索",
+ "selectAll": "すべて選択",
+ "previous": "前のページ",
+ "next": "次のページ",
+ "chatSetup": "取り込める情報を保存しました。すぐに会話を始められます。ログインや確認が必要な項目は、都合のよいときに進めましょう。引き継ぎが完了するまで、元の自動化の状態は変わりません。",
+ "chatReady": "情報をインポートしました。会話を始められます。"
}
},
"common": {
diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.json
index 0f5d0990d8..828d79c0ca 100644
--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json
@@ -8258,13 +8258,13 @@
"automations": "자동화",
"paused": "일시 중지 유지",
"itemAttention": "확인 필요",
- "takeover": "확인 후 자동화 인계",
+ "takeover": "가져온 후 자동화 확인 및 인계",
"takeoverNote": "데이터 연결 확인 후 원본 작업을 중지합니다. 필요한 항목을 제외하면 원본 작업은 계속 실행됩니다.",
"submit": "가져오기",
"back": "이전",
"open": "동료 열기",
"running": "가져오기 및 연결 확인 중…",
- "complete": "가져오기 완료",
+ "complete": "가져온 내용을 저장했습니다",
"attention": "확인이 필요한 항목이 있습니다. 아래 내용을 확인하세요.",
"error": "가져오기를 완료하지 못했습니다. 같은 선택으로 재시도하세요.",
"keptAtSource": "인계가 완료되지 않았습니다",
@@ -8279,7 +8279,13 @@
"credentialFailed": "인증 정보를 안전하게 저장하지 못했습니다.",
"scriptMissing": "필요한 스크립트가 없습니다.",
"sourceCommand": "기존 Agent 제어 명령을 찾지 못했습니다.",
- "readFailed": "작업에 필요한 실제 데이터 조회를 확인하지 못했습니다."
+ "readFailed": "작업에 필요한 실제 데이터 조회를 확인하지 못했습니다.",
+ "search": "검색",
+ "selectAll": "모두 선택",
+ "previous": "이전 페이지",
+ "next": "다음 페이지",
+ "chatSetup": "가져올 수 있는 자료를 저장했어요. 바로 대화를 시작할 수 있어요. 로그인이나 확인이 필요한 항목은 편할 때 마무리하면 돼요. 인계가 끝날 때까지 기존 자동화 상태는 그대로 유지돼요.",
+ "chatReady": "정보를 가져왔습니다. 이제 대화를 시작할 수 있어요."
}
},
"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 854fec617d..b02efa72b3 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json
@@ -8258,13 +8258,13 @@
"automations": "自动化",
"paused": "导入后仍停用",
"itemAttention": "需要处理",
- "takeover": "检查通过后,由伙伴接管自动化",
+ "takeover": "导入后检查并接管自动化",
"takeoverNote": "数据连接验证通过后才暂停原任务。取消所需依赖时,原任务继续运行。",
"submit": "导入",
"back": "上一步",
"open": "打开伙伴",
"running": "正在导入并检查连接…",
- "complete": "导入完成",
+ "complete": "导入已保存",
"attention": "部分内容需要处理,详见下方。",
"error": "未能完成导入,可按原选择重试。",
"keptAtSource": "尚未完成接管",
@@ -8279,7 +8279,13 @@
"credentialFailed": "凭证未能安全保存。",
"scriptMissing": "缺少这项任务所需的脚本。",
"sourceCommand": "找不到原 Agent 的控制命令。",
- "readFailed": "尚未验证这项任务实际需要的数据查询。"
+ "readFailed": "尚未验证这项任务实际需要的数据查询。",
+ "search": "搜索",
+ "selectAll": "全选",
+ "previous": "上一页",
+ "next": "下一页",
+ "chatSetup": "已保存可导入的资料,可以开始交流了。部分内容还需要登录或检查,你方便时我们再继续。接管前,原来的自动化保持原状。",
+ "chatReady": "资料已经导入,可以开始交流了。"
}
},
"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 2e72b8d362..3373b7887c 100644
--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json
@@ -8258,13 +8258,13 @@
"automations": "自動化",
"paused": "匯入後仍停用",
"itemAttention": "需要處理",
- "takeover": "檢查通過後,由夥伴接管自動化",
+ "takeover": "匯入後檢查並接管自動化",
"takeoverNote": "資料連線驗證通過後才暫停原任務。取消所需依賴時,原任務繼續執行。",
"submit": "匯入",
"back": "上一步",
"open": "開啟夥伴",
"running": "正在匯入並檢查連線…",
- "complete": "匯入完成",
+ "complete": "匯入已儲存",
"attention": "部分內容需要處理,詳見下方。",
"error": "未能完成匯入,可按原選擇重試。",
"keptAtSource": "尚未完成接管",
@@ -8279,7 +8279,13 @@
"credentialFailed": "憑證未能安全儲存。",
"scriptMissing": "缺少這項任務所需的指令碼。",
"sourceCommand": "找不到原 Agent 的控制命令。",
- "readFailed": "尚未驗證這項任務實際需要的資料查詢。"
+ "readFailed": "尚未驗證這項任務實際需要的資料查詢。",
+ "search": "搜尋",
+ "selectAll": "全選",
+ "previous": "上一頁",
+ "next": "下一頁",
+ "chatSetup": "已儲存可匯入的資料,可以開始交流了。部分內容還需要登入或檢查,你方便時我們再繼續。接管前,原來的自動化保持原狀。",
+ "chatReady": "資料已經匯入,可以開始交流了。"
}
},
"common": {
diff --git a/apps/desktop/src/shared/botSkill.ts b/apps/desktop/src/shared/botSkill.ts
index ad68a7b425..9f18db5565 100644
--- a/apps/desktop/src/shared/botSkill.ts
+++ b/apps/desktop/src/shared/botSkill.ts
@@ -16,6 +16,8 @@ export interface BotSkillSummary {
description: string;
/** ISO 串;解析不出来时为空串,由展示方降级成不显示时间。 */
updatedAt: string;
+ /** A retained source skill can be stored without being mounted. */
+ enabled?: boolean;
}
/** 展开某条技能时额外带上正文。 */
diff --git a/apps/mobile/src/__tests__/CompanionImportSheet.test.tsx b/apps/mobile/src/__tests__/CompanionImportSheet.test.tsx
index 1191d3d992..b110747ff8 100644
--- a/apps/mobile/src/__tests__/CompanionImportSheet.test.tsx
+++ b/apps/mobile/src/__tests__/CompanionImportSheet.test.tsx
@@ -4,7 +4,7 @@ import { createRoot, type Root } from 'react-dom/client';
import { afterEach, expect, it, vi } from 'vitest';
const h = vi.hoisted(() => ({ invoke: vi.fn(), submit: vi.fn(), openLink: vi.fn(), created: vi.fn(), uuid: vi.fn(() => 'fixture-request-12345') }));
vi.mock('react-native', () => ({
- StyleSheet: { create: (v: unknown) => v }, View: 'div', ScrollView: 'div',
+ StyleSheet: { create: (v: unknown) => v }, View: ({ children }: any) => createElement('div', {}, children), ScrollView: ({ children }: any) => createElement('div', {}, children),
Pressable: ({ onPress, children }: any) => createElement('button', { onClick: onPress }, children),
Switch: ({ accessibilityLabel, value, disabled, onValueChange }: any) => createElement('input', { type: 'checkbox', 'aria-label': accessibilityLabel, checked: value, disabled, onChange: (e: any) => onValueChange(e.target.checked) }),
}));
@@ -12,7 +12,7 @@ vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => k
vi.mock('expo-crypto', () => ({ randomUUID: () => h.uuid() }));
vi.mock('@/device-link/DeviceLinkContext', () => ({ useDeviceLink: () => ({ invoke: h.invoke, openLink: h.openLink }) }));
vi.mock('@/device-link/remoteResources', () => ({ invokeRemoteResourceAction: (...args: unknown[]) => h.submit(...args) }));
-vi.mock('@/components/AppText', () => ({ Text: 'span', TextInput: ({ value, editable, onChangeText }: any) => createElement('input', { value, disabled: !editable, onInput: (e: any) => onChangeText(e.target.value), onChange() {} }) }));
+vi.mock('@/components/AppText', () => ({ Text: ({ children }: any) => createElement('span', {}, children), TextInput: ({ value, editable, onChangeText }: any) => createElement('input', { value, disabled: !editable, onInput: (e: any) => onChangeText(e.target.value), onChange() {} }) }));
vi.mock('@/components/MobilePrimitives', () => ({ MainWindowActionButton: ({ action }: any) => createElement('button', { onClick: action.onPress, disabled: action.disabled }, action.label) }));
vi.mock('@/session/CompanionSheet', () => ({ CompanionSheet: ({ children }: any) => children }));
vi.mock('@/session/CompanionPortraitPicker', () => ({ randomCompanionPortrait: async () => 'original-portrait', CompanionPortraitPicker: ({ onChange }: any) => createElement('button', { onClick: () => onChange('chosen-existing-portrait') }, 'existing portrait picker') }));
@@ -63,6 +63,7 @@ it.each(['IMPORT_NAME_EXISTS', 'INVALID_SELECTION', 'PROFILE_TEXT_TOO_LARGE', 'S
await act(async () => (container.querySelector('[aria-label="Work"]') as HTMLInputElement).click());
await act(async () => (container.querySelector('[aria-label="Personal"]') as HTMLInputElement).click());
expect((container.querySelector('[aria-label="Work"]') as HTMLInputElement).checked).toBe(false);
+ await click('devices.companionImport.back');
await click('devices.companionImport.submit');
const input = container.querySelector('input:not([type="checkbox"])') as HTMLInputElement;
expect(input.disabled).toBe(code === 'INTERNAL');
@@ -70,7 +71,7 @@ it.each(['IMPORT_NAME_EXISTS', 'INVALID_SELECTION', 'PROFILE_TEXT_TOO_LARGE', 'S
await act(async () => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, 'Corrected name');
input.dispatchEvent(new Event('input', { bubbles: true }));
- (container.querySelector('[aria-label="Personal"]') as HTMLInputElement).click();
+ (container.querySelector('[aria-label="devices.companionImport.connections"]') as HTMLInputElement).click();
});
}
await click('devices.companionImport.submit');
@@ -158,3 +159,19 @@ it('rejects an oversized action before freezing the selection and can submit aft
const { parseRemoteActionInvokeRequest, REMOTE_RESOURCE_PROTOCOL_VERSION } = await import('@cindy/device-link');
expect(parseRemoteActionInvokeRequest({ ...request, client: { protocolVersion: REMOTE_RESOURCE_PROTOCOL_VERSION, primitives: [] } })).not.toBeNull();
});
+
+it('submits all 10,000 selected entries compactly without raising the transport budget', async () => {
+ const entries = Array.from({ length: 10_000 }, (_, index) => ({ id: `entry-${index}`, name: `Memory ${index}`, category: 'memory', selected: true }));
+ 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', selectionRanges: true, name: 'Ada', source: { id: 'source', name: 'Ada', kind: 'hermes' }, entries } }
+ : { result: null } }] };
+ });
+ 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 () => [...container.querySelectorAll('button')].find(button => button.textContent === text)!.click()); };
+ await click('Ada · Hermes'); await click('devices.companionImport.submit');
+ expect(h.submit.mock.calls[0]?.[2].input).toMatchObject({ entryIds: [], entryRanges: [[0, 9999]], deferSetup: true });
+});
diff --git a/apps/mobile/src/i18n/locales/en/devices.json b/apps/mobile/src/i18n/locales/en/devices.json
index fc27c6ac18..fa50e5cf1b 100644
--- a/apps/mobile/src/i18n/locales/en/devices.json
+++ b/apps/mobile/src/i18n/locales/en/devices.json
@@ -704,13 +704,13 @@
"automations": "Automations",
"paused": "Keep paused",
"itemAttention": "Needs attention",
- "takeover": "Take over automations after verification",
+ "takeover": "Check and take over automations after import",
"takeoverNote": "Source tasks pause only after their data connections are verified. Unselected dependencies keep the source task running.",
"submit": "Import",
"back": "Back",
"open": "Open teammate",
"running": "Importing and checking connections…",
- "complete": "Import complete",
+ "complete": "Import saved",
"attention": "Some items need attention. See the details below.",
"error": "Import could not finish. Retry with the same selection.",
"keptAtSource": "Takeover is not complete",
@@ -725,6 +725,12 @@
"credentialFailed": "Credentials could not be saved securely.",
"scriptMissing": "A required script is missing.",
"sourceCommand": "The original Agent command is unavailable.",
- "readFailed": "The required data query has not been verified."
+ "readFailed": "The required data query has not been verified.",
+ "search": "Search",
+ "selectAll": "Select all",
+ "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."
}
}
diff --git a/apps/mobile/src/i18n/locales/ja/devices.json b/apps/mobile/src/i18n/locales/ja/devices.json
index 8fd15c1f2d..8b10de27a5 100644
--- a/apps/mobile/src/i18n/locales/ja/devices.json
+++ b/apps/mobile/src/i18n/locales/ja/devices.json
@@ -704,13 +704,13 @@
"automations": "自動化",
"paused": "停止状態を維持",
"itemAttention": "確認が必要",
- "takeover": "確認後に自動化を引き継ぐ",
+ "takeover": "インポート後に自動化を確認して引き継ぐ",
"takeoverNote": "データ接続を確認してから元のタスクを停止します。必要な項目を除外した場合、元のタスクは実行を続けます。",
"submit": "インポート",
"back": "戻る",
"open": "仲間を開く",
"running": "インポートと接続確認中…",
- "complete": "インポート完了",
+ "complete": "インポートを保存しました",
"attention": "確認が必要な項目があります。詳細をご確認ください。",
"error": "インポートできませんでした。同じ選択で再試行できます。",
"keptAtSource": "引き継ぎは未完了です",
@@ -725,6 +725,12 @@
"credentialFailed": "認証情報を安全に保存できませんでした。",
"scriptMissing": "必要なスクリプトがありません。",
"sourceCommand": "元の Agent の制御コマンドが見つかりません。",
- "readFailed": "このタスクに必要なデータ取得を確認できていません。"
+ "readFailed": "このタスクに必要なデータ取得を確認できていません。",
+ "search": "検索",
+ "selectAll": "すべて選択",
+ "previous": "前のページ",
+ "next": "次のページ",
+ "chatSetup": "取り込める情報を保存しました。すぐに会話を始められます。ログインや確認が必要な項目は、都合のよいときに進めましょう。引き継ぎが完了するまで、元の自動化の状態は変わりません。",
+ "chatReady": "情報をインポートしました。会話を始められます。"
}
}
diff --git a/apps/mobile/src/i18n/locales/ko/devices.json b/apps/mobile/src/i18n/locales/ko/devices.json
index 75563bad24..304be98ad6 100644
--- a/apps/mobile/src/i18n/locales/ko/devices.json
+++ b/apps/mobile/src/i18n/locales/ko/devices.json
@@ -704,13 +704,13 @@
"automations": "자동화",
"paused": "일시 중지 유지",
"itemAttention": "확인 필요",
- "takeover": "확인 후 자동화 인계",
+ "takeover": "가져온 후 자동화 확인 및 인계",
"takeoverNote": "데이터 연결 확인 후 원본 작업을 중지합니다. 필요한 항목을 제외하면 원본 작업은 계속 실행됩니다.",
"submit": "가져오기",
"back": "이전",
"open": "동료 열기",
"running": "가져오기 및 연결 확인 중…",
- "complete": "가져오기 완료",
+ "complete": "가져온 내용을 저장했습니다",
"attention": "확인이 필요한 항목이 있습니다. 아래 내용을 확인하세요.",
"error": "가져오기를 완료하지 못했습니다. 같은 선택으로 재시도하세요.",
"keptAtSource": "인계가 완료되지 않았습니다",
@@ -725,6 +725,12 @@
"credentialFailed": "인증 정보를 안전하게 저장하지 못했습니다.",
"scriptMissing": "필요한 스크립트가 없습니다.",
"sourceCommand": "기존 Agent 제어 명령을 찾지 못했습니다.",
- "readFailed": "작업에 필요한 실제 데이터 조회를 확인하지 못했습니다."
+ "readFailed": "작업에 필요한 실제 데이터 조회를 확인하지 못했습니다.",
+ "search": "검색",
+ "selectAll": "모두 선택",
+ "previous": "이전 페이지",
+ "next": "다음 페이지",
+ "chatSetup": "가져올 수 있는 자료를 저장했어요. 바로 대화를 시작할 수 있어요. 로그인이나 확인이 필요한 항목은 편할 때 마무리하면 돼요. 인계가 끝날 때까지 기존 자동화 상태는 그대로 유지돼요.",
+ "chatReady": "정보를 가져왔습니다. 이제 대화를 시작할 수 있어요."
}
}
diff --git a/apps/mobile/src/i18n/locales/zh-CN/devices.json b/apps/mobile/src/i18n/locales/zh-CN/devices.json
index 52133ec164..1b1e6c1188 100644
--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json
@@ -704,13 +704,13 @@
"automations": "自动化",
"paused": "导入后仍停用",
"itemAttention": "需要处理",
- "takeover": "检查通过后,由伙伴接管自动化",
+ "takeover": "导入后检查并接管自动化",
"takeoverNote": "数据连接验证通过后才暂停原任务。取消所需依赖时,原任务继续运行。",
"submit": "导入",
"back": "上一步",
"open": "打开伙伴",
"running": "正在导入并检查连接…",
- "complete": "导入完成",
+ "complete": "导入已保存",
"attention": "部分内容需要处理,详见下方。",
"error": "未能完成导入,可按原选择重试。",
"keptAtSource": "尚未完成接管",
@@ -725,6 +725,12 @@
"credentialFailed": "凭证未能安全保存。",
"scriptMissing": "缺少这项任务所需的脚本。",
"sourceCommand": "找不到原 Agent 的控制命令。",
- "readFailed": "尚未验证这项任务实际需要的数据查询。"
+ "readFailed": "尚未验证这项任务实际需要的数据查询。",
+ "search": "搜索",
+ "selectAll": "全选",
+ "previous": "上一页",
+ "next": "下一页",
+ "chatSetup": "已保存可导入的资料,可以开始交流了。部分内容还需要登录或检查,你方便时我们再继续。接管前,原来的自动化保持原状。",
+ "chatReady": "资料已经导入,可以开始交流了。"
}
}
diff --git a/apps/mobile/src/i18n/locales/zh-TW/devices.json b/apps/mobile/src/i18n/locales/zh-TW/devices.json
index 7c3504fe97..f279f61dd1 100644
--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json
+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json
@@ -704,13 +704,13 @@
"automations": "自動化",
"paused": "匯入後仍停用",
"itemAttention": "需要處理",
- "takeover": "檢查通過後,由夥伴接管自動化",
+ "takeover": "匯入後檢查並接管自動化",
"takeoverNote": "資料連線驗證通過後才暫停原任務。取消所需依賴時,原任務繼續執行。",
"submit": "匯入",
"back": "上一步",
"open": "開啟夥伴",
"running": "正在匯入並檢查連線…",
- "complete": "匯入完成",
+ "complete": "匯入已儲存",
"attention": "部分內容需要處理,詳見下方。",
"error": "未能完成匯入,可按原選擇重試。",
"keptAtSource": "尚未完成接管",
@@ -725,6 +725,12 @@
"credentialFailed": "憑證未能安全儲存。",
"scriptMissing": "缺少這項任務所需的指令碼。",
"sourceCommand": "找不到原 Agent 的控制命令。",
- "readFailed": "尚未驗證這項任務實際需要的資料查詢。"
+ "readFailed": "尚未驗證這項任務實際需要的資料查詢。",
+ "search": "搜尋",
+ "selectAll": "全選",
+ "previous": "上一頁",
+ "next": "下一頁",
+ "chatSetup": "已儲存可匯入的資料,可以開始交流了。部分內容還需要登入或檢查,你方便時我們再繼續。接管前,原來的自動化保持原狀。",
+ "chatReady": "資料已經匯入,可以開始交流了。"
}
}
diff --git a/apps/mobile/src/session/CompanionImportSheet.tsx b/apps/mobile/src/session/CompanionImportSheet.tsx
index ab10c49ad5..996c3c45c1 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 { areCompanionImportEntriesSelected, toggleCompanionImportEntries, companionImportIssueKey, companionImportCategories, remoteCompanionImportApi, type CompanionImportPreview, type CompanionImportResult, type CompanionImportSelection, type CompanionImportSource } from '@cindy/maker-shared/companion-import';
+import { 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';
@@ -26,7 +26,9 @@ export function CompanionImportSheet({ visible, onClose, onClosed, deviceId, dev
const [sources, setSources] = useState<CompanionImportSource[]>();
const [preview, setPreview] = useState<CompanionImportPreview>();
const [selected, setSelected] = useState<string[]>([]);
- const [expanded, setExpanded] = useState<string>('automations');
+ const [expanded, setExpanded] = useState<string>('');
+ const [query, setQuery] = useState('');
+ const [page, setPage] = useState(0);
const [name, setName] = useState('');
const [avatar, setAvatar] = useState('');
const [takeover, setTakeover] = useState(true);
@@ -65,7 +67,7 @@ export function CompanionImportSheet({ visible, onClose, onClosed, deviceId, dev
const submit = () => act(async () => {
if (!preview || !name.trim() || !avatar) return;
if (!intent.current) {
- const selection = { requestId: randomUUID(), previewId: preview.id, name: name.trim(), avatarImageBase64: avatar, entryIds: selected, takeover };
+ const selection = { requestId: randomUUID(), previewId: preview.id, name: name.trim(), avatarImageBase64: avatar, ...compactCompanionImportSelection(preview, selected), takeover, deferSetup: true };
// Validate the complete action with the host's wire parser before freezing
// this request. Oversized inputs must remain editable, never retry forever.
if (!parseRemoteActionInvokeRequest({
@@ -86,41 +88,56 @@ export function CompanionImportSheet({ visible, onClose, onClosed, deviceId, dev
if (alive.current && value) setResult(value);
});
const toggle = (ids: string[], checked: boolean) => setSelected(value => toggleCompanionImportEntries(preview?.entries ?? [], value, ids, checked));
+ const selectedSet = new Set(selected);
const locked = busy || !!intent.current || !online;
+ const saved = !!result?.saved || result?.status === 'complete';
+ 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}>
- <Text style={styles.note}>{tr('description')}</Text>
{!online || error ? <Text accessibilityRole="alert" style={styles.note}>{!online ? t('devices.companionProfile.offline', { deviceName }) : tr('error')}</Text> : null}
- {!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) }} />)}{sources?.length === 0 ? <Text style={styles.note}>{tr('empty')}</Text> : null}</> : <>
+ {finished && saved ? <>
+ <Text style={styles.label}>{tr('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;
+ })}
+ </> : 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}
+ {sources?.length === 0 ? <Text style={styles.note}>{tr('empty')}</Text> : null}
+ </> : expanded ? <>
+ <MainWindowActionButton action={{ label: tr('back'), onPress: () => setExpanded('') }} />
+ <View style={styles.row}><Text style={[styles.label, styles.expand]}>{tr(expanded)}</Text><Switch accessibilityLabel={tr('selectAll')} disabled={locked} value={areCompanionImportEntriesSelected(entries, selected)} onValueChange={checked => toggle(entries.map(entry => entry.id), checked)} /></View>
+ <TextInput accessibilityLabel={tr('search')} placeholder={tr('search')} value={query} onChangeText={value => { setQuery(value); setPage(0); }} style={styles.input} />
+ {filtered.slice(page * 20, (page + 1) * 20).map(entry => <View key={entry.id} style={styles.row}><View style={styles.expand}><Text style={styles.label}>{entry.name}</Text>{entry.description ? <Text numberOfLines={2} style={styles.note}>{entry.description}</Text> : null}{entry.enabled === false ? <Text style={styles.note}>{tr('paused')}</Text> : null}</View><Switch accessibilityLabel={entry.name} value={selectedSet.has(entry.id)} disabled={locked} onValueChange={value => toggle([entry.id], value)} /></View>)}
+ {filtered.length > 20 ? <View style={styles.row}><MainWindowActionButton action={{ label: tr('previous'), disabled: page === 0, onPress: () => setPage(page - 1) }} /><Text style={styles.count}>{page + 1} / {Math.ceil(filtered.length / 20)}</Text><MainWindowActionButton action={{ label: tr('next'), disabled: (page + 1) * 20 >= filtered.length, onPress: () => setPage(page + 1) }} /></View> : null}
+ </> : <>
<Text style={styles.label}>{t('devices.companionProfile.name')}</Text>
<TextInput accessibilityLabel={t('devices.companionProfile.name')} maxLength={200} value={name} onChangeText={setName} editable={!locked} style={styles.input} />
<CompanionPortraitPicker value={avatar} onChange={setAvatar} disabled={locked} />
{companionImportCategories.map(category => {
- const entries = preview.entries.filter(entry => entry.category === category);
- if (!entries.length) return null;
- const count = entries.filter(entry => selected.includes(entry.id)).length;
- const allSelected = areCompanionImportEntriesSelected(entries, selected);
- return <View key={category} style={styles.group}>
- <View style={styles.row}><Pressable accessibilityRole="button" accessibilityState={{ expanded: expanded === category }} style={styles.expand} onPress={() => setExpanded(expanded === category ? '' : category)}><Text style={styles.label}>{tr(category)}</Text><Text style={styles.count}>{count} / {entries.length}</Text></Pressable><Switch accessibilityLabel={tr(category)} value={allSelected} disabled={locked} onValueChange={value => toggle(entries.map(entry => entry.id), value)} /></View>
- {expanded === category ? entries.map(entry => <View key={entry.id} style={styles.row}><View style={styles.expand}><Text style={styles.label}>{entry.name}</Text>{entry.description ? <Text style={styles.note}>{entry.description}</Text> : null}{entry.enabled === false ? <Text style={styles.note}>{tr('paused')}</Text> : null}{entry.issues?.length ? <Text style={styles.note}>{tr(companionImportIssueKey(entry.issues[0]))}</Text> : null}</View><Switch accessibilityLabel={entry.name} value={selected.includes(entry.id)} disabled={locked} onValueChange={value => toggle([entry.id], value)} /></View>) : null}
- </View>;
+ const group = preview.entries.filter(entry => entry.category === category);
+ if (!group.length) return null;
+ const count = group.filter(entry => selectedSet.has(entry.id)).length;
+ return <View key={category} style={styles.row}><Pressable accessibilityRole="button" style={styles.expand} disabled={locked} onPress={() => { setExpanded(category); setQuery(''); setPage(0); }}><Text style={styles.label}>{tr(category)}</Text><Text style={styles.count}>{count} / {group.length}</Text></Pressable><Switch accessibilityLabel={tr(category)} value={areCompanionImportEntriesSelected(group, selected)} disabled={locked} onValueChange={value => toggle(group.map(entry => entry.id), value)} /></View>;
})}
- {preview.entries.some(entry => entry.category === 'automations' && selected.includes(entry.id)) ? <View style={styles.row}><View style={styles.expand}><Text style={styles.label}>{tr('takeover')}</Text><Text style={styles.note}>{tr('takeoverNote')}</Text></View><Switch accessibilityLabel={tr('takeover')} value={takeover} onValueChange={setTakeover} disabled={locked} /></View> : null}
+ {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}
</>}
- {result ? <><Text style={styles.note}>{tr(result.status === 'running' ? 'running' : result.status === 'complete' ? 'complete' : 'attention')}</Text>{result.checks.filter(check => check.status === 'needs-attention').map(check => <Text key={check.entryId} style={styles.note}>{preview?.entries.find(entry => entry.id === check.entryId)?.name ?? tr('title')} · {tr(companionImportIssueKey(check.message))}{preview?.entries.find(entry => entry.id === check.entryId)?.category === 'automations' ? ` · ${tr('keptAtSource')}` : ''}</Text>)}</> : null}
- {result?.status === 'needs-attention' ? <MainWindowActionButton action={{ label: tr('retry'), busy, disabled: busy || !online, onPress: () => void submit() }} /> : null}
- {result && result.status !== 'running' ? <MainWindowActionButton action={{ label: tr('open'), disabled: !result.canonicalSessionId, onPress: () => { onCreated({ collectionId: 'teammates', kind: 'bot', id: result.botId }); onClose(); } }} /> : preview ? <MainWindowActionButton action={{ label: tr('submit'), busy, disabled: busy || !online || !name.trim() || !avatar, onPress: () => void submit() }} /> : null}
+ {finished && !saved ? <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>;
}
const makeStyles = (colors: ThemeColors) => StyleSheet.create({
content: { padding: spacing.lg, gap: spacing.md },
- group: { borderColor: colors.border, borderWidth: 1, borderRadius: radius.container, paddingHorizontal: spacing.md },
row: { flexDirection: 'row', alignItems: 'center', gap: spacing.md, paddingVertical: spacing.md },
expand: { flex: 1, gap: spacing.xs, minHeight: 44, justifyContent: 'center' },
label: { fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.medium, color: colors.textPrimary },
note: { fontSize: typeScale.footnote, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular, color: colors.textSecondary },
count: { fontSize: typeScale.caption, lineHeight: lineHeight.caption, fontWeight: fontWeight.regular, color: colors.textTertiary },
- input: { minHeight: 44, borderWidth: 1, borderColor: colors.border, borderRadius: radius.container, paddingHorizontal: spacing.md, fontSize: typeScale.body, color: colors.textPrimary, backgroundColor: colors.surfaceElevated },
+ input: { minHeight: 44, borderWidth: 1, borderColor: colors.border, borderRadius: radius.container, paddingHorizontal: spacing.md, fontSize: typeScale.body, lineHeight: lineHeight.body, fontWeight: fontWeight.regular, color: colors.textPrimary, backgroundColor: colors.surfaceElevated },
});
diff --git a/docs/assets/companion-import/README.md b/docs/assets/companion-import/README.md
new file mode 100644
index 0000000000..414cac9e90
--- /dev/null
+++ b/docs/assets/companion-import/README.md
@@ -0,0 +1,15 @@
+# Companion import component evidence
+
+These images render the actual Desktop `BotImportForm`, button component and
+Cindy theme tokens with fixture data: 142 skills, 2,100 memories, 23 connections,
+15 automations and four profile documents. The host API and portrait picker use
+test stand-ins. They are not screenshots of a packaged app or a live migration.
+
+- `light-selection.png`, `dark-selection.png`: flat category summary in both themes.
+- `narrow-skills.png`: the Desktop component at 390 px, with 20-row pagination and
+ one scrolling body; this is not a native Mobile screenshot.
+- `light-saved.png`: saved content opens the companion while setup is deferred.
+
+The fixture renderer and its embedded data are not included in shipped code.
+Native iOS/Android visual checks, mixed-version device sessions and live provider
+login/authorization remain separate from this component evidence.
diff --git a/docs/assets/companion-import/dark-selection.png b/docs/assets/companion-import/dark-selection.png
new file mode 100644
index 0000000000..69a0ec0738
Binary files /dev/null and b/docs/assets/companion-import/dark-selection.png differ
diff --git a/docs/assets/companion-import/light-saved.png b/docs/assets/companion-import/light-saved.png
new file mode 100644
index 0000000000..13e437b8f9
Binary files /dev/null and b/docs/assets/companion-import/light-saved.png differ
diff --git a/docs/assets/companion-import/light-selection.png b/docs/assets/companion-import/light-selection.png
new file mode 100644
index 0000000000..54c9475f04
Binary files /dev/null and b/docs/assets/companion-import/light-selection.png differ
diff --git a/docs/assets/companion-import/narrow-skills.png b/docs/assets/companion-import/narrow-skills.png
new file mode 100644
index 0000000000..a9f4a19d6a
Binary files /dev/null and b/docs/assets/companion-import/narrow-skills.png differ
diff --git a/docs/product-rules/cindy-bots-runtime.md b/docs/product-rules/cindy-bots-runtime.md
index 5a4c1b1022..de6449bae1 100644
--- a/docs/product-rules/cindy-bots-runtime.md
+++ b/docs/product-rules/cindy-bots-runtime.md
@@ -550,3 +550,14 @@ Codex 切模型重建时,线程索引里的路径不等于文件已经落盘
- 伙伴读位复用设备本地、账号隔离的持久存储;同机窗口通过 storage 事件更新。它不是跨设备已读协议,手机读过不会清除桌面伙伴角标。群聊复用同样的读位机制,旧工作端缺少回复时间字段时不凭空推断未读。首次建立读位不追溯已有历史,之后列表刷新不重置读位。
- 手机在现有首页菜单的「任务/伙伴」切换上显示对应数字,不另造返回按钮。伙伴页仍让任务镜像按现有连接恢复链路同步全部可用电脑;任务页本身的筛选、消息存储和运行行为不变。离线保留已有镜像,重连后重取;解除绑定或删除条目后不再聚合。
- 零不显示,入口溢出复用伙伴列表的 `99+` 规范;辅助文本保留完整数字与单位,所有界面语言一起提供。
+
+
+## 本机 Hermes / OpenClaw 导入
+
+- 按来源实际可发现的技能、记忆和自动化列出内容,不用固定条数裁剪;技能默认全选,来源停用的技能仍保持停用。
+- 导入页用分类汇总和可搜索、分页的单层列表;保存完成后直接进入伙伴聊天,不在完成页堆叠逐项待办。
+- 先保存资料、连接与停用状态的自动化定义,再在聊天中完成登录和验证;用户可以稍后处理,普通聊天始终可用。
+- 新导入的自动化结果统一进入 Cindy 伙伴聊天,不校验或沿用原发送渠道。存量已导入自动化不自动改渠道。
+- 不展示无法接管的原生 Heartbeat;名字包含 heartbeat 的普通定时任务仍保留。
+- 单项读取或写入失败保留重试记录,不中止其它内容;导入成功数量与自动化启用状态分别计算。文件字节保护仍适用,不截断文件冒充完整导入。
+- 原任务在验证及接管完成前保持原状。明确选用 Cindy 模型和工具设置后可解除相应兼容性待办,仍须验证数据并确认原任务已暂停,才能启用 Cindy 任务。
diff --git a/packages/maker-shared/src/__tests__/companionImport.test.ts b/packages/maker-shared/src/__tests__/companionImport.test.ts
index ed752f4ea0..9ec969d1c5 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 } from 'vitest';
-import { areCompanionImportEntriesSelected, toggleCompanionImportEntries, type CompanionImportEntry } from '../companionImport.js';
+import { expect, it, vi } from 'vitest';
+import { 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'] },
@@ -18,3 +18,16 @@ it('switches credentials in the existing selection and keeps bulk selection unam
expect(toggleCompanionImportEntries(entries, personal, ['personal'], false)).toEqual(['other']);
expect(toggleCompanionImportEntries(entries, personal, all, false)).toEqual([]);
});
+
+it.each([false, true])('negotiates compact selections only when the host advertises support (%s)', async supported => {
+ const many = Array.from({ length: 2100 }, (_, index) => ({ id: `memory-${index}`, name: `Memory ${index}`, category: 'memory' as const, selected: true }));
+ const preview: CompanionImportPreview = { id: 'preview', source: { id: 'source', name: 'Ada', kind: 'hermes' }, name: 'Ada', entries: many, ...(supported ? { selectionRanges: true as const } : {}) };
+ const result = { requestId: 'compat-request-12345', botId: 'bot', canonicalSessionId: 'chat', status: 'complete', checks: [] };
+ const invoke = vi.fn<Parameters<typeof remoteCompanionImportApi>[1]>(async () => ({}));
+ const api = remoteCompanionImportApi(async id => ({ blocks: [{ primitive: 'companion-import', data: id.startsWith('preview:') ? { preview } : { result } }] }), invoke);
+ const received = await api.preview('source');
+ const chosen = many.filter((_, index) => index !== 100).map(entry => entry.id);
+ await expect(api.start({ previewId: received.id, requestId: result.requestId, name: 'Ada', takeover: false, ...compactCompanionImportSelection(received, chosen) })).resolves.toEqual(result);
+ expect(invoke).toHaveBeenCalledWith('source', expect.objectContaining(supported ? { entryIds: [], entryRanges: [[0, 99], [101, 2099]] } : { entryIds: chosen }));
+ if (!supported) expect(invoke.mock.calls[0]?.[1]).not.toHaveProperty('entryRanges');
+});
diff --git a/packages/maker-shared/src/companionImport.ts b/packages/maker-shared/src/companionImport.ts
index ef758a3e64..bb554e9f7a 100644
--- a/packages/maker-shared/src/companionImport.ts
+++ b/packages/maker-shared/src/companionImport.ts
@@ -29,6 +29,8 @@ export interface CompanionImportPreview {
name: string;
avatarImageBase64?: string;
entries: CompanionImportEntry[];
+ /** Host understands compact immutable preview-index ranges. */
+ selectionRanges?: true;
}
export interface CompanionImportSelection {
@@ -38,7 +40,11 @@ export interface CompanionImportSelection {
name: string;
avatarImageBase64?: string;
entryIds: string[];
+ /** Inclusive preview-index ranges, only when advertised; mutually exclusive with entryIds. */
+ entryRanges?: Array<[number, number]>;
takeover: boolean;
+ /** Save first; connection checks and source handover continue from the teammate chat. */
+ deferSetup?: boolean;
}
export interface CompanionImportCheck {
@@ -53,6 +59,10 @@ export interface CompanionImportResult {
canonicalSessionId?: string;
status: 'running' | 'complete' | 'needs-attention';
checks: CompanionImportCheck[];
+ /** The companion and selected content have finished their save pass. */
+ saved?: boolean;
+ /** Saved definitions/content, independently of later authorization and activation. */
+ savedEntryIds?: string[];
}
export interface CompanionImportApi {
@@ -64,9 +74,25 @@ export interface CompanionImportApi {
export const companionImportCategories: CompanionImportCategory[] = ['personality', 'memory', 'skills', 'connections', 'automations'];
+/** Preserve exact choices while keeping large selections below the existing action budget. */
+export function compactCompanionImportSelection(preview: CompanionImportPreview, selected: string[]): Pick<CompanionImportSelection, 'entryIds' | 'entryRanges'> {
+ if (!preview.selectionRanges || selected.length < 200) return { entryIds: selected };
+ const ids = new Set(selected);
+ const ranges: Array<[number, number]> = [];
+ preview.entries.forEach((entry, index) => {
+ if (!ids.has(entry.id)) return;
+ const last = ranges.at(-1);
+ if (last && last[1] + 1 === index) last[1] = index;
+ else ranges.push([index, index]);
+ });
+ return JSON.stringify(ranges).length < JSON.stringify(selected).length
+ ? { entryIds: [], entryRanges: ranges } : { entryIds: selected };
+}
+
/** An alternative already chosen within this category also satisfies its group checkbox. */
export function areCompanionImportEntriesSelected(entries: CompanionImportEntry[], selected: string[]): boolean {
- const selectedHere = new Set(entries.filter(entry => selected.includes(entry.id)).map(entry => entry.id));
+ const all = new Set(selected);
+ const selectedHere = new Set(entries.filter(entry => all.has(entry.id)).map(entry => entry.id));
return entries.every(entry => selectedHere.has(entry.id) || entry.exclusiveWith?.some(id => selectedHere.has(id)));
}
@@ -112,7 +138,7 @@ export function remoteCompanionImportApi(
};
const status = async (requestId: string) => {
const result = (await data(`result:${requestId}`)).result as CompanionImportResult | null;
- if (result && (result.requestId !== requestId || !Array.isArray(result.checks) || result.checks.length > 2001
+ if (result && (result.requestId !== requestId || !Array.isArray(result.checks)
|| !['running', 'complete', 'needs-attention'].includes(result.status))) throw new Error('INVALID_IMPORT_RESPONSE');
return result ?? undefined;
};
@@ -120,12 +146,12 @@ export function remoteCompanionImportApi(
return {
async sources() {
const result = (await data('sources')).sources as CompanionImportSource[];
- if (!Array.isArray(result) || result.length > 2000 || result.some(source => !source.id || !source.name || !['hermes', 'openclaw'].includes(source.kind))) throw new Error('INVALID_IMPORT_RESPONSE');
+ if (!Array.isArray(result) || result.some(source => !source.id || !source.name || !['hermes', 'openclaw'].includes(source.kind))) throw new Error('INVALID_IMPORT_RESPONSE');
return result;
},
async preview(sourceId) {
const result = (await data(`preview:${sourceId}`)).preview as CompanionImportPreview;
- if (!result?.id || !Array.isArray(result.entries) || result.entries.length > 2000
+ if (!result?.id || !Array.isArray(result.entries)
|| result.entries.some(entry => !entry.id || typeof entry.name !== 'string' || !companionImportCategories.includes(entry.category))) throw new Error('INVALID_IMPORT_RESPONSE');
sources.set(result.id, sourceId);
return result;