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): page import setup without decoding source snapshots

Chrisa2b63f4edbda
diff --git a/apps/desktop/src/main/bot-import/README.md b/apps/desktop/src/main/bot-import/README.md
index 867d1641d9..223cbab0c4 100644
--- a/apps/desktop/src/main/bot-import/README.md
+++ b/apps/desktop/src/main/bot-import/README.md
@@ -547,3 +547,21 @@ library resolution when the skill is saved or temporarily materialized.
This grants no access to neighboring credentials or external directories. The
original virtualenv configuration and resource files stay intact; cross-machine
runtime availability is not implied by saving their definitions.
+
+### Setup status metadata and raw command URLs (2026-09-29)
+
+Setup status resolves the active Main-owned session/owner and reads the opaque
+import request ID from the existing environment manifest. The receipt retains
+already-redacted entry captions (at most 200 characters for status display).
+Paging never opens the vault or reconstructs Skill/attachment buffers. Existing
+manifests/receipts upgrade once under the import lock; normal recovery and explicit
+retry still load the checkpoint when required. Caption clipping does not alter
+source names, files, automation definitions, or encrypted originals. Repaired
+capture metadata replaces the captions on the next checkpoint save.
+
+Raw command environment capability URLs use the same URL component masks as JSON
+command environments, before Remote Resource previews and public Skill/memory/
+routine/receipt publication. Encoded and decoded path, query and fragment values
+are covered even when the command is deselected but its token occurs in selected
+content. This remains scoped to command environment values; ordinary provider
+base URLs do not create global path-word masks. Encrypted originals are retained.
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 61767dd64e..9854c714fa 100644
--- a/apps/desktop/src/main/bot-import/__tests__/connectionProvider.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/connectionProvider.test.ts
@@ -7,9 +7,9 @@ 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';
+vi.mock('../host.js', () => ({ continueCompanionImport: vi.fn(), getCompanionImportSetupStatus: vi.fn(), useCindyImportSettings: vi.fn() }));
+vi.mock('../runtime.js', () => ({ readCompanionSessionEnvironment: vi.fn(), readCompanionSessionScope: vi.fn() }));
+import { readCompanionSessionEnvironment, readCompanionSessionScope } from '../runtime.js';
import { createCompanionConnectionsProvider } from '../connectionProvider.js';
import { redactEnvironmentData } from '../process.js';
import { withImportedConnection } from '../connections.js';
@@ -402,13 +402,14 @@ readline.createInterface({input:process.stdin}).on('line', line => {
});
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 { getCompanionImportSetupStatus, 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(getCompanionImportSetupStatus).mockImplementation(async (_bot, _root, _assert, offset) => ({ status: result.status, total: 23, nextOffset: offset === 0 ? 20 : undefined, items: checks.slice(offset, offset + 20).map(check => ({ ...check, name: 'Job [API_KEY]' })) }));
vi.mocked(continueCompanionImport).mockResolvedValue(result);
const assertOwner = vi.fn();
+ vi.mocked(readCompanionSessionScope).mockResolvedValue({ owner: 'fixture', botId: 'bot', userData: '/fixture', assertOwner });
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 },
@@ -420,6 +421,7 @@ it('offers paginated private import setup only in the owning companion and masks
await config.instance.connect(serverTransport); await client.connect(clientTransport);
try {
expect((await client.listTools()).tools.some(tool => tool.name === 'import_setup')).toBe(true);
+ vi.mocked(readCompanionSessionEnvironment).mockClear().mockRejectedValue(new Error('must not load full environment'));
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);
@@ -427,6 +429,8 @@ it('offers paginated private import setup only in the owning companion and masks
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(getCompanionImportSetupStatus).toHaveBeenLastCalledWith('bot', '/fixture', assertOwner, 20);
+ expect(readCompanionSessionEnvironment).not.toHaveBeenCalled();
expect(assertOwner).toHaveBeenCalled();
} finally { await client.close(); await config.instance.close(); }
});
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 0be81732a7..7a4f813751 100644
--- a/apps/desktop/src/main/bot-import/__tests__/host.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/host.test.ts
@@ -43,9 +43,11 @@ vi.mock('../openclawCron.js', () => ({ readOpenClawCronDatabase: vi.fn() }));
vi.mock('../verification.js', () => ({ verifyImportedAutomation: vi.fn(async () => ({ verified: h.verified, reason: 'AUTOMATION_DATA_READ_FAILED' })) }));
vi.mock('../takeover.js', () => ({ changeSourceAutomationState: async (_source: unknown, _item: unknown, enabled: boolean, _readers: unknown, _owner: unknown, _resume: boolean, env: Record<string, string>) => { h.pause(enabled); h.sourceEnabled = enabled; h.sourceEnvironment = env; } }));
vi.mock('../runtime.js', () => ({ recoverCompanionEnvironmentRemovals: vi.fn(async () => {}),
+ readCompanionSessionScope: async () => ({ owner: h.root, botId: h.botId, userData: h.root, assertOwner() { if (h.boundary) throw new Error('OWNER_CHANGED'); } }),
readCompanionSessionEnvironment: async () => ({ identity: h.root, botId: h.botId, userData: h.root, assertOwner() {}, environment: await h.store.read(h.root, h.botId, () => {}) }),
companionEnvironmentStore: {
read: (...args: Parameters<typeof h.store.read>) => h.store.read(...args),
+ readImportRequestId: (...args: Parameters<typeof h.store.readImportRequestId>) => h.store.readImportRequestId(...args),
write: (...args: Parameters<typeof h.store.write>) => h.store.write(...args),
update: (...args: Parameters<typeof h.store.update>) => h.store.update(...args),
stageRemoval: (...args: Parameters<typeof h.store.stageRemoval>) => h.store.stageRemoval(...args),
@@ -69,7 +71,7 @@ vi.mock('../../routines/service.js', () => ({
h.routines = h.routines.map(row => row.id === id ? { ...row, ...input, revision: row.revision + 1 } : row);
} }),
}));
-import { submitRemoteCompanionImport, readRemoteCompanionImport, listCompanionImportSources, previewCompanionImport, startCompanionImport, getCompanionImportResult, recoverCompanionImports, prepareCompanionImportDeletion, cancelCompanionImportsForDeletion, ensureImportedAutomationReady } from '../host.js';
+import { submitRemoteCompanionImport, readRemoteCompanionImport, listCompanionImportSources, previewCompanionImport, startCompanionImport, getCompanionImportResult, getCompanionImportSetupStatus, recoverCompanionImports, prepareCompanionImportDeletion, cancelCompanionImportsForDeletion, ensureImportedAutomationReady } from '../host.js';
import { withBotProfileLocks } from '../../maker-ipc/botProfileLock.js';
import { assertImportedAutomationReady, prepareImportedAutomation } from '../automationRuntime.js';
import { decodeBotAvatarImage } from '../../localDb/ipc/botAvatarSelection.js';
@@ -414,13 +416,14 @@ it.each([false, true])('redacts all known credentials from profile/memory copies
it.each([false, true])('publishes structured command env credentials safely (command selected: %s)', async selected => {
const secret = 'fixture-command-json-token';
const nested = 'fixture-command-json-nested';
- const urlSecrets = ['fixture-hook-token', 'fixture-fragment token', 'fixture-fragment%20token'];
+ const urlSecrets = ['fixture-hook-token', 'fixture-fragment token', 'fixture-fragment%20token',
+ 'fixture-raw token', 'fixture-raw%20token', 'fixture-raw-query', 'fixture-raw-fragment'];
const config = JSON.stringify({ token: secret, credentials: [{ key: nested }],
services: [{ endpoint: 'https://host/hooks/fixture-hook-token#access_token=fixture-fragment%20token' }],
unused: { password: 'fixture-unused-command-secret' }, city: 'Paris', count: 7 });
const text = `Keep Paris and 7. ${secret} ${nested} ${urlSecrets.join(' ')}`;
const skill = `---\nname: report\ndescription: ${text}\n---\n${text}\n`;
- const original = { enabled: false, payload: { kind: 'command', argv: ['node', '-e', ''], env: { CONFIG: config } } };
+ const original = { enabled: false, payload: { kind: 'command', argv: ['node', '-e', ''], env: { CONFIG: config, WEBHOOK_URL: 'https://host/hooks/fixture-raw%20token?token=fixture-raw-query#access_token=fixture-raw-fragment' } } };
h.sourceEnabled = false;
h.snapshot.items = [
{ view: { id: 'task', name: text, category: 'automations', selected, enabled: false }, automation: { sourceId: 'task', fingerprint: 'fixture', original,
@@ -438,7 +441,8 @@ it.each([false, true])('publishes structured command env credentials safely (com
entryIds: ['memory', 'skill', ...(selected ? ['task'] : [])], takeover: false }, 'fixture');
await vi.waitFor(async () => expect((await getCompanionImportResult(requestId))?.saved).toBe(true));
const published = await fs.readFile(path.join(h.root, 'bots', result.botId, 'skills/report/SKILL.md'), 'utf8');
- const output = JSON.stringify([published, h.importDocument.mock.calls, h.routines]);
+ const receiptText = await fs.readFile(path.join(h.root, 'companion-imports', `${requestId}.json`), 'utf8');
+ const output = JSON.stringify([published, h.importDocument.mock.calls, h.routines, receiptText]);
for (const value of [secret, nested, ...urlSecrets]) expect(output).not.toContain(value);
expect(published).toContain('Keep Paris and 7.');
const stored = (await h.store.read(h.root, result.botId, () => {}))!;
@@ -1383,3 +1387,60 @@ it.each(['identity', 'user', 'instructions'] as const)('reapplies a repaired %s
expect(saved?.savedEntryIds).toContain('role-source');
expect(h.profile[field]).toBe('Repaired original');
});
+
+it.each([false, true])('pages setup without vault reads after one-time legacy metadata upgrade: %s', async legacy => {
+ const secret = 'fixture-private-setup-name';
+ const task = h.snapshot.items[0]!;
+ h.snapshot.items = Array.from({ length: 23 }, (_, index) => ({ ...structuredClone(task),
+ view: { ...task.view, id: `job-${index}`, name: `Report ${index} ${secret}` },
+ automation: { ...structuredClone(task.automation!), sourceId: `job-${index}` },
+ }));
+ h.snapshot.items[22]!.view.name = `Report 22 ${'x'.repeat(178)}${secret}`;
+ h.snapshot.items.push({ view: { id: 'env', name: 'API_KEY', category: 'connections', selected: true }, env: { API_KEY: secret } });
+ const [source] = await listCompanionImportSources('fixture');
+ const preview = await previewCompanionImport(source!.id, 'fixture');
+ const requestId = 'fixture-setup-paging-12345';
+ const result = await startCompanionImport({ requestId, previewId: preview.id, name: 'Ada',
+ entryIds: h.snapshot.items.map(item => item.view.id), takeover: true, deferSetup: true }, 'fixture');
+ await vi.waitFor(async () => expect((await getCompanionImportResult(requestId))?.status).toBe('needs-attention'));
+ const receiptFile = path.join(h.root, 'companion-imports', `${requestId}.json`);
+ const bindingFile = path.join(h.root, 'bots', result.botId, 'environment.json');
+ const originalCheckpoint = (await h.store.read(h.root, result.botId, () => {}))!.pendingImport!.snapshotJson;
+ if (legacy) {
+ const receipt = JSON.parse(await fs.readFile(receiptFile, 'utf8')); delete receipt.entryNames;
+ await fs.writeFile(receiptFile, JSON.stringify(receipt));
+ const binding = JSON.parse(await fs.readFile(bindingFile, 'utf8')); delete binding.importRequestId;
+ await fs.writeFile(bindingFile, JSON.stringify(binding));
+ const migrated = await getCompanionImportSetupStatus(result.botId, h.root, () => {}, 0);
+ expect(migrated).toMatchObject({ total: 23, nextOffset: 20 });
+ expect((await h.store.read(h.root, result.botId, () => {}))!.pendingImport!.snapshotJson).toBe(originalCheckpoint);
+ }
+ const publicReceipt = await fs.readFile(receiptFile, 'utf8');
+ expect(publicReceipt).not.toContain(secret);
+ expect(publicReceipt).not.toContain(secret.slice(0, 10));
+ expect(JSON.parse(publicReceipt).entryNames['job-22'].length).toBeLessThanOrEqual(200);
+ // Even a locked/unavailable vault must not be opened merely to paginate names.
+ const vaultRead = vi.spyOn(h.store, 'read').mockRejectedValue(new Error('status must not open vault'));
+ 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 {
+ for (const offset of [0, 20, 0]) {
+ const response = await client.callTool({ name: 'import_setup', arguments: { operation: 'status', offset } });
+ expect(response.isError).not.toBe(true);
+ const text = (response.content as Array<{ text: string }>)[0]!.text;
+ expect(text).not.toContain(secret);
+ const page = JSON.parse(text);
+ expect(page.total).toBe(23);
+ expect(page.items).toHaveLength(offset === 0 ? 20 : 3);
+ expect(page.items[0].name).toContain(`Report ${offset} `);
+ }
+ expect(vaultRead).not.toHaveBeenCalled();
+ h.boundary = true;
+ await expect(client.callTool({ name: 'import_setup', arguments: { operation: 'status' } })).rejects.toThrow('OWNER_CHANGED');
+ } finally { h.boundary = false; vaultRead.mockRestore(); await client.close(); await config.instance.close(); }
+ const receipt = JSON.parse(await fs.readFile(receiptFile, 'utf8')); receipt.result.botId = 'another-bot';
+ await fs.writeFile(receiptFile, JSON.stringify(receipt));
+ await expect(getCompanionImportSetupStatus(result.botId, h.root, () => {}, 0)).rejects.toThrow('INVALID_COMPANION');
+});
diff --git a/apps/desktop/src/main/bot-import/__tests__/runtime.test.ts b/apps/desktop/src/main/bot-import/__tests__/runtime.test.ts
index cedfec8f67..eec4e4ba5e 100644
--- a/apps/desktop/src/main/bot-import/__tests__/runtime.test.ts
+++ b/apps/desktop/src/main/bot-import/__tests__/runtime.test.ts
@@ -9,7 +9,7 @@ vi.mock('../../localDb/client/current.js', () => ({ getDbClient: () => {
const query = { from: () => query, innerJoin: () => query, where: () => query, limit: h.lookup };
return { drizzle: { select: () => query } };
} }));
-import { companionEnvironmentStore, finishCompanionEnvironmentRemoval, readCompanionSessionEnvironment, resolveCompanionRuntimeEnvironment } from '../runtime.js';
+import { companionEnvironmentStore, finishCompanionEnvironmentRemoval, readCompanionSessionEnvironment, readCompanionSessionScope, resolveCompanionRuntimeEnvironment } from '../runtime.js';
import { withImportedConnection } from '../connections.js';
afterEach(() => vi.restoreAllMocks());
@@ -79,3 +79,13 @@ readline.createInterface({input:process.stdin}).on('line', line => {
await fs.rm(h.root, { recursive: true, force: true }); h.root = '/fixture';
}
});
+
+it('resolves the active session owner and deletion fence without reading encrypted content', async () => {
+ const read = vi.spyOn(companionEnvironmentStore, 'read').mockRejectedValue(new Error('vault unavailable'));
+ const scope = await readCompanionSessionScope('fixture-session');
+ expect(scope).toMatchObject({ owner: 'fixture-owner', userData: '/fixture', botId: 'fixture-bot' });
+ scope!.assertOwner();
+ h.lookup.mockResolvedValueOnce([]);
+ expect(await readCompanionSessionScope('unlinked-session')).toBeUndefined();
+ expect(read).not.toHaveBeenCalled();
+});
diff --git a/apps/desktop/src/main/bot-import/connectionProvider.ts b/apps/desktop/src/main/bot-import/connectionProvider.ts
index a2bc444bc4..b51575d1b1 100644
--- a/apps/desktop/src/main/bot-import/connectionProvider.ts
+++ b/apps/desktop/src/main/bot-import/connectionProvider.ts
@@ -4,10 +4,10 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { CallToolRequestSchema, ListToolsRequestSchema, type Tool } from '@modelcontextprotocol/sdk/types.js';
import type { McpProvider } from '@cindy/maker-core';
import { resolveLiziMcpSessionContext } from '@cindy/mcps';
-import { readCompanionSessionEnvironment } from './runtime.js';
+import { readCompanionSessionEnvironment, readCompanionSessionScope } from './runtime.js';
import { IMPORTED_TOOL_LIMIT, listImportedTools, withImportedConnection } from './connections.js';
-import { deserializeImportSnapshotAsync, fingerprint } from './files.js';
-import { continueCompanionImport, getCompanionImportResult, useCindyImportSettings } from './host.js';
+import { fingerprint } from './files.js';
+import { continueCompanionImport, getCompanionImportSetupStatus, useCindyImportSettings } from './host.js';
import { connectionRedactions, importedContentRedactions, publicConnectionName, redactImportedResult, redactImportedTool, restoreImportedArguments } from './connectionCatalog.js';
import { withImportedSkillResources } from './skillResources.js';
@@ -54,28 +54,21 @@ export function createCompanionConnectionsProvider(): McpProvider {
return { tools };
});
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 }) }] };
+ const session = resolveLiziMcpSessionContext(context);
+ const scope = session.sessionId ? await readCompanionSessionScope(session.sessionId) : undefined;
+ if (!scope) throw new Error('Companion connection unavailable');
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);
+ if (operation === 'retry') await continueCompanionImport(scope.botId, scope.userData, scope.assertOwner);
+ const response = await getCompanionImportSetupStatus(scope.botId, scope.userData, scope.assertOwner, Number(offset));
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)) }] };
+ return { content: [{ type: 'text', text: JSON.stringify(response) }] };
}
+ const scope = await resolve();
+ if (!scope) throw new Error('Companion connection unavailable');
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/environment.ts b/apps/desktop/src/main/bot-import/environment.ts
index a3071787de..549718d46b 100644
--- a/apps/desktop/src/main/bot-import/environment.ts
+++ b/apps/desktop/src/main/bot-import/environment.ts
@@ -73,13 +73,24 @@ export function createCompanionEnvironmentStore(io: CompanionSecretIo) {
assertOwner();
// Names are untrusted too: a connection or variable identifier can contain
// a credential. This existence binding has no consumer for original names.
- const manifest = JSON.stringify({ version: 1, variables: Object.keys(value.env).map(name => fingerprint(name)), connections: value.mcp.map(server => fingerprint(server.name)), revision });
+ const manifest = JSON.stringify({ version: 1, variables: Object.keys(value.env).map(name => fingerprint(name)), connections: value.mcp.map(server => fingerprint(server.name)), revision,
+ importRequestId: value.pendingImport?.selection.requestId ?? null });
atomicWriteFileSync(file, manifest);
})();
const pending = writes.get(key) ?? new Set<Promise<void>>();
pending.add(task); writes.set(key, pending);
try { await task; } finally { pending.delete(task); if (!pending.size) writes.delete(key); }
},
+ /** Opaque request binding only. Undefined means a legacy manifest needs one-time migration. */
+ readImportRequestId(userData: string, botId: string, assertOwner: () => void): string | null | undefined {
+ assertOwner();
+ const text = readAtomicFileSync(bindingPath(userData, botId));
+ if (text === null) return null;
+ const id: unknown = JSON.parse(text).importRequestId;
+ if (id !== undefined && id !== null && (typeof id !== 'string' || !/^[A-Za-z0-9_-]{16,100}$/.test(id)))
+ throw new CompanionImportError('CREDENTIAL_STORAGE_INVALID');
+ return id as string | null | undefined;
+ },
async read(userData: string, botId: string, assertOwner: () => void): Promise<CompanionEnvironment | undefined> {
assertOwner();
if (readAtomicFileSync(bindingPath(userData, botId)) === null) return undefined;
diff --git a/apps/desktop/src/main/bot-import/environmentSelection.ts b/apps/desktop/src/main/bot-import/environmentSelection.ts
index 5af43ef464..daa75f670b 100644
--- a/apps/desktop/src/main/bot-import/environmentSelection.ts
+++ b/apps/desktop/src/main/bot-import/environmentSelection.ts
@@ -79,12 +79,14 @@ function importRedactions(items: ImportItem[], env: Record<string, string>): Rec
Object.entries(object(object(item.automation?.original.payload).env))
.filter((entry): entry is [string, string] => typeof entry[1] === 'string'),
));
- // Command env JSON can also occur in readable Skill/memory/routine copies.
+ // Command env JSON and raw capability URLs can occur in readable copies.
// Reuse the credential-field classifier before preview and publication, not
// just after command execution. Ordinary JSON scalar settings stay unchanged.
- const structured = commandEnvironments.flatMap(environment => Object.values(environment)).flatMap((value, index) => {
+ const structured = commandEnvironments.flatMap(environment => Object.values(environment)).flatMap<{ id: string; format: string; value: unknown }>((value, index) => {
+ const resolved = String(resolve(value));
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(resolved)) return [{ id: `command_${index}`, format: 'command-env', value: resolved }];
try {
- const parsed: unknown = JSON.parse(String(resolve(value)));
+ const parsed: unknown = JSON.parse(resolved);
return parsed && typeof parsed === 'object' ? [{ id: `command_${index}`, format: 'command-env', value: parsed }] : [];
} catch { return []; }
});
diff --git a/apps/desktop/src/main/bot-import/host.ts b/apps/desktop/src/main/bot-import/host.ts
index c3fcbec348..7bd11dd3f9 100644
--- a/apps/desktop/src/main/bot-import/host.ts
+++ b/apps/desktop/src/main/bot-import/host.ts
@@ -23,6 +23,7 @@ import { withBotProfileLocks } from '../maker-ipc/botProfileLock.js';
import { getRoutineEngine, routineTools, updateBotRoutineLifecycle } from '../routines/service.js';
import { previewImportRedactions, retainedImportRedactions, resolveImportReferences, selectedImportEnvironment, selectedImportRedactions } from './environmentSelection.js';
import { redactEnvironmentValues } from './process.js';
+import { importedContentRedactions } from './connectionCatalog.js';
import { createImportSourceReader, discoverImportSources, inspectImportSource, type SourceReaderDeps } from './sources.js';
import { readOpenClawCronDatabase } from './openclawCron.js';
import { companionEnvironmentStore, recoverCompanionEnvironmentRemovals } from './runtime.js';
@@ -388,6 +389,66 @@ export async function getCompanionImportResult(requestId: string): Promise<Compa
return receipt?.result;
}
+function setupEntryNames(items: ImportItem[], redact: (text: string) => string): Record<string, string> {
+ // A display-only caption, never the original Skill/persona/file name. Redact
+ // before clipping so a partial credential cannot escape into the receipt.
+ return Object.fromEntries(items.map(item => [item.view.id, redact(item.view.name).slice(0, 200)]));
+}
+
+/** Status uses public receipt metadata, not the encrypted source tree or attachment buffers. */
+export async function getCompanionImportSetupStatus(botId: string, root: string, assertOwner: () => void, offset: number) {
+ assertOwner();
+ const scope = owner();
+ if (scope.root !== root) throw new CompanionImportError('OWNER_CHANGED');
+ if (!Number.isSafeInteger(offset) || offset < 0) throw new CompanionImportError('INVALID_SELECTION');
+ let requestId = companionEnvironmentStore.readImportRequestId(root, botId, assertOwner);
+ let receipt = requestId ? await readReceipt(root, requestId) : undefined;
+ assertOwner();
+ if (receipt && receipt.result.botId !== botId) throw new CompanionImportError('INVALID_COMPANION');
+ if (requestId === undefined || receipt && !receipt.entryNames) await withBotProfileLocks([botId], async () => {
+ // Legacy checkpoints pay this cost once. Recheck under the same lock used by
+ // import/retry so a status migration cannot overwrite a newer receipt.
+ requestId = companionEnvironmentStore.readImportRequestId(root, botId, assertOwner);
+ receipt = requestId ? await readReceipt(root, requestId) : undefined;
+ assertOwner();
+ if (receipt && receipt.result.botId !== botId) throw new CompanionImportError('INVALID_COMPANION');
+ if (requestId !== undefined && (!receipt || receipt.entryNames)) return;
+ const environment = await companionEnvironmentStore.read(root, botId, assertOwner);
+ const pending = environment?.pendingImport;
+ if (pending) {
+ requestId = pending.selection.requestId;
+ receipt = await readReceipt(root, requestId); assertOwner();
+ if (receipt && receipt.result.botId !== botId) throw new CompanionImportError('INVALID_COMPANION');
+ if (receipt && !receipt.entryNames) {
+ const snapshot = await deserializeImportSnapshotAsync(pending.snapshotJson, assertOwner);
+ const secrets = Object.fromEntries([...new Set([
+ ...Object.values(importedContentRedactions(environment)), ...Object.values(previewImportRedactions(snapshot.items)),
+ ...Object.values(snapshot.publicationRedactions ?? {}),
+ ])].map((value, index) => [`setup_credential_${index}`, value]));
+ receipt.entryNames = setupEntryNames(snapshot.items, text => redactEnvironmentValues(text, secrets));
+ await saveReceipt(root, receipt); assertOwner();
+ }
+ } else requestId = null;
+ // Rewriting through the serialized store upgrades only metadata; the latest
+ // encrypted environment is preserved, including concurrent routine changes.
+ if (environment) await companionEnvironmentStore.update(root, botId, assertOwner, () => {});
+ });
+ assertOwner();
+ if (!requestId) return { complete: true };
+ const result = await getCompanionImportResult(requestId); assertOwner();
+ if (result && result.botId !== botId) throw new CompanionImportError('INVALID_COMPANION');
+ // Recovery may have refreshed names/checks. Read its durable public metadata.
+ receipt = await readReceipt(root, requestId); assertOwner();
+ if (receipt && receipt.result.botId !== botId) throw new CompanionImportError('INVALID_COMPANION');
+ let total = 0;
+ const items: Array<CompanionImportResult['checks'][number] & { name?: string }> = [];
+ for (const check of result?.checks ?? []) if (check.status === 'needs-attention') {
+ if (total >= offset && items.length < 20) items.push({ ...check, name: receipt?.entryNames?.[check.entryId] });
+ total++;
+ }
+ return { status: result?.status, total, nextOffset: offset + items.length < total ? offset + items.length : undefined, items };
+}
+
/** Explicit enable/run reuses the saved import retry, without a second settings UI. */
export async function ensureImportedAutomationReady(root: string, botId: string, routineId: string, assertOwner: () => void,
request?: { input?: RoutineInput; expectedRevision?: number }): Promise<number | void> {
@@ -462,6 +523,7 @@ export async function startCompanionImport(selection: CompanionImportSelection,
const publicRoutine = (input: RoutineInput): RoutineInput => ({ ...input, name: redactText(input.name), prompt: redactText(input.prompt) });
// Resource capture finishes before saveCheckpoint; retain only selected embedded values.
const publicationRedactions = (items: ImportSnapshot['items']) => retainedImportRedactions(items, contentSecrets);
+ let entryNames = setupEntryNames(selected, redactText);
const skillSlug = (item: ImportSnapshot['items'][number]) => {
const original = item.view.name;
if (redactText(original) !== original) return `import-${fingerprint(item.view.id).slice(0, 16)}`;
@@ -540,7 +602,7 @@ export async function startCompanionImport(selection: CompanionImportSelection,
if (skillConfigReader?.budget !== budget) skillConfigReader = { budget, reader: createImportSourceReader(readers(), budget) };
return skillConfigReader.reader.readConfig(path.dirname(source.configFile), source.configFile);
},
- saveReceipt: receipt => saveReceipt(scope.root, receipt),
+ saveReceipt: receipt => { receipt.entryNames = entryNames; return saveReceipt(scope.root, receipt); },
async createCompanion(botId, input) {
try {
const profile = await getBotRemoteResourceSource(botId); scope.assert();
@@ -638,6 +700,7 @@ export async function startCompanionImport(selection: CompanionImportSelection,
},
async saveCheckpoint(botId, items) {
const previous = await companionEnvironmentStore.read(scope.root, botId, scope.assert);
+ entryNames = setupEntryNames(items, redactText);
const pendingImport = { selection, snapshotJson: await serializeImportSnapshotAsync({ ...snapshot, avatarImageBase64: selection.avatarImageBase64, items, publicationRedactions: publicationRedactions(items) }, scope.assert) };
if (previous) await companionEnvironmentStore.update(scope.root, botId, scope.assert, environment => { environment.pendingImport = pendingImport; });
else await companionEnvironmentStore.write(scope.root, botId, { version: 1, env: {}, mcp: [], credentials: [], pendingImport }, scope.assert);
diff --git a/apps/desktop/src/main/bot-import/runtime.ts b/apps/desktop/src/main/bot-import/runtime.ts
index 1a0f36e5c5..0bad62e806 100644
--- a/apps/desktop/src/main/bot-import/runtime.ts
+++ b/apps/desktop/src/main/bot-import/runtime.ts
@@ -46,7 +46,7 @@ export async function recoverCompanionEnvironmentRemovals(): Promise<void> {
}
/** Resolve from the main-owned session link, never from a renderer-supplied Bot ID or path. */
-export async function readCompanionSessionEnvironment(sessionId: string) {
+export async function readCompanionSessionScope(sessionId: string) {
const owner = activeOwnerScopeKey();
const userData = ownerScopedUserDataPath();
let botId: string | undefined;
@@ -62,9 +62,16 @@ export async function readCompanionSessionEnvironment(sessionId: string) {
botId = link?.botId;
assertOwner();
if (!link) return undefined;
- const environment = await companionEnvironmentStore.read(userData, link.botId, assertOwner);
+ return { owner, assertOwner, botId: link.botId, userData };
+}
+
+export async function readCompanionSessionEnvironment(sessionId: string) {
+ const scope = await readCompanionSessionScope(sessionId);
+ if (!scope) return undefined;
+ const { owner, userData, botId, assertOwner } = scope;
+ const environment = await companionEnvironmentStore.read(userData, botId, assertOwner);
if (!environment) return undefined;
- return { identity: fingerprint([owner, link.botId, environment.env, environment.mcp, environment.credentials]), environment, assertOwner, botId: link.botId, userData };
+ return { identity: fingerprint([owner, botId, environment.env, environment.mcp, environment.credentials]), environment, assertOwner, botId, userData };
}
export async function resolveCompanionRuntimeEnvironment(sessionId: string) {
diff --git a/apps/desktop/src/main/bot-import/transfer.ts b/apps/desktop/src/main/bot-import/transfer.ts
index f652682034..1e694401fb 100644
--- a/apps/desktop/src/main/bot-import/transfer.ts
+++ b/apps/desktop/src/main/bot-import/transfer.ts
@@ -13,6 +13,8 @@ export interface ImportReceipt {
/** Present on receipts whose identity includes the original setup choice. */
deferSetup?: boolean;
result: CompanionImportResult;
+ /** Already-redacted display metadata; status pages must not open the encrypted checkpoint. */
+ entryNames?: Record<string, string>;
copied: string[];
environmentSaved?: boolean;
checkpointSaved?: boolean;