Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(companions): batch import progress and open saved teammates
Chris87e44301be19
diff --git a/apps/desktop/src/main/bot-import/README.md b/apps/desktop/src/main/bot-import/README.mdindex 60bed7d7ed..3ce8d80baf 100644--- a/apps/desktop/src/main/bot-import/README.md+++ b/apps/desktop/src/main/bot-import/README.md@@ -330,7 +330,9 @@ GUI imports send the additive `deferSetup` flag (the command defaults it to trueSaving personality/memory/skills, private connections and disabled routine definitionsfinishes before any data probe, source pause or target activation. `savedEntryIds`counts saved definitions independently of activation status. `saved: true` means-that the save pass finished, not that every selected item succeeded. Both clients+that the save pass finished, not that every selected item succeeded. After all+selected content is saved, both clients open the teammate chat once,+including when sign-in or mapping remains. Partial-save resultsshow saved/selected counts and distinguish partial imports from setup-only checks.An expandable, paginated detail list shows filenames, safe reasons and partialprogress. Chat remains available alongside retry. Idempotent chat notices distinguish@@ -470,3 +472,8 @@ verification and handover gates. They never start a model turn or inherit model/policy requirements. Read-only verification must verify their actual dependencies;it cannot accept a command as a simple local reminder. Native `heartbeat` payloadsare excluded, while ordinary jobs named heartbeat remain importable.++Ordinary content/routine progress uses indexed checks and at most about 100 full+receipt snapshots per pass, sized from the selected input. An interrupted batch+replays idempotent writes and `createOnce` under the same IDs. Handover intent,+source pause, target enable and rollback milestones still persist immediately.diff --git a/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts b/apps/desktop/src/main/bot-import/__tests__/transfer.test.tsindex 9d3800b9a1..486b4506ff 100644--- a/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts+++ b/apps/desktop/src/main/bot-import/__tests__/transfer.test.ts@@ -411,3 +411,35 @@ it('validates 100,000 sparse selections in linear work and rejects oversized ranexpect(() => validateImportSelection({ ...selection, entryIds: [], entryRanges: [[0, Number.MAX_SAFE_INTEGER - 1]] }, indexed)).toThrow('SELECTION_CHANGED');});++it('saves 100,000 content entries with bounded receipt rewrites and indexed progress', async () => {+ const { deps } = harness();+ const count = 100_000;+ const items = Array.from({ length: count }, (_, index) => ({ view: { id: `memory-${index}`, name: 'Note', category: 'memory' as const, selected: true }, text: 'Original' }));+ let writes = 0, serializedChecks = 0;+ deps.saveReceipt = async receipt => { writes++; serializedChecks += receipt.result.checks.length; };+ const result = await transferCompanion({ ...snapshot, items }, { ...selection, entryIds: items.map(item => item.view.id), takeover: false, deferSetup: true }, deps);+ expect(result.savedEntryIds).toHaveLength(count);+ expect(result.checks).toHaveLength(count);+ expect(writes).toBeLessThan(110);+ expect(serializedChecks).toBeLessThan(count * 60);+ expect(deps.importItem).toHaveBeenCalledTimes(count);+}, 10_000);++it('resumes an interrupted progress batch using stable item IDs without replaying saved batches', async () => {+ const { deps, receipt } = harness();+ const items = Array.from({ length: 400 }, (_, index) => ({ view: { id: `memory-${index}`, name: 'Note', category: 'memory' as const, selected: true }, text: 'Original' }));+ const input = { ...selection, entryIds: items.map(item => item.view.id), takeover: false, deferSetup: true };+ let interrupted = false;+ const calls: string[] = [];+ deps.assertOwner = () => { if (interrupted) throw new Error('OWNER_CHANGED'); };+ deps.importItem = async (_bot, item) => { calls.push(item.view.id); if (calls.length === 6) interrupted = true; };+ await expect(transferCompanion({ ...snapshot, items }, input, deps)).rejects.toThrow('OWNER_CHANGED');+ expect(receipt()?.copied).toEqual(items.slice(0, 4).map(item => item.view.id));+ interrupted = false;+ const result = await transferCompanion({ ...snapshot, items }, input, deps);+ expect(result.savedEntryIds).toHaveLength(400);+ expect(calls.filter(id => id === 'memory-0')).toHaveLength(1);+ expect(calls.filter(id => id === 'memory-4')).toHaveLength(2);+ expect(calls.filter(id => id === 'memory-5')).toHaveLength(2);+});diff --git a/apps/desktop/src/main/bot-import/transfer.ts b/apps/desktop/src/main/bot-import/transfer.tsindex 31b080318b..90a2ae2e85 100644--- a/apps/desktop/src/main/bot-import/transfer.ts+++ b/apps/desktop/src/main/bot-import/transfer.ts@@ -121,19 +121,34 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Comreceipt.selectionHash = selectionHash;receipt.deferSetup = selection.deferSetup === true;const botId = receipt.result.botId;- const save = async () => { deps.assertOwner(); await deps.saveReceipt(receipt); deps.assertOwner(); };- const check = (entryId: string, status: CompanionImportResult['checks'][number]['status'], message?: string, progress?: { saved: number; total: number }) => {- receipt.result.checks = [...receipt.result.checks.filter(item => item.entryId !== entryId), { entryId, status, ...(message ? { message } : {}), ...(progress ? { progress } : {}) }];- };receipt.result.status = 'running';receipt.result.checks = receipt.result.checks.filter(item => item.entryId !== 'import');+ const copied = new Set(receipt.copied);+ const checkIndexes = new Map(receipt.result.checks.map((item, index) => [item.entryId, index]));+ const selected = new Set(selectedIds);+ // Cap full progress snapshots per pass, not imported items. A lost batch is+ // replayed through idempotent content writes/createOnce; source handover+ // milestones still call save immediately before/after each external mutation.+ const progressBatchSize = Math.max(1, Math.ceil(items.length / 100));+ let pendingProgress = 0;+ const save = async () => { deps.assertOwner(); await deps.saveReceipt(receipt); deps.assertOwner(); pendingProgress = 0; };+ const saveProgress = async () => { if (++pendingProgress >= progressBatchSize) await save(); };+ const check = (entryId: string, status: CompanionImportResult['checks'][number]['status'], message?: string, progress?: { saved: number; total: number }) => {+ const index = checkIndexes.get(entryId) ?? receipt.result.checks.length;+ checkIndexes.set(entryId, index);+ receipt.result.checks[index] = { entryId, status, ...(message ? { message } : {}), ...(progress ? { progress } : {}) };+ };+ const needsAttention = (id: string) => {+ const index = checkIndexes.get(id);+ return index !== undefined && receipt.result.checks[index]?.status === 'needs-attention';+ };// Capture only selected resources, then publish a non-secret request index// before storing credentials. Acceptance still waits for the full checkpoint.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)) {+ if (item.captureIssue && item.sourceDirectory && item.filesComplete && !copied.has(item.view.id)) {item.files = undefined; item.filesComplete = false;}if (item.captureIssue && item.sourceFile) {@@ -204,22 +219,23 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Comdeps.assertOwner();receipt.companionCreated = true;await save();- // Each selected item is a separate checkpoint. Retrying never copies unselected source files.+ // Retry only selected resources; saved batches skip completed idempotent copies.for (const item of items.filter(item => item.view.category !== 'automations' && item.view.category !== 'connections')) {- if (receipt.copied.includes(item.view.id)) continue;+ if (copied.has(item.view.id)) continue;deps.assertOwner();try {if (item.captureIssue) throw new CompanionImportError(item.captureIssue);await deps.importItem(botId, item, snapshot);deps.assertOwner();- receipt.copied.push(item.view.id);+ receipt.copied.push(item.view.id); copied.add(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', importFailureCode(error), (error as { importProgress?: { saved: number; total: number } })?.importProgress);}- await save();+ await saveProgress();}+ await save();if (!receipt.environmentSaved) {await deps.saveEnvironment(botId, items);deps.assertOwner();@@ -227,30 +243,29 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Comawait save();}for (const item of items.filter(item => item.view.category === 'connections')) {- const issue = item.view.dependsOn?.some(id => !selectedIds.includes(id)) ? 'AUTOMATION_DEPENDENCY_NOT_SELECTED' : item.view.issues?.[0];+ const issue = item.view.dependsOn?.some(id => !selected.has(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(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?.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));+ return !!item?.captureIssue || item?.view.enabled === false && (item.view.category === 'skills' || !!item.mcp) || needsAttention(id) || !!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// failed verification needs an explicit retry, never another model/Ask call.const prior = receipt.routines[item.view.id];- if (reconcileOnly && receipt.result.checks.some(check => check.entryId === item.view.id && check.status === 'needs-attention')+ if (reconcileOnly && needsAttention(item.view.id)&& prior?.phase !== 'pausing-source' && prior?.phase !== 'source-paused') continue;const automation = item.automation!;if (!automation.input) {check(item.view.id, 'needs-attention', item.view.issues?.find(issue => !['SOURCE_TOOL_POLICY_NEEDS_MAPPING', 'AUTOMATION_MODEL_NEEDS_MAPPING'].includes(issue)) ?? 'SOURCE_AUTOMATION_INVALID');- await save(); continue;+ await saveProgress(); continue;}let record = receipt.routines[item.view.id];if (!record) {@@ -258,25 +273,25 @@ export async function transferCompanion(snapshot: ImportSnapshot, selection: Comconst 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();+ // createOnce is idempotent if this progress batch is interrupted.} catch (error) {deps.assertOwner();check(item.view.id, 'needs-attention', importFailureCode(error));- await save(); continue;+ await saveProgress(); 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;+ record.phase = 'complete'; check(item.view.id, 'paused'); await saveProgress(); continue;}if (item.view.issues?.length) {- check(item.view.id, 'needs-attention', item.view.issues[0]); await save(); continue;+ check(item.view.id, 'needs-attention', item.view.issues[0]); await saveProgress(); continue;}if (selection.deferSetup && !resumeSetup && record.phase === 'created') {- check(item.view.id, 'needs-attention', 'IMPORT_SETUP_DEFERRED'); await save(); continue;+ check(item.view.id, 'needs-attention', 'IMPORT_SETUP_DEFERRED'); await saveProgress(); continue;}if (item.view.dependsOn?.some(id => missingDependency(id))) {- check(item.view.id, 'needs-attention', 'AUTOMATION_DEPENDENCY_NOT_SELECTED'); await save(); continue;+ check(item.view.id, 'needs-attention', 'AUTOMATION_DEPENDENCY_NOT_SELECTED'); await saveProgress(); continue;}if (record.phase === 'created') {try {diff --git a/apps/desktop/src/renderer/features/bots/BotImportForm.tsx b/apps/desktop/src/renderer/features/bots/BotImportForm.tsxindex 81994283aa..59bf2e8cdd 100644--- a/apps/desktop/src/renderer/features/bots/BotImportForm.tsx+++ b/apps/desktop/src/renderer/features/bots/BotImportForm.tsx@@ -84,12 +84,20 @@ export function BotImportForm({ api = window.electronAPI.companionImport, onBackconst savedIds = new Set(result?.savedEntryIds);const incomplete = result?.savedEntryIds ? selected.some(id => !savedIds.has(id)) : outstanding.some(check => check.message === 'IMPORT_ITEM_FAILED');const finished = result && result.status !== 'running';+ const openedRequest = useRef<string | undefined>(undefined);+ const enterChat = !!finished && saved && !incomplete && !!result?.canonicalSessionId;+ useEffect(() => {+ if (!enterChat || !result || openedRequest.current === result.requestId) return;+ openedRequest.current = result.requestId;+ onCreated(result.botId);+ }, [enterChat, result, onCreated]);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)]" />;+ if (enterChat) return null;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">diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botImport.test.tsx b/apps/desktop/src/renderer/features/bots/__tests__/botImport.test.tsxindex 13163c82fb..67f358e499 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botImport.test.tsx+++ b/apps/desktop/src/renderer/features/bots/__tests__/botImport.test.tsx@@ -124,8 +124,8 @@ it('uses the original portrait control and sends only the items still selected',fireEvent.click(screen.getByRole('button', { name: 'bots.import.submit' }));await waitFor(() => expect(api.start).toHaveBeenCalledTimes(1));expect(vi.mocked(api.start).mock.calls[0]![0]).toMatchObject({ name: 'Ada', entryIds: ['skill'], avatarImageBase64: 'chosen' });- fireEvent.click(await screen.findByRole('button', { name: 'bots.import.open' }));- expect(open).toHaveBeenCalledWith('imported');+ await waitFor(() => expect(open).toHaveBeenCalledExactlyOnceWith('imported'));+ expect(screen.queryByRole('button', { name: 'bots.import.open' })).toBeNull();});@@ -166,8 +166,8 @@ it('shows 142 selected skills in a flat searchable paginated list and opens chatexpect((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');+ await waitFor(() => expect(open).toHaveBeenCalledExactlyOnceWith('bot'));+ expect(screen.queryByRole('button', { name: 'bots.import.open' })).toBeNull();expect(screen.queryByRole('alert')).toBeNull();expect(screen.queryByRole('button', { name: 'bots.import.retry' })).toBeNull();});diff --git a/apps/mobile/src/__tests__/CompanionImportSheet.test.tsx b/apps/mobile/src/__tests__/CompanionImportSheet.test.tsxindex bf4cbe4837..0677d4e145 100644--- a/apps/mobile/src/__tests__/CompanionImportSheet.test.tsx+++ b/apps/mobile/src/__tests__/CompanionImportSheet.test.tsx@@ -41,7 +41,8 @@ it('uses the existing portrait picker and sends only the remaining selections thawait act(async () => (container.querySelector('[aria-label="devices.companionImport.memory"]') as HTMLInputElement).click());await click('devices.companionImport.submit');expect(h.submit.mock.calls[0]?.[2].input).toMatchObject({ entryIds: ['personality'], avatarImageBase64: 'chosen-existing-portrait' });- await click('devices.companionImport.open'); expect(h.created).toHaveBeenCalledWith({ collectionId: 'teammates', kind: 'bot', id: 'bot' });+ expect(h.created).toHaveBeenCalledExactlyOnceWith({ collectionId: 'teammates', kind: 'bot', id: 'bot' });+ expect(container.textContent).not.toContain('devices.companionImport.open');});diff --git a/apps/mobile/src/session/CompanionImportSheet.tsx b/apps/mobile/src/session/CompanionImportSheet.tsxindex 66d3ea4681..52b32ca801 100644--- a/apps/mobile/src/session/CompanionImportSheet.tsx+++ b/apps/mobile/src/session/CompanionImportSheet.tsx@@ -98,10 +98,17 @@ export function CompanionImportSheet({ visible, onClose, onClosed, deviceId, devconst savedIds = new Set(result?.savedEntryIds);const incomplete = result?.savedEntryIds ? selected.some(id => !savedIds.has(id)) : outstanding.some(check => check.message === 'IMPORT_ITEM_FAILED');const finished = result && result.status !== 'running';+ const openedRequest = useRef<string | undefined>(undefined);+ const enterChat = !!finished && saved && !incomplete && !!result?.canonicalSessionId;+ useEffect(() => {+ if (!enterChat || !result || openedRequest.current === result.requestId) return;+ openedRequest.current = result.requestId;+ onCreated({ collectionId: 'teammates', kind: 'bot', id: result.botId }); onClose();+ }, [enterChat, result, onCreated, onClose]);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}>+ return <CompanionSheet visible={visible && !enterChat} title={tr('title')} onClose={() => { if (!busy || result) onClose(); }} onClosed={onClosed} preventDismiss={busy && !result}>+ {!enterChat ? <ScrollView keyboardShouldPersistTaps="handled" contentContainerStyle={styles.content}>{!online || error ? <Text accessibilityRole="alert" style={styles.note}>{!online ? t('devices.companionProfile.offline', { deviceName }) : tr(companionImportReasonKey(error))}</Text> : null}{finished && saved ? <><Text style={styles.label}>{tr(incomplete ? 'partial' : 'complete')}</Text>@@ -145,7 +152,7 @@ export function CompanionImportSheet({ visible, onClose, onClosed, deviceId, dev</>}{finished && (!saved || incomplete) ? <MainWindowActionButton action={{ label: tr('retry'), busy, disabled: busy || !online, onPress: () => void submit() }} /> : null}{finished ? <MainWindowActionButton action={{ label: tr('open'), disabled: !result.canonicalSessionId, onPress: () => { onCreated({ collectionId: 'teammates', kind: 'bot', id: result.botId }); onClose(); } }} /> : preview && !expanded ? <MainWindowActionButton action={{ label: tr('submit'), busy, disabled: busy || !online || !name.trim() || !avatar, onPress: () => void submit() }} /> : null}- </ScrollView>+ </ScrollView> : null}</CompanionSheet>;}diff --git a/docs/assets/companion-import/README.md b/docs/assets/companion-import/README.mdindex 414cac9e90..9285da8185 100644--- a/docs/assets/companion-import/README.md+++ b/docs/assets/companion-import/README.md@@ -8,7 +8,8 @@ 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 andone scrolling body; this is not a native Mobile screenshot.-- `light-saved.png`: saved content opens the companion while setup is deferred.+Completed saves now navigate directly to the teammate chat; the old completion-page+fixture was removed. Partial failures retain their detail and retry controls.The fixture renderer and its embedded data are not included in shipped code.Native iOS/Android visual checks, mixed-version device sessions and live providerdiff --git a/docs/assets/companion-import/light-saved.png b/docs/assets/companion-import/light-saved.pngdeleted file mode 100644index 13e437b8f9..0000000000Binary files a/docs/assets/companion-import/light-saved.png and /dev/null differ