Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(bots): 允许删除有往来的伙伴并收口设置缺口 (#4969)
Chris Zhangb7c5d0a39c73
diff --git a/apps/desktop/src/main/localDb/__tests__/botProfileDeletionStore.test.ts b/apps/desktop/src/main/localDb/__tests__/botProfileDeletionStore.test.tsindex a2c069433f..58f90d70da 100644--- a/apps/desktop/src/main/localDb/__tests__/botProfileDeletionStore.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/botProfileDeletionStore.test.ts@@ -60,14 +60,14 @@ describe('Bot profile deletion transaction', () => {);CREATE TABLE bot_direct_message_threads (id TEXT PRIMARY KEY,- bot_a_id TEXT NOT NULL REFERENCES bot_profiles(id) ON DELETE CASCADE,- bot_b_id TEXT NOT NULL REFERENCES bot_profiles(id) ON DELETE CASCADE+ bot_a_id TEXT NOT NULL,+ bot_b_id TEXT NOT NULL);CREATE TABLE bot_direct_messages (id TEXT PRIMARY KEY,- thread_id TEXT NOT NULL REFERENCES bot_direct_message_threads(id) ON DELETE CASCADE,- sender_bot_id TEXT NOT NULL REFERENCES bot_profiles(id) ON DELETE CASCADE,- recipient_bot_id TEXT NOT NULL REFERENCES bot_profiles(id) ON DELETE CASCADE,+ thread_id TEXT NOT NULL,+ sender_bot_id TEXT NOT NULL,+ recipient_bot_id TEXT NOT NULL,content TEXT NOT NULL);CREATE TABLE media_refs (id TEXT PRIMARY KEY, ref_kind TEXT NOT NULL, ref_id TEXT NOT NULL);@@ -156,46 +156,71 @@ describe('Bot profile deletion transaction', () => {}describe.each([true, false])('shared history with keepTaskHistory=%s', (keepTaskHistory) => {- async function expectDeletionRejected() {- const before = snapshot();- await expect(commitBotProfileDeletion({+ async function deleteBot() {+ await commitBotProfileDeletion({botId: 'bot-1', sessionIds: ['canonical', 'route'], keepTaskHistory,- })).rejects.toMatchObject({ code: 'BOT_SHARED_HISTORY_REFERENCED' });- expect(snapshot()).toEqual(before);+ });}- it.each(['target', 'requester'])('preserves shared delegation when deleting its %s', async (role) => {+ it.each(['target', 'requester'])('deletes the profile without cascading the other bot when it is the delegation %s', async (role) => {sqlite.prepare('INSERT INTO bot_delegations VALUES (?, ?, ?)').run('delegation-1', role === 'target' ? 'bot-2' : 'bot-1', role === 'target' ? 'bot-1' : 'bot-2',);- await expectDeletionRejected();+ await deleteBot();+ expect(sqlite.prepare("SELECT id FROM bot_profiles WHERE id = 'bot-1'").get()).toBeUndefined();+ expect(sqlite.prepare("SELECT id FROM bot_profiles WHERE id = 'bot-2'").get()).toEqual({ id: 'bot-2' });+ expect(sqlite.prepare('SELECT * FROM bot_delegations').all()).toEqual(role === 'target'+ ? [{ id: 'delegation-1', requesting_bot_id: 'bot-2', target_bot_id: null }]+ : []);});- it.each(['a', 'b'])('preserves a private thread and its messages when deleting member %s', async (member) => {+ it.each(['a', 'b'])('keeps a private thread and its messages when deleting member %s', async (member) => {sqlite.prepare('INSERT INTO bot_direct_message_threads VALUES (?, ?, ?)').run('thread-1', member === 'a' ? 'bot-1' : 'bot-2', member === 'a' ? 'bot-2' : 'bot-1',);sqlite.exec(`INSERT INTO bot_direct_messages VALUES('dm-1', 'thread-1', 'bot-1', 'bot-2', 'Request'),('dm-2', 'thread-1', 'bot-2', 'bot-1', 'Reply')`);- await expectDeletionRejected();+ const messages = sqlite.prepare('SELECT * FROM bot_direct_messages').all();+ await deleteBot();+ expect(sqlite.prepare("SELECT id FROM bot_profiles WHERE id = 'bot-1'").get()).toBeUndefined();+ expect(sqlite.prepare('SELECT * FROM bot_direct_message_threads').all()).toEqual([+ { id: 'thread-1', bot_a_id: member === 'a' ? 'bot-1' : 'bot-2', bot_b_id: member === 'a' ? 'bot-2' : 'bot-1' },+ ]);+ expect(sqlite.prepare('SELECT * FROM bot_direct_messages').all()).toEqual(messages);});- it('preserves a private thread even before its first message', async () => {+ it('keeps a private thread even before its first message', async () => {sqlite.exec("INSERT INTO bot_direct_message_threads VALUES ('thread-1', 'bot-1', 'bot-2')");- await expectDeletionRejected();+ await deleteBot();+ expect(sqlite.prepare("SELECT id FROM bot_profiles WHERE id = 'bot-1'").get()).toBeUndefined();+ expect(sqlite.prepare('SELECT * FROM bot_direct_message_threads').all()).toEqual([+ { id: 'thread-1', bot_a_id: 'bot-1', bot_b_id: 'bot-2' },+ ]);});- it.each(['sender', 'recipient'])('checks actual message %s references independently of thread membership', async (role) => {+ it.each(['sender', 'recipient'])('keeps a message %s reference that is not a thread member', async (role) => {sqlite.exec("INSERT INTO bot_direct_message_threads VALUES ('thread-1', 'bot-2', 'bot-3')");sqlite.prepare('INSERT INTO bot_direct_messages VALUES (?, ?, ?, ?, ?)').run('dm-1', 'thread-1', role === 'sender' ? 'bot-1' : 'bot-2',role === 'sender' ? 'bot-2' : 'bot-1', 'Retained shared message',);- await expectDeletionRejected();+ await deleteBot();+ expect(sqlite.prepare("SELECT id FROM bot_profiles WHERE id = 'bot-1'").get()).toBeUndefined();+ expect(sqlite.prepare('SELECT content FROM bot_direct_messages').all()).toEqual([+ { content: 'Retained shared message' },+ ]);});});+ it('keeps inbound delegation targets until the final delete transaction', async () => {+ sqlite.prepare('INSERT INTO bot_delegations VALUES (?, ?, ?)').run('delegation-1', 'bot-2', 'bot-1');+ await h.tx!('bots.prepareProfileDeletion', { botId: 'bot-1' });+ expect(sqlite.prepare('SELECT target_bot_id FROM bot_delegations').pluck().get()).toBe('bot-1');+ await commitBotProfileDeletion({ botId: 'bot-1', sessionIds: [], keepTaskHistory: false });+ expect(sqlite.prepare('SELECT target_bot_id FROM bot_delegations').pluck().get()).toBeNull();+ });+it('atomically detaches kept transcripts and removes the Profile', async () => {await commitBotProfileDeletion({botId: 'bot-1',diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.tsindex c87381248a..0aa3f42091 100644--- a/apps/desktop/src/main/localDb/client/tx/types.ts+++ b/apps/desktop/src/main/localDb/client/tx/types.ts@@ -51,7 +51,8 @@ export type DbTxName =| 'bots.resumeLifecycle'| 'bots.archiveLifecycle'| 'bots.deleteProfile'- | 'bots.assertNoSharedHistory'+ | 'bots.prepareProfileDeletion'+ | 'bots.persistSessionPermission'| 'im.rotateSession'| 'wechatActivateBindingEpoch'| 'wechatCommitPollBatch'@@ -1215,7 +1216,8 @@ export type DbTxArgsByName = {'bots.resumeLifecycle': BotsLifecycleTransitionArgs;'bots.archiveLifecycle': BotsArchiveLifecycleArgs;'bots.deleteProfile': BotsDeleteProfileArgs;- 'bots.assertNoSharedHistory': { botId: string };+ 'bots.prepareProfileDeletion': { botId: string };+ 'bots.persistSessionPermission': { sessionId: string; mode: string };'im.rotateSession': ImRotateSessionArgs;wechatActivateBindingEpoch: WechatActivateBindingEpochArgs;wechatCommitPollBatch: WechatCommitPollBatchArgs;@@ -1293,7 +1295,8 @@ export type DbTxResultByName = {'bots.resumeLifecycle': undefined;'bots.archiveLifecycle': { sessions: number };'bots.deleteProfile': { sessionIds: string[]; status: 'archived' | 'deleted' };- 'bots.assertNoSharedHistory': undefined;+ 'bots.prepareProfileDeletion': undefined;+ 'bots.persistSessionPermission': { updated: boolean };'im.rotateSession': ImRotateSessionResult;wechatActivateBindingEpoch: WechatActivateBindingEpochResult;wechatCommitPollBatch: WechatCommitPollBatchResult;diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.tsindex bb98a3b122..e9580908d3 100644--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts@@ -3798,9 +3798,6 @@ describe('Bot Session task end-to-end runtime', () => {botId: 'bot-1', expectedCanonicalSessionId: null, expectedProfileVersion: 1,});const sqlite = h.sqlite!;- const before = sqlite.prepare("SELECT * FROM bot_profiles WHERE id = 'bot-a'").get();- const beforeSession = sqlite.prepare("SELECT * FROM sessions WHERE id = 'session-1'").get();- const beforeLink = sqlite.prepare("SELECT * FROM bot_session_links WHERE session_id = 'session-1'").get();let release!: () => void;const barrier = new Promise<void>((resolve) => { release = resolve; });let entered!: () => void;@@ -3808,7 +3805,7 @@ describe('Bot Session task end-to-end runtime', () => {const realTx = h.tx!;h.tx = async (name, args) => {const result = await realTx(name, args);- if (order === 'delete-first' && name === 'bots.assertNoSharedHistory') {+ if (order === 'delete-first' && name === 'bots.prepareProfileDeletion') {entered();await barrier;}@@ -3843,15 +3840,10 @@ describe('Bot Session task end-to-end runtime', () => {expect(sqlite.prepare('SELECT * FROM bot_direct_messages').all()).toEqual([]);} else {expect(firstResult).toMatchObject({ status: 'fulfilled', value: { ok: true } });- expect(secondResult).toMatchObject({ status: 'rejected', reason: { code: 'BOT_SHARED_HISTORY_REFERENCED' } });- expect(sqlite.prepare("SELECT * FROM bot_profiles WHERE id = 'bot-a'").get()).toEqual(before);- expect(sqlite.prepare("SELECT * FROM sessions WHERE id = 'session-1'").get()).toEqual(beforeSession);- expect(sqlite.prepare("SELECT * FROM bot_session_links WHERE session_id = 'session-1'").get()).toEqual(beforeLink);- expect(h.closeSession).not.toHaveBeenCalled();+ expect(secondResult, secondResult.status === 'rejected' ? String(secondResult.reason) : '').toMatchObject({ status: 'fulfilled', value: { status: 'deleted' } });+ expect(sqlite.prepare("SELECT id FROM bot_profiles WHERE id = 'bot-a'").get()).toBeUndefined();expect(sqlite.prepare('SELECT * FROM bot_direct_message_threads').all()).toHaveLength(1);expect(sqlite.prepare('SELECT * FROM bot_direct_messages').all()).toHaveLength(1);- await expect(lifecycle.run({ botId: 'bot-a', action: 'pause' })).resolves.toMatchObject({ status: 'paused' });- await expect(lifecycle.run({ botId: 'bot-a', action: 'resume' })).resolves.toMatchObject({ status: 'active' });}});diff --git a/apps/desktop/src/main/localDb/schema.ts b/apps/desktop/src/main/localDb/schema.tsindex b78b8b1c1c..9c82faee0a 100644--- a/apps/desktop/src/main/localDb/schema.ts+++ b/apps/desktop/src/main/localDb/schema.ts@@ -486,7 +486,7 @@ export const botDirectMessageThreads = sqliteTable('bot_direct_message_threads',{id: text('id').primaryKey(),- /** Local Bot ids or deviceId::botId addresses, lexically ordered. Lifecycle deletion guards shared history. */+ /** Local Bot ids or deviceId::botId addresses, lexically ordered. Deletion keeps these rows. */botAId: text('bot_a_id').notNull(),botBId: text('bot_b_id').notNull(),status: text('status', { enum: ['active', 'closed'] })diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.tsindex b729bc1fc6..be87643969 100644--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts@@ -141,8 +141,11 @@ export function tx(db: Database.Database, args: unknown): unknown {return botsArchiveLifecycle(db, txArgs);case 'bots.deleteProfile':return botsDeleteProfile(db, txArgs);- case 'bots.assertNoSharedHistory':- return assertBotHasNoSharedHistory(db, expectString(asRecord(txArgs, 'args').botId, 'botId'));+ case 'bots.prepareProfileDeletion':+ expectString(asRecord(txArgs, 'args').botId, 'botId');+ return undefined;+ case 'bots.persistSessionPermission':+ return botsPersistSessionPermission(db, txArgs);case 'im.rotateSession':return imRotateSession(db, txArgs);case 'wechatActivateBindingEpoch':@@ -1017,20 +1020,90 @@ function botsArchiveLifecycle(db: Database.Database, args: unknown): { sessions:})();}-/** Shared preflight and final transaction guard: deleting a profile must never cascade shared history. */-function assertBotHasNoSharedHistory(db: Database.Database, botId: string): void {- const sharedHistory = db.prepare(`SELECT 1 WHERE- EXISTS (SELECT 1 FROM bot_delegations- WHERE target_bot_id = ? OR (requesting_bot_id = ? AND target_bot_id IS NOT NULL))- OR EXISTS (SELECT 1 FROM bot_direct_message_threads- WHERE bot_a_id = ? OR bot_b_id = ?)- OR EXISTS (SELECT 1 FROM bot_direct_messages- WHERE sender_bot_id = ? OR recipient_bot_id = ?)`)- .get(botId, botId, botId, botId, botId, botId);- if (sharedHistory) throw Object.assign(- new Error('Bot 有共享委派或私聊历史,不能永久删除'),- { code: 'BOT_SHARED_HISTORY_REFERENCED' },- );+function tableColumns(db: Database.Database, table: string): Set<string> {+ const rows = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;+ return new Set(rows.map((row) => row.name));+}++/**+ * Keep the other teammate's records when this profile row goes away.+ * Delegation targets are foreign keys; null them before delete so cascade cannot+ * remove the requester's task. Direct messages are address text, not profile keys.+ */+function botsPersistSessionPermission(+ db: Database.Database,+ args: unknown,+): { updated: boolean } {+ const p = asRecord(args, 'bots.persistSessionPermission args');+ const sessionId = expectString(p.sessionId, 'sessionId');+ const mode = expectString(p.mode, 'mode');+ if (!['ask', 'default', 'acceptEdits', 'plan', 'auto', 'bypassPermissions'].includes(mode)) {+ throw Object.assign(new Error('invalid permission mode'), { code: 'INVALID_PARAMS' });+ }+ const profilePermission = mode === 'bypassPermissions' ? 'trusted' : mode === 'auto' ? 'auto' : mode === 'ask' ? 'ask' : null;+ return db.transaction(() => {+ const session = db.prepare('SELECT id FROM sessions WHERE id = ?').get(sessionId);+ if (!session) return { updated: false };+ if (!profilePermission) {+ db.prepare('UPDATE sessions SET permission_mode = ?, updated_at = ? WHERE id = ?')+ .run(mode, Date.now(), sessionId);+ return { updated: true };+ }+ const link = db.prepare(`SELECT bot_id AS botId FROM bot_session_links+ WHERE session_id = ? AND role = 'canonical' AND archived_at IS NULL`).get(sessionId) as { botId: string } | undefined;+ if (link) {+ const profile = db.prepare('SELECT current_version AS version FROM bot_profiles WHERE id = ?')+ .get(link.botId) as { version: number } | undefined;+ const version = profile+ ? db.prepare('SELECT capabilities_json AS json FROM bot_profile_versions WHERE bot_id = ? AND version = ?')+ .get(link.botId, profile.version) as { json: string } | undefined+ : undefined;+ if (!profile || !version) {+ throw Object.assign(new Error('Bot profile version missing'), { code: 'PRECONDITION_FAILED' });+ }+ let config: Record<string, unknown>;+ try {+ const parsed = JSON.parse(version.json) as unknown;+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('unreadable');+ config = parsed as Record<string, unknown>;+ } catch {+ throw Object.assign(new Error('Bot profile capabilities are unreadable'), { code: 'PRECONDITION_FAILED' });+ }+ if (config.permissions !== profilePermission) {+ const next = JSON.stringify({ ...config, permissions: profilePermission });+ const changed = db.prepare(`UPDATE bot_profile_versions SET capabilities_json = ?+ WHERE bot_id = ? AND version = ? AND capabilities_json = ?`).run(next, link.botId, profile.version, version.json);+ if (changed.changes !== 1) {+ throw Object.assign(new Error('Bot profile changed while saving permission'), { code: 'PRECONDITION_FAILED' });+ }+ }+ }+ db.prepare('UPDATE sessions SET permission_mode = ?, updated_at = ? WHERE id = ?')+ .run(mode, Date.now(), sessionId);+ return { updated: true };+ })();+}++function detachSharedHistoryForProfileDeletion(db: Database.Database, botId: string): void {+ const delegationColumns = tableColumns(db, 'bot_delegations');+ if (delegationColumns.has('target_bot_id')) {+ db.prepare('UPDATE bot_delegations SET target_bot_id = NULL WHERE target_bot_id = ?').run(botId);+ }+ const messageColumns = tableColumns(db, 'bot_direct_messages');+ const profileColumns = tableColumns(db, 'bot_profiles');+ if (!messageColumns.has('sender_bot_id') || !messageColumns.has('sender_name') || !profileColumns.has('display_name')) return;+ const profile = db.prepare('SELECT display_name AS name FROM bot_profiles WHERE id = ?').get(botId) as+ { name?: string } | undefined;+ const name = profile?.name?.trim();+ if (!name) return;+ db.prepare(`UPDATE bot_direct_messages+ SET sender_name = ?+ WHERE sender_bot_id = ? AND (sender_name IS NULL OR sender_name = '')`).run(name, botId);+ if (messageColumns.has('recipient_bot_id') && messageColumns.has('recipient_name')) {+ db.prepare(`UPDATE bot_direct_messages+ SET recipient_name = ?+ WHERE recipient_bot_id = ? AND (recipient_name IS NULL OR recipient_name = '')`).run(name, botId);+ }}function botsDeleteProfile(@@ -1058,9 +1131,9 @@ function botsDeleteProfile({ code: 'PRECONDITION_FAILED' },);- // Profile foreign keys cascade into history shared with surviving Bots.- // Check both delegation roles and actual message references before any mutation.- assertBotHasNoSharedHistory(db, botId);+ // Profile foreign keys cascade into delegations that target this Bot.+ // Detach those references first; direct-message rows are not profile keys.+ detachSharedHistoryForProfileDeletion(db, botId);const allSessionIds = [...new Set(sessionIds)];if (sessionIds.length > 0) {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/botLifecycleService.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/botLifecycleService.test.tsindex 58c725a278..9fa8b17c6f 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/botLifecycleService.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/botLifecycleService.test.ts@@ -325,24 +325,19 @@ describe('Bot lifecycle coordinator', () => {"INSERT INTO bot_delegations VALUES ('shared', 'bot-1', 'other-bot')","INSERT INTO bot_direct_message_threads VALUES ('shared', 'bot-1', 'other-bot')","INSERT INTO bot_direct_messages VALUES ('shared', 'other-bot', 'bot-1')",- ])('preserves the active Bot and canonical task when shared history blocks deletion: %s', async (insert) => {+ ])('deletes the Bot without clearing existing shared-history rows: %s', async (insert) => {sqlite.exec(insert);- const beforeProfile = row(sqlite, 'bot_profiles', 'bot-1');- const beforeSession = row(sqlite, 'sessions', 'canonical');- const beforeLink = row(sqlite, 'bot_session_links', 'link-canonical');+ const sharedRows = sqlite.prepare('SELECT * FROM bot_delegations').all().length+ + sqlite.prepare('SELECT * FROM bot_direct_message_threads').all().length+ + sqlite.prepare('SELECT * FROM bot_direct_messages').all().length;await expect(service().run({botId: 'bot-1', action: 'delete', confirmName: 'Helper', keepTaskHistory: true,- })).rejects.toMatchObject({ code: 'BOT_SHARED_HISTORY_REFERENCED' });- expect(row(sqlite, 'bot_profiles', 'bot-1')).toEqual(beforeProfile);- expect(row(sqlite, 'sessions', 'canonical')).toEqual(beforeSession);- expect(row(sqlite, 'bot_session_links', 'link-canonical')).toEqual(beforeLink);- expect(closeSession).not.toHaveBeenCalled();- expect(cancelDelegationsForBot).not.toHaveBeenCalled();- expect(deleteProfileAndDetachSessions).not.toHaveBeenCalled();- expect(sqlite.prepare('SELECT * FROM bot_lifecycle_events').all()).toEqual([]);- // Its existing runtime was never closed, and normal lifecycle controls remain usable.- await expect(service().run({ botId: 'bot-1', action: 'pause' })).resolves.toMatchObject({ status: 'paused' });- await expect(service().run({ botId: 'bot-1', action: 'resume' })).resolves.toMatchObject({ status: 'active' });+ })).resolves.toMatchObject({ status: 'deleted' });+ expect(sqlite.prepare("SELECT id FROM bot_profiles WHERE id = 'bot-1'").get()).toBeUndefined();+ expect(sqlite.prepare('SELECT * FROM bot_delegations').all().length+ + sqlite.prepare('SELECT * FROM bot_direct_message_threads').all().length+ + sqlite.prepare('SELECT * FROM bot_direct_messages').all().length).toBe(sharedRows);+ expect(deleteProfileAndDetachSessions).toHaveBeenCalled();});it('pauses, archives and detaches sessions when permanently deleting a Bot', async () => {diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionPermissionPersistence.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionPermissionPersistence.test.tsnew file mode 100644index 0000000000..5ede4fcd77--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionPermissionPersistence.test.ts@@ -0,0 +1,82 @@+import Database from 'better-sqlite3';+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { tx as runWorkerTx } from '../../localDb/worker/opHandlers/tx.js';++const h = vi.hoisted(() => ({+ sqlite: null as Database.Database | null,+}));++vi.mock('../../localDb/client/current.js', () => ({+ getDbClient: () => ({+ tx: (name: string, args: unknown) => runWorkerTx(h.sqlite!, { name, args } as never),+ }),+}));++import { persistPermissionModeWithoutRuntime, profilePermissionForSessionMode } from '../sessionPermissionPersistence.js';++function createDatabase(): Database.Database {+ const sqlite = new Database(':memory:');+ sqlite.exec(`+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY,+ permission_mode TEXT NOT NULL,+ updated_at INTEGER NOT NULL+ );+ CREATE TABLE bot_profiles (+ id TEXT PRIMARY KEY,+ current_version INTEGER NOT NULL+ );+ CREATE TABLE bot_session_links (+ bot_id TEXT NOT NULL,+ session_id TEXT NOT NULL,+ role TEXT NOT NULL,+ archived_at INTEGER+ );+ CREATE TABLE bot_profile_versions (+ bot_id TEXT NOT NULL,+ version INTEGER NOT NULL,+ capabilities_json TEXT NOT NULL+ );+ INSERT INTO sessions VALUES ('chat', 'ask', 1);+ INSERT INTO bot_profiles VALUES ('bot-1', 2);+ INSERT INTO bot_session_links VALUES ('bot-1', 'chat', 'canonical', NULL);+ INSERT INTO bot_profile_versions VALUES ('bot-1', 2, '{"permissions":"ask","memory":true}');+ `);+ return sqlite;+}++describe('permission persistence without a live runtime', () => {+ let sqlite: Database.Database;++ beforeEach(() => {+ sqlite = createDatabase();+ h.sqlite = sqlite;+ });++ it('maps only the teammate permission values', () => {+ expect(profilePermissionForSessionMode('bypassPermissions')).toBe('trusted');+ expect(profilePermissionForSessionMode('acceptEdits')).toBeNull();+ });++ it('writes the session and the canonical profile together', async () => {+ await expect(persistPermissionModeWithoutRuntime('chat', 'auto')).resolves.toBe(true);+ expect(sqlite.prepare('SELECT permission_mode FROM sessions WHERE id = ?').pluck().get('chat')).toBe('auto');+ expect(JSON.parse(sqlite.prepare('SELECT capabilities_json FROM bot_profile_versions').pluck().get() as string))+ .toMatchObject({ permissions: 'auto', memory: true });+ });++ it('does not report success when the session row is missing', async () => {+ await expect(persistPermissionModeWithoutRuntime('missing', 'ask')).resolves.toBe(false);+ expect(sqlite.prepare('SELECT permission_mode FROM sessions').pluck().get()).toBe('ask');+ });++ it('does not replace a newer profile version with a stale capabilities snapshot', async () => {+ sqlite.prepare('UPDATE bot_profiles SET current_version = 3 WHERE id = ?').run('bot-1');+ sqlite.prepare('INSERT INTO bot_profile_versions VALUES (?, ?, ?)').run('bot-1', 3, '{"permissions":"ask","memory":false}');+ await expect(persistPermissionModeWithoutRuntime('chat', 'auto')).resolves.toBe(true);+ expect(JSON.parse(sqlite.prepare('SELECT capabilities_json FROM bot_profile_versions WHERE version = 3').pluck().get() as string))+ .toEqual({ permissions: 'auto', memory: false });+ expect(JSON.parse(sqlite.prepare('SELECT capabilities_json FROM bot_profile_versions WHERE version = 2').pluck().get() as string))+ .toEqual({ permissions: 'ask', memory: true });+ });+});diff --git a/apps/desktop/src/main/maker-ipc/botLifecycleService.ts b/apps/desktop/src/main/maker-ipc/botLifecycleService.tsindex 5c6809ab9d..5068966b19 100644--- a/apps/desktop/src/main/maker-ipc/botLifecycleService.ts+++ b/apps/desktop/src/main/maker-ipc/botLifecycleService.ts@@ -312,10 +312,10 @@ export function createBotLifecycleService(deps: BotLifecycleServiceDeps) {if (profile.status === 'deleting') {throwIpcError('PRECONDITION_FAILED', 'Bot 已在永久删除流程中');}- // Reject known shared history before pausing live work or archiving its canonical link.- // The profile lock excludes concurrent shared-history writers until deletion finishes.- // The final transaction retains its own guard as the database safety boundary.- await getDbClient().tx('bots.assertNoSharedHistory', { botId: request.botId });+ // Hold the profile lock before pausing so a concurrent message cannot land halfway.+ // Active delegations are cancelled while their target id is still intact. Historical+ // foreign keys are detached only inside the final delete transaction.+ await getDbClient().tx('bots.prepareProfileDeletion', { botId: request.botId });assertOwnerUnchanged();let preparationWarnings: string[] = [];if (profile.status !== 'archived') {diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex cd84d57653..b62bbc38d5 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -446,6 +446,7 @@ import {} from './botDirectMessageService.js';import { restartBotRuntime } from './botRuntimeRestart.js';import { registerBotLifecycleHandlers } from './botLifecycleService.js';+import { isSessionPermissionMode, persistPermissionModeWithoutRuntime } from './sessionPermissionPersistence.js';import { updateBotRoutineLifecycle } from '../routines/service.js';import {createBotCompactRuntimeRefreshCoordinator,@@ -17448,14 +17449,20 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)throwIpcError('INVALID_PARAMS', 'sessionId + mode required');}await assertReviewSettingsUnlocked(sessionId);+ if (!isSessionPermissionMode(mode)) {+ throwIpcError('INVALID_PARAMS', 'invalid permission mode');+ }const sess = maker.getSession(sessionId);if (!sess) {- log.debug('set-permission-mode: session not found, no-op', { sessionId });- return;+ const persisted = await persistPermissionModeWithoutRuntime(sessionId, mode);+ if (!persisted) throwIpcError('NOT_FOUND', 'session not found');+ broadcastSessionPatched(sessionId, { permissionMode: mode });+ return true;}await sess.setPermissionMode(mode as 'ask' | 'default' | 'acceptEdits' | 'plan' | 'auto' | 'bypassPermissions',);+ return true;},);diff --git a/apps/desktop/src/main/maker-ipc/sessionPermissionPersistence.ts b/apps/desktop/src/main/maker-ipc/sessionPermissionPersistence.tsnew file mode 100644index 0000000000..89e30eb774--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/sessionPermissionPersistence.ts@@ -0,0 +1,35 @@+import { getDbClient } from '../localDb/client/current.js';++const SESSION_PERMISSION_MODES = new Set([+ 'ask',+ 'default',+ 'acceptEdits',+ 'plan',+ 'auto',+ 'bypassPermissions',+]);++export function isSessionPermissionMode(mode: string): boolean {+ return SESSION_PERMISSION_MODES.has(mode);+}++/** Profile stores only the three teammate permission values. Other session modes stay on the session row. */+export function profilePermissionForSessionMode(mode: string): 'ask' | 'auto' | 'trusted' | null {+ if (mode === 'bypassPermissions') return 'trusted';+ if (mode === 'auto') return 'auto';+ if (mode === 'ask') return 'ask';+ return null;+}++/**+ * Persist a permission change when the Maker runtime is not loaded.+ * Returns false only when the mode is invalid or the session row does not exist.+ */+export async function persistPermissionModeWithoutRuntime(+ sessionId: string,+ mode: string,+): Promise<boolean> {+ if (!isSessionPermissionMode(mode)) return false;+ const saved = await getDbClient().tx('bots.persistSessionPermission', { sessionId, mode });+ return saved.updated;+}diff --git a/apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx b/apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsxindex 42403127c8..e42a49004b 100644--- a/apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx+++ b/apps/desktop/src/renderer/features/bots/BotDeleteDialog.tsx@@ -75,7 +75,7 @@ export function BotDeleteDialog({</div>{failed ? (<p className="mt-3 text-11 text-[var(--text-danger)]" role="alert">- {t('bots.lifecycle.actionFailed')}+ {t('bots.lifecycle.deleteFailed')}</p>) : null}<div className="mt-5 flex justify-end gap-2">diff --git a/apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx b/apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsxindex 128b40dc28..345f9ffbef 100644--- a/apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx+++ b/apps/desktop/src/renderer/features/bots/BotLifecycleSettings.tsx@@ -141,15 +141,6 @@ export function BotLifecycleSettings({{t('bots.lifecycle.deleteTitle')}</button></div>- <p className="mt-2 px-3 text-12 leading-5 text-[var(--text-secondary)]">- {t(- isPaused- ? 'bots.lifecycle.pausedDescription'- : isArchived- ? 'bots.lifecycle.stoppedDescription'- : 'bots.lifecycle.restartDescription',- )}- </p>{restarted ? (<p className="mt-3 text-12 text-[var(--text-secondary)]" role="status">{t('bots.lifecycle.restarted')}@@ -173,9 +164,6 @@ export function BotLifecycleSettings({{mode !== 'actions' ? (<><div className="px-3 pt-3">- <p className="mt-1 text-11 leading-5 text-[var(--text-tertiary)]">- {t('bots.historySearch.description')}- </p><formclassName="mt-3 flex gap-2"onSubmit={(event) => {@@ -187,7 +175,7 @@ export function BotLifecycleSettings({aria-label={t('bots.historySearch.title')}value={query}onChange={(event) => setQuery(event.target.value)}- placeholder={t('bots.historySearch.placeholder')}+ placeholder={t('bots.historySearch.search')}className="h-9 min-w-0 flex-1 rounded-full border border-[var(--border-default)] bg-[var(--surface)] px-3 text-12 text-[var(--text-primary)] outline-none focus:ring-2 focus:ring-[var(--focus-ring-soft)]"/><Buttondiff --git a/apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx b/apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsxindex dbcf43afee..4c4abcbdc0 100644--- a/apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx+++ b/apps/desktop/src/renderer/features/bots/BotModelChainEditor.tsx@@ -244,7 +244,6 @@ export function BotModelChainEditor({{t('bots.model.restoreDefault')}</Button>) : null}- <p className="text-11 leading-5">{t('bots.modelChain.description')}</p></div>) : null}</details>diff --git a/apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx b/apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsxindex 6257509c91..b7ea2a7874 100644--- a/apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx+++ b/apps/desktop/src/renderer/features/bots/BotsGlobalSettingsSection.tsx@@ -59,17 +59,9 @@ export function BotsGlobalSettingsSection() {<h2 className="text-16 font-medium leading-[1.2] text-[var(--settings-section-title)]">{t('bots.globalSettings.title')}</h2>- <p className="-mt-2 text-12 leading-[1.5] text-[var(--settings-section-sublabel)] opacity-70">- {t('bots.globalSettings.description')}- </p><div className={cn(CARD_CLASS, 'flex flex-col gap-4')}>- <div>- <p className={ROW_LABEL_CLASS}>{t('bots.modelLabel')}</p>- <p className={cn('mt-1', ROW_HINT_CLASS)}>- {t('bots.globalSettings.description')}- </p>- </div>+ <p className={ROW_LABEL_CLASS}>{t('bots.modelLabel')}</p><fieldset disabled={pending} aria-busy={pending} className="min-w-0"><BotModelChainEditordisabled={pending}@@ -80,15 +72,12 @@ export function BotsGlobalSettingsSection() {: undefined}/></fieldset>- <p className={ROW_HINT_CLASS}>{t('bots.globalSettings.restoreHint')}</p>{notice ? (<p className={ROW_HINT_CLASS} role="status">{notice}</p>) : null}</div>-- <p className={ROW_HINT_CLASS}>{t('bots.globalSettings.rosterNote')}</p></div>);}diff --git a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsxindex 7803c6cb9e..7febcb44da 100644--- a/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx+++ b/apps/desktop/src/renderer/features/bots/BotsHomeView.tsx@@ -579,15 +579,9 @@ export function BotSettings({) : null}{page === 'advanced' ? (<div className="mt-4 flex flex-col gap-5 px-3">- <div className="flex items-start gap-3">- <FolderOpen size={16} className="mt-0.5 shrink-0 text-[var(--text-tertiary)]" />+ <div className="flex items-center gap-3">+ <FolderOpen size={16} className="shrink-0 text-[var(--text-tertiary)]" /><div className="min-w-0 flex-1">- <p className="text-12 leading-5 text-[var(--text-secondary)]">- {t('bots.homeFolder.description')}- </p>- <p className="mt-1 break-words text-11 leading-5 text-[var(--text-tertiary)] [overflow-wrap:anywhere]">- {t('bots.homeFolder.contents')}- </p><Buttonvariant="secondary"size="lg"@@ -602,7 +596,6 @@ export function BotSettings({setFolderError(result.error ?? t('bots.homeFolder.openFailed'));});}}- className="mt-3">{t('bots.homeFolder.open')}</Button>diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 7d03766171..e67c0c412b 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -7718,6 +7718,7 @@"deleteDescription": "Deleting {{name}} permanently removes the teammate’s profile, memory, working directory, channel connections and automated tasks. Task history and separate worktrees are retained.","working": "Updating…","actionFailed": "The action did not finish. Try again shortly.",+ "deleteFailed": "The teammate was not deleted.","restart": "Restart teammate","restartDescription": "Stop the current run and prepare a fresh start. Conversation history, memories, and files are kept.","restarting": "Restarting…",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex f71aef2e75..bc9ffd3bfd 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -7716,6 +7716,7 @@"deleteDescription": "{{name}} を削除すると、プロフィール、記憶、作業ディレクトリ、チャンネル接続、自動化タスクが完全に削除されます。タスク履歴と独立したworktreeは保持されます。","working": "更新中…","actionFailed": "操作が完了しませんでした。しばらくしてから再試行してください。",+ "deleteFailed": "削除は完了しませんでした。","restart": "チームメイトを再起動","restartDescription": "現在の実行を停止して再開の準備をします。会話履歴、メモリ、ファイルは保持されます。","restarting": "再起動中…",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex b6912ef354..2710291782 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -7716,6 +7716,7 @@"deleteDescription": "{{name}}을(를) 삭제하면 프로필, 메모리, 작업 디렉터리, 채널 연결 및 자동화 작업이 영구적으로 삭제됩니다. 작업 기록과 별도의 worktree는 유지됩니다.","working": "업데이트 중…","actionFailed": "작업이 완료되지 않았습니다. 잠시 후 다시 시도하세요.",+ "deleteFailed": "삭제가 완료되지 않았습니다.","restart": "팀원 다시 시작","restartDescription": "현재 실행을 중지하고 새로 시작할 준비를 합니다. 대화 기록, 메모리, 파일은 유지됩니다.","restarting": "다시 시작하는 중…",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex a939b30fb3..9482302cf5 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -7716,6 +7716,7 @@"deleteDescription": "删除 {{name}} 后,伙伴的资料、记忆、工作目录、通道连接与自动化任务将被移除,无法撤销。任务历史与独立 worktree会保留。","working": "正在更新…","actionFailed": "操作未完成,请稍后重试。",+ "deleteFailed": "删除没有完成。","restart": "重启伙伴","restartDescription": "停止当前运行并重新准备,保留对话记录、记忆和文件。","restarting": "正在重启…",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 17cd9ad7bb..625c2722b1 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -7716,6 +7716,7 @@"deleteDescription": "刪除 {{name}} 後,夥伴的資料、記憶、工作目錄、通道連線與自動化任務將被移除,無法復原。任務歷史與獨立 worktree會保留。","working": "正在更新…","actionFailed": "操作未完成,請稍後重試。",+ "deleteFailed": "刪除沒有完成。","restart": "重新啟動夥伴","restartDescription": "停止目前執行並重新準備,保留對話記錄、記憶和檔案。","restarting": "正在重新啟動…",diff --git a/apps/mobile/src/i18n/locales/en/devices.json b/apps/mobile/src/i18n/locales/en/devices.jsonindex 9825165ceb..293db288cc 100644--- a/apps/mobile/src/i18n/locales/en/devices.json+++ b/apps/mobile/src/i18n/locales/en/devices.json@@ -861,6 +861,7 @@"continueEditing": "Continue Editing","discard": "Discard Changes","invalid": "Check the name, instructions, and trigger settings, then save again.",+ "failed": "The automation change did not finish.","everyMinutes": "Every {{count}} minutes","everyMinutes_one": "Every {{count}} minute","everyMinutes_other": "Every {{count}} minutes",@@ -1006,6 +1007,7 @@"offline": "Reconnect to {{deviceName}} to continue. Your edits are retained.","hostUpgrade": "Update Cindy on {{deviceName}} and retry, or edit this teammate’s settings there.","readFailed": "Couldn’t confirm the latest state. Refresh before retrying; the action may already have completed. Your edits are retained.",+ "deleteFailed": "The teammate was not deleted.","artifactsEmpty": "No artifacts yet. Ask your teammate to create something.","openSourceTask": "Open Source Session","modelFollowsDefault": "Follow the default model chain",diff --git a/apps/mobile/src/i18n/locales/ja/devices.json b/apps/mobile/src/i18n/locales/ja/devices.jsonindex 797320b5d4..e5b680c133 100644--- a/apps/mobile/src/i18n/locales/ja/devices.json+++ b/apps/mobile/src/i18n/locales/ja/devices.json@@ -861,6 +861,7 @@"continueEditing": "編集を続ける","discard": "変更を破棄","invalid": "名前、実行内容、トリガー設定を確認して、もう一度保存してください。",+ "failed": "自動化の操作は完了しませんでした。","everyMinutes": "{{count}} 分ごと","everyMinutes_one": "{{count}} 分ごと","everyMinutes_other": "{{count}} 分ごと",@@ -1006,6 +1007,7 @@"offline": "続けるには {{deviceName}} に再接続してください。編集内容は保持されています。","hostUpgrade": "{{deviceName}} の Cindy を更新して再試行するか、そのパソコンでチームメイトの設定を編集してください。","readFailed": "最新の状態を確認できませんでした。更新してから再試行してください。操作は完了している可能性があります。編集内容は保持されています。",+ "deleteFailed": "削除は完了しませんでした。","artifactsEmpty": "成果物はまだありません。チームメイトに作成を頼んでみましょう。","openSourceTask": "元のセッションを開く","modelFollowsDefault": "現在のデフォルトモデル候補を使用",diff --git a/apps/mobile/src/i18n/locales/ko/devices.json b/apps/mobile/src/i18n/locales/ko/devices.jsonindex 159f73a0ef..8ff409ed4a 100644--- a/apps/mobile/src/i18n/locales/ko/devices.json+++ b/apps/mobile/src/i18n/locales/ko/devices.json@@ -861,6 +861,7 @@"continueEditing": "계속 편집","discard": "변경 사항 버리기","invalid": "이름, 실행 지침, 트리거 설정을 확인한 후 다시 저장하세요.",+ "failed": "자동화 작업을 완료하지 못했습니다.","everyMinutes": "{{count}}분마다","everyMinutes_one": "{{count}}분마다","everyMinutes_other": "{{count}}분마다",@@ -1006,6 +1007,7 @@"offline": "계속하려면 {{deviceName}}에 다시 연결하세요. 편집 내용은 유지됩니다.","hostUpgrade": "{{deviceName}}의 Cindy를 업데이트하고 다시 시도하거나 해당 컴퓨터에서 팀원 설정을 편집하세요.","readFailed": "최신 상태를 확인하지 못했습니다. 새로 고친 후 다시 시도하세요. 작업이 이미 완료되었을 수 있습니다. 편집 내용은 유지됩니다.",+ "deleteFailed": "삭제가 완료되지 않았습니다.","artifactsEmpty": "아직 결과물이 없습니다. 팀원에게 만들어 달라고 요청하세요.","openSourceTask": "원본 세션 열기","modelFollowsDefault": "현재 기본 모델 후보 사용",diff --git a/apps/mobile/src/i18n/locales/zh-CN/devices.json b/apps/mobile/src/i18n/locales/zh-CN/devices.jsonindex cac9d2d7d9..b262df9a61 100644--- a/apps/mobile/src/i18n/locales/zh-CN/devices.json+++ b/apps/mobile/src/i18n/locales/zh-CN/devices.json@@ -861,6 +861,7 @@"continueEditing": "继续编辑","discard": "放弃更改","invalid": "请检查名称、执行说明和触发设置后重新保存。",+ "failed": "自动化操作没有完成。","everyMinutes": "每 {{count}} 分钟","everyMinutes_one": "每 {{count}} 分钟","everyMinutes_other": "每 {{count}} 分钟",@@ -1006,6 +1007,7 @@"offline": "请重新连接 {{deviceName}} 后继续,未保存的编辑已保留。","hostUpgrade": "请更新 {{deviceName}} 上的 Cindy 后重试,或在那台电脑上编辑伙伴设置。","readFailed": "暂时无法确认最新状态。请刷新后再试,操作可能已经完成。你的编辑已保留。",+ "deleteFailed": "删除没有完成。","artifactsEmpty": "还没有成果,可以让伙伴创作一些内容。","openSourceTask": "打开来源任务","modelFollowsDefault": "跟随当前默认模型链",diff --git a/apps/mobile/src/i18n/locales/zh-TW/devices.json b/apps/mobile/src/i18n/locales/zh-TW/devices.jsonindex 2bd748131d..0d6e51ae80 100644--- a/apps/mobile/src/i18n/locales/zh-TW/devices.json+++ b/apps/mobile/src/i18n/locales/zh-TW/devices.json@@ -861,6 +861,7 @@"continueEditing": "繼續編輯","discard": "放棄變更","invalid": "請檢查名稱、執行說明和觸發設定後重新儲存。",+ "failed": "自動化操作沒有完成。","everyMinutes": "每 {{count}} 分鐘","everyMinutes_one": "每 {{count}} 分鐘","everyMinutes_other": "每 {{count}} 分鐘",@@ -1006,6 +1007,7 @@"offline": "請重新連接 {{deviceName}} 後繼續,未儲存的編輯已保留。","hostUpgrade": "請更新 {{deviceName}} 上的 Cindy 後重試,或在那台電腦上編輯夥伴設定。","readFailed": "暫時無法確認最新狀態。請重新整理後再試,操作可能已經完成。你的編輯已保留。",+ "deleteFailed": "刪除沒有完成。","artifactsEmpty": "還沒有成果,可以讓夥伴創作一些內容。","openSourceTask": "開啟來源任務","modelFollowsDefault": "跟隨目前預設模型鏈",diff --git a/apps/mobile/src/session/CompanionAutomationSheet.tsx b/apps/mobile/src/session/CompanionAutomationSheet.tsxindex f8f87da126..3f1a4e6d41 100644--- a/apps/mobile/src/session/CompanionAutomationSheet.tsx+++ b/apps/mobile/src/session/CompanionAutomationSheet.tsx@@ -10,7 +10,6 @@ import { useAuth } from '@/auth/AuthContext';import { useDeviceLink } from '@/device-link/DeviceLinkContext';import { startFocusedTopicSubscription } from '@/device-link/focusedTopicSubscription';import { getRemoteResource, invokeRemoteResourceAction } from '@/device-link/remoteResources';-import { formatRemoteError } from '@/device-link/remoteStatus';import { CompanionChoice } from './CompanionChoice';import { useTheme, useThemedStyles, type ThemeColors } from '@/theme';import { fontWeight, radius, spacing, typeScale, lineHeight } from '@/theme/tokens';@@ -19,6 +18,22 @@ import { CompanionAutomationNativeView } from './CompanionAutomationNativeView';import { useRoutineCronFields } from './useRoutineCronFields';import { emptyRoutineDefinition, getRoutineActionId, parseRoutineDetail, parseRoutineSummaries, routineDraftValid, type RoutineDefinition, type RoutineDetail, type RoutineSummary, type RoutineTrigger } from './companionRoutines';+function automationFailure(error: unknown, tr: (key: string) => string): string {+ const code = typeof (error as { code?: unknown } | null)?.code === 'string'+ ? (error as { code: string }).code+ : '';+ const text = error instanceof Error ? error.message : String(error);+ if (code === 'unsupported' || code === 'CHANNEL_NOT_ALLOWED' || text.includes('CHANNEL_NOT_ALLOWED')) return tr('unsupported');+ if (code === 'DEVICE_OFFLINE' || code === 'NOT_CONNECTED' || text.includes('DEVICE_OFFLINE') || text.includes('NOT_CONNECTED')) return tr('offline');+ // A host validation sentence is the actionable reason. Raw codes and JSON stay behind the localized summary.+ if (text && !text.startsWith('[') && !text.startsWith('{') && !/^[A-Z0-9_]+$/.test(text)) return text;+ return tr('failed');+}++function unsupportedAutomationError(): Error {+ return Object.assign(new Error('unsupported'), { code: 'unsupported' });+}+export function CompanionAutomationSheet({ visible, onClose, collectionId, botId, deviceId, deviceName, online }: {visible: boolean; onClose(): void; collectionId: string; botId: string; deviceId: string; deviceName: string; online: boolean;}) {@@ -128,7 +143,7 @@ export function CompanionAutomationSheet({ visible, onClose, collectionId, botIdlet runRevision = detail?.revision ?? 0;if (actionId === 'routine-run' && dirty) {const saveId = getRoutineActionId(resource, 'routine-save');- if (!saveId) throw new Error(tr('unsupported'));+ if (!saveId) throw unsupportedAutomationError();await invokeRemoteResourceAction(invoke, { deviceId, deviceName }, { collectionId, resourceRef: resource.ref, actionId: saveId,input: { revision: runRevision, definition: draft } }, i18n.language);if (!valid(scope, page)) return;@@ -141,7 +156,7 @@ export function CompanionAutomationSheet({ visible, onClose, collectionId, botIdsetResource(runResource); setDetail(next); runRevision = next.revision;}const nextCapability = getRoutineActionId(runResource, actionId);- if (!nextCapability) throw new Error(tr('unsupported'));+ if (!nextCapability) throw unsupportedAutomationError();await invokeRemoteResourceAction(invoke, { deviceId, deviceName }, {collectionId, resourceRef: runResource.ref, actionId: nextCapability,input: { revision: runRevision, requestId: requestId.current,@@ -150,7 +165,7 @@ export function CompanionAutomationSheet({ visible, onClose, collectionId, botIdif (!valid(scope, page)) return;if (actionId === 'routine-run') { await load(); }else open(null);- } catch (e) { if (valid(scope, page)) setError(formatRemoteError(e)); }+ } catch (e) { if (valid(scope, page)) setError(automationFailure(e, tr)); }finally { if (operationGeneration.current === operation) { inFlight.current = false; if (current.current.identity === scope) setBusy(false); } }};const button = (label: string, onPress: () => void, destructive = false, disabled = false) => (diff --git a/apps/mobile/src/session/CompanionProfileNativeView.ios.tsx b/apps/mobile/src/session/CompanionProfileNativeView.ios.tsxindex 3fca5833b6..368fd7a89e 100644--- a/apps/mobile/src/session/CompanionProfileNativeView.ios.tsx+++ b/apps/mobile/src/session/CompanionProfileNativeView.ios.tsx@@ -62,7 +62,7 @@ export function CompanionProfileNativeView(p: CompanionProfileNativeViewProps) {return <ComposerSheet visible={p.visible} title={p.title} onClose={p.onClose} onClosed={p.onClosed} onBack={p.onBack}nativeContent preventDismiss={p.dirty || p.busy || !!p.confirmation} testID="companionProfile">{!p.online ? note(tr('offline')) : null}- {p.error ? <>{note(tr('readFailed'), true)}<Section>{action(t('devices.resources.retry'), p.onRetry, !p.online)}{p.dirty ? action(t('devices.companions.automation.discard'), () => p.onDiscard(false), false, true) : null}</Section></> : null}+ {p.error ? <>{note(p.errorLabel || tr('readFailed'), true)}<Section>{action(t('devices.resources.retry'), p.onRetry, !p.online)}{p.dirty ? action(t('devices.companions.automation.discard'), () => p.onDiscard(false), false, true) : null}</Section></> : null}{p.conflict ? <>{note(tr('changed'), true)}<Section>{action(tr('discardAndReload'), () => p.onDiscard(true), false, true)}</Section></> : null}{p.receipt ? note(p.receipt) : null}{p.deleted ? <Section>{action(t('shared.closePanel'), p.onClose)}</Section> : p.confirmation?.action?.confirmation ? <>diff --git a/apps/mobile/src/session/CompanionProfileNativeView.tsx b/apps/mobile/src/session/CompanionProfileNativeView.tsxindex 664bea08c6..017d1ccedf 100644--- a/apps/mobile/src/session/CompanionProfileNativeView.tsx+++ b/apps/mobile/src/session/CompanionProfileNativeView.tsx@@ -5,7 +5,7 @@ export interface CompanionProfileNativeViewProps {visible: boolean; title: string; name: string; page: string; deviceId: string; deviceName: string;resource: RemoteResource | null; data: CompanionProfileData | null; editor: CompanionProfileData | null;panel?: ProfilePanel; values: ProfileValues; busy: boolean; online: boolean; dirty: boolean;- loading: boolean; error: boolean; conflict: boolean; receipt: string | null;+ loading: boolean; error: boolean; errorLabel?: string; conflict: boolean; receipt: string | null;confirmation: ProfilePanel | null; deleted: boolean; artifacts: ReactNode; models: ReactNode;onClose(): void; onClosed?(): void; onBack?(): void; onOpen(page: string): void;onChange(values: ProfileValues): void; onSubmit(panel: ProfilePanel, confirmed?: boolean): void;diff --git a/apps/mobile/src/session/CompanionProfileSheet.tsx b/apps/mobile/src/session/CompanionProfileSheet.tsxindex b372d0fe43..f45067175b 100644--- a/apps/mobile/src/session/CompanionProfileSheet.tsx+++ b/apps/mobile/src/session/CompanionProfileSheet.tsx@@ -67,6 +67,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {const [editing, setEditing] = useState(false);const [busy, setBusy] = useState(false);const [error, setError] = useState(false);+ const [deleteFailure, setDeleteFailure] = useState(false);const [conflict, setConflict] = useState<{ page: string; next: CompanionProfileData } | null>(null);const [receipt, setReceipt] = useState<RemoteText | null>(null);const [confirmation, setConfirmation] = useState<ProfilePanel | null>(null);@@ -93,6 +94,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {const started = binding;const sequence = ++generation.current;setError(false);+ setDeleteFailure(false);try {const next = await read();if (current.current === started && generation.current === sequence) {@@ -106,7 +108,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {}}, [binding, read]);useEffect(() => {- setModelStage('profile'); setConflict(null); setEditor(null); setEditorPanel(null); setEditorLoading(false); setData(null); setPage('home'); setValues({}); setReceipt(null); setConfirmation(null); setDeleted(false); setError(false); setEditing(false); setBusy(false);+ setModelStage('profile'); setConflict(null); setEditor(null); setEditorPanel(null); setEditorLoading(false); setData(null); setPage('home'); setValues({}); setReceipt(null); setConfirmation(null); setDeleted(false); setError(false); setDeleteFailure(false); setEditing(false); setBusy(false);return () => { generation.current++; };}, [binding]);useEffect(() => { if (visible && online) void refresh(); }, [visible, online, refresh]);@@ -114,7 +116,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {const openEditor = async (resourceId: string) => {if (inFlight.current || !online || !resource) return;const started = binding; const sequence = ++generation.current;- setConflict(null); setEditorResourceId(resourceId); setPage('editor'); setEditor(null); setEditorPanel(null); setEditorLoading(true); setEditing(false); setError(false);+ setConflict(null); setEditorResourceId(resourceId); setPage('editor'); setEditor(null); setEditorPanel(null); setEditorLoading(true); setEditing(false); setError(false); setDeleteFailure(false);try {await openLink(deviceId);const next = await loadCompanionProfile(invoke, deviceId, { ...resource.ref, collectionId, id: resourceId }, i18n.language);@@ -134,13 +136,13 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {await openEditor(`settings:${resource?.ref.id}/${next === 'personalSkills' ? 'skills' : next}`);})(); return;}- setConflict(null); setEditor(null); setEditorPanel(null); setPage(next); setReceipt(null); setError(false); setConfirmation(null); setEditing(false);+ setConflict(null); setEditor(null); setEditorPanel(null); setPage(next); setReceipt(null); setError(false); setDeleteFailure(false); setConfirmation(null); setEditing(false);setValues(data?.panels.find(item => item.id === next)?.values ?? {});};const submit = async (target: ProfilePanel, confirmed = false): Promise<boolean> => {if (!target.action || target.action.disabled || inFlight.current || !online || !resource || conflict?.page === page) return false;if (target.action.confirmation && !confirmed) { setConfirmation(target); return false; }- inFlight.current = true; generation.current++; setBusy(true); setError(false); setReceipt(null);+ inFlight.current = true; generation.current++; setBusy(true); setError(false); setDeleteFailure(false); setReceipt(null);const started = binding;try {const response = await invokeRemoteResourceAction(invoke, { deviceId, deviceName }, {@@ -175,7 +177,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {} catch { setError(true); }return true;} catch {- if (current.current === started) { setError(true); setConfirmation(null); }+ if (current.current === started) { setError(true); setDeleteFailure(target.id === 'delete'); setConfirmation(null); }return false;} finally {inFlight.current = false;@@ -257,7 +259,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {visible={visible && modelStage === 'profile'} title={confirmation?.action?.confirmation ? label(confirmation.action.confirmation.title) : page === 'editor' && editor ? label(editor.resource.display.title) : t(`devices.companionProfile.${titleKey}`)}name={name} page={page} deviceId={deviceId} deviceName={deviceName} resource={resource} data={data} editor={editor} panel={panel}values={editing ? values : panel?.values ?? values} busy={busy} online={online} dirty={dirty} loading={editorLoading}- error={error} conflict={conflict?.page === page} receipt={receipt && !confirmation ? label(receipt) : null} confirmation={confirmation} deleted={deleted}+ error={error} errorLabel={deleteFailure ? t('devices.companionProfile.deleteFailed') : undefined} conflict={conflict?.page === page} receipt={receipt && !confirmation ? label(receipt) : null} confirmation={confirmation} deleted={deleted}artifacts={sessionId && resource ? <CompanionProfileArtifacts deviceId={deviceId} botId={resource.ref.id} sessionId={sessionId} online={online} onOpenTask={openArtifactTask} /> : note('artifactsRecovery')}onClose={dismiss} onClosed={afterClosed} onBack={page !== 'home' || confirmation ? () => void leave(false) : undefined}onOpen={open}@@ -274,7 +276,7 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {title={confirmation?.action?.confirmation ? label(confirmation.action.confirmation.title) : page === 'editor' && editor ? label(panel?.title ?? editor.resource.display.title) : t(`devices.companionProfile.${titleKey}`)} testID="companionProfile"><View style={styles.content}>{!online ? note('offline') : null}- {error ? <View accessibilityRole="alert">{note('readFailed')}<MainWindowActionButton action={{ label: t('devices.resources.retry'), disabled: busy || !online, onPress: () => { if (page === 'editor') void retryEditor(); else void refresh(); } }} />+ {error ? <View accessibilityRole="alert">{note(deleteFailure ? 'deleteFailed' : 'readFailed')}<MainWindowActionButton action={{ label: t('devices.resources.retry'), disabled: busy || !online, onPress: () => { if (page === 'editor') void retryEditor(); else void refresh(); } }} />{dirty ? <MainWindowActionButton action={{ label: t('devices.companions.automation.discard'), tone: 'danger', disabled: busy, onPress: () => discardDraft(false) }} /> : null}</View> : null}{conflict?.page === page ? <View accessibilityRole="alert">{note('changed')}<MainWindowActionButton action={{ label: t('devices.companionProfile.discardAndReload'), tone: 'danger', disabled: busy, onPress: () => discardDraft(true) }} /></View> : null}@@ -317,7 +319,6 @@ function CompanionProfileSheetContent(props: CompanionProfileSheetProps) {{actionPanel('skills')?.entries?.length ? row('personalSkills', Sparkles) : renderPanel(actionPanel('skills'))}{actionPanel('connections')?.entries?.length ? row('connections', Settings2) : renderPanel(actionPanel('connections'))}</> : page === 'artifacts' ? sessionId && resource ? <CompanionProfileArtifacts deviceId={deviceId} botId={resource.ref.id} sessionId={sessionId} online={online} onOpenTask={openArtifactTask} /> : note('artifactsRecovery') : page === 'direct' ? actionPanel('direct') ? <><Text selectable style={styles.body}>{actionPanel('direct')!.text || t('devices.companionProfile.directEmpty')}</Text></> : note('directRecovery') : <>{page === 'profile' && actionPanel('avatar')?.entries?.length ? row('avatar', UserRound) : null}- {page === 'models' && typeof panel?.followsDefault === 'boolean' ? note(panel.followsDefault ? 'modelFollowsDefault' : 'modelOverride') : null}{page === 'models' && panel?.action ? models : renderPanel(panel)}{(page === 'profile' || page === 'memory') && panel && !panel.action ? note('largeProfileRecovery') : null}{page === 'memory' && actionPanel('notes')?.action ? row('notes', Brain) : null}@@ -459,8 +460,8 @@ function CompanionProfileForm({ panel, values, onChange, disabled }: { panel: Pr</Pressable></NativePullDownMenu>{!fieldDisabled && openSelect === field.id ? <View style={styles.group}>- <TextInput accessibilityLabel={`${label} ${t('devices.companionProfile.searchOptions')}`} placeholder={t('devices.companionProfile.searchOptions')}- value={selectQuery} onChangeText={setSelectQuery} style={styles.input} placeholderTextColor={colors.textTertiary} />+ {field.id === 'permissions' ? null : <TextInput accessibilityLabel={`${label} ${t('devices.companionProfile.searchOptions')}`} placeholder={t('devices.companionProfile.searchOptions')}+ value={selectQuery} onChangeText={setSelectQuery} style={styles.input} placeholderTextColor={colors.textTertiary} />}<ScrollView nestedScrollEnabled keyboardShouldPersistTaps="handled" style={styles.optionScroll}>{options.filter(option => resolveRemoteText(option.label, i18n.language).toLocaleLowerCase().includes(selectQuery.trim().toLocaleLowerCase())).map(option =><ContextSheetRow key={option.value} icon={null} label={resolveRemoteText(option.label, i18n.language)} disabled={optionDisabled(option)}