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(teammates): let listed teammate tasks archive, restore and delete

zqchris2510e8defa36
diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
index c1baf28b05..b0da5c012d 100644
--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
@@ -1169,6 +1169,8 @@ function sessionsSetStatus(readyDb, args) {
})();
}
+const TASK_LIST_BOT_LANE_SQL = "SELECT 1 FROM bot_session_links WHERE session_id = ? AND role IN ('routine', 'channel') LIMIT 1";
+
// Keep this in sync with worker/opHandlers/tx.ts.
function sessionsSetTerminalStatus(readyDb, args) {
const payload = asRecord(args, 'sessions.setTerminalStatus args');
@@ -1181,7 +1183,8 @@ function sessionsSetTerminalStatus(readyDb, args) {
const existing = readyDb.prepare('SELECT id, status, source FROM sessions WHERE id = ? LIMIT 1').get(sessionId);
if (!existing) throw Object.assign(new Error('Session not found: ' + sessionId), { code: 'NOT_FOUND' });
if (existing.status === 'deleted') throw Object.assign(new Error('Deleted session cannot change status: ' + sessionId), { code: 'PRECONDITION_FAILED' });
- if (existing.source === 'bot') throw Object.assign(new Error('Bot sessions must use Bot lifecycle: ' + sessionId), { code: 'PRECONDITION_FAILED' });
+ // Routine/channel lanes are listed with ordinary tasks and follow their lifecycle.
+ if (existing.source === 'bot' && !readyDb.prepare(TASK_LIST_BOT_LANE_SQL).get(sessionId)) throw Object.assign(new Error('Bot sessions must use Bot lifecycle: ' + sessionId), { code: 'PRECONDITION_FAILED' });
const now = Date.now();
readyDb.prepare(CLOSE_SHARED_TASKS_FOR_SESSION_SQL).run(now, sessionId);
const updated = readyDb.prepare(
diff --git a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
index f2f29e83b3..293396cd95 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
@@ -1952,6 +1952,34 @@ describe('db worker tx handlers', () => {
},
);
+ it.each([false, true])(
+ 'sessions.setTerminalStatus archives listed teammate lanes but not private Bot chats (inline=%s)',
+ async (useInlineWorker) => {
+ await withClient(
+ async (client) => {
+ await client.exec(
+ 'CREATE TABLE IF NOT EXISTS bot_session_links (id TEXT PRIMARY KEY, bot_id TEXT NOT NULL, session_id TEXT NOT NULL, role TEXT NOT NULL, route_key TEXT, created_at INTEGER NOT NULL, archived_at INTEGER)',
+ );
+ for (const [id, role] of [['routine-lane', 'routine'], ['bot-chat', 'canonical']] as const) {
+ await seedSession(client, id, { source: 'bot' });
+ await client.exec(
+ 'INSERT INTO bot_session_links (id, bot_id, session_id, role, created_at) VALUES (?, ?, ?, ?, ?)',
+ [`link-${id}`, 'bot-1', id, role, Date.now()],
+ );
+ }
+ await expect(client.tx('sessions.setTerminalStatus', { sessionId: 'routine-lane', status: 'archived' }))
+ .resolves.toEqual(expect.objectContaining({ sessionId: 'routine-lane', status: 'archived' }));
+ await expect(client.tx('sessions.setTerminalStatus', { sessionId: 'bot-chat', status: 'archived' }))
+ .rejects.toThrow('Bot sessions must use Bot lifecycle');
+ await expect(client.query('SELECT id, status FROM sessions ORDER BY id')).resolves.toEqual([
+ { id: 'bot-chat', status: 'active' }, { id: 'routine-lane', status: 'archived' },
+ ]);
+ },
+ { useInlineWorker },
+ );
+ },
+ );
+
// DB tier, #6529: terminal-status writes must delete hidden children in the
// same commit. Existing closure-fence coverage only seeded a single task.
// A child UPDATE failure must preserve the parent and all child statuses.
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
index fa29c3a96e..6ae6bb0874 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/botCanonicalSession.test.ts
@@ -2059,6 +2059,11 @@ describe('Bot canonical Session lifecycle', () => {
if (!first.ok) throw new Error(first.message);
await expect(ensureBotChannelLaneSession({ botId: 'bot-1', routeKey, title: 'ignored' }))
.resolves.toEqual({ ok: true, sessionId: first.sessionId, created: false });
+ // The owner archived the lane from the task list: the next message resumes it, not a second lane.
+ h.sqlite!.prepare("UPDATE sessions SET status = 'archived' WHERE id = ?").run(first.sessionId);
+ await expect(ensureBotChannelLaneSession({ botId: 'bot-1', routeKey, title: 'ignored' }))
+ .resolves.toEqual({ ok: true, sessionId: first.sessionId, created: false });
+ expect(h.sqlite!.prepare('SELECT status FROM sessions WHERE id = ?').get(first.sessionId)).toEqual({ status: 'active' });
expect(emitSessionCreated).toHaveBeenCalledExactlyOnceWith(first.sessionId);
await expect(findBotChannelLaneSession('bot-1', routeKey)).resolves.toBe(first.sessionId);
const canonical = h.sqlite!.prepare(
diff --git a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
index ff795bcdaa..46bb8d354d 100644
--- a/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
+++ b/apps/desktop/src/main/localDb/ipc/__tests__/sessionsUpdate.test.ts
@@ -1024,6 +1024,23 @@ describe('local-db:sessions:update handler wiring', () => {
expect(persisted).toEqual({ title: 'Release Bot', status: 'active' });
});
+ it('archives, restores and deletes teammate tasks listed with ordinary tasks', async () => {
+ // 例行任务 / 渠道专线进入普通任务列表,生命周期与普通任务一致;主聊天仍由伙伴生命周期管理。
+ const link = h.sqlite!.prepare('INSERT INTO bot_session_links(session_id, bot_id, role, route_key) VALUES (?, ?, ?, ?)');
+ link.run('bot-local', 'bot-1', 'canonical', null);
+ await expect(invokeUpdate('bot-local', { status: 'archived' })).rejects.toThrow(/Bot task lifecycle/);
+
+ h.sqlite!.prepare('UPDATE bot_session_links SET role = ?, route_key = ? WHERE session_id = ?')
+ .run('routine', 'routine:daily', 'bot-local');
+ const status = () => (h.sqlite!.prepare('SELECT status FROM sessions WHERE id = ?').get('bot-local') as { status: string }).status;
+ await invokeUpdate('bot-local', { status: 'archived' });
+ expect(status()).toBe('archived');
+ await restoreArchivedSessionForSend('bot-local');
+ expect(status()).toBe('active');
+ await invokeUpdate('bot-local', { status: 'deleted' });
+ expect(status()).toBe('deleted');
+ });
+
it('persists and broadcasts title-only patches to device-link subscribers', async () => {
await invokeUpdate('codex-local', { title: '排查远程标题同步' });
diff --git a/apps/desktop/src/main/localDb/ipc/bots.ts b/apps/desktop/src/main/localDb/ipc/bots.ts
index 74f0a4c332..b819931eb2 100644
--- a/apps/desktop/src/main/localDb/ipc/bots.ts
+++ b/apps/desktop/src/main/localDb/ipc/bots.ts
@@ -106,7 +106,7 @@ import { createMessage } from './messages.js';
import { syncBotLanePermission, syncBotLinkedLanePermissions, syncBotPermissionsByBotId } from '../../maker-ipc/botPermissionSync.js';
import { withSessionPermissionChange } from '../../maker-ipc/sessionPermissionChange.js';
import { withBotPermissionChangeForBot } from '../../maker-ipc/botPermissionDispatch.js';
-import { broadcastSessionPatched } from './sessions.js';
+import { broadcastSessionPatched, restoreArchivedSessionForSend } from './sessions.js';
import { BOT_DELEGATION_CLIENT_ID } from '../../../shared/botCollaboration.js';
import { generateBotCreationDraft, readBotCreationDraft, generateBotCreationAvatar } from '../../maker-ipc/botCreationDraft.js';
@@ -449,7 +449,12 @@ export async function findBotChannelLaneSession(botId: string, routeKey: string)
return findBotOwnedLaneSession(botId, routeKey, 'channel');
}
-async function findBotOwnedLaneSession(botId: string, routeKey: string, role: 'channel' | 'routine'): Promise<string | null> {
+async function findBotOwnedLaneSession(
+ botId: string,
+ routeKey: string,
+ role: 'channel' | 'routine',
+ status: 'active' | 'archived' = 'active',
+): Promise<string | null> {
const [existing] = await getDbClient()
.drizzle.select({ sessionId: botSessionLinks.sessionId })
.from(botSessionLinks)
@@ -460,12 +465,34 @@ async function findBotOwnedLaneSession(botId: string, routeKey: string, role: 'c
eq(botSessionLinks.routeKey, routeKey),
isNull(botSessionLinks.archivedAt),
eq(sessions.source, 'bot'),
- eq(sessions.status, 'active'),
+ eq(sessions.status, status),
))
+ .orderBy(desc(sessions.updatedAt))
.limit(1);
return existing?.sessionId ?? null;
}
+/**
+ * The owner can archive these lanes from the task list. Like an archived automation
+ * target, the next trigger resumes the same Session (and its context) instead of
+ * starting another one; a lane deleted meanwhile falls through to a new Session.
+ */
+async function resumeArchivedBotOwnedLaneSession(
+ botId: string,
+ routeKey: string,
+ role: 'channel' | 'routine',
+): Promise<string | null> {
+ const archived = await findBotOwnedLaneSession(botId, routeKey, role, 'archived');
+ if (!archived) return null;
+ try {
+ await restoreArchivedSessionForSend(archived);
+ } catch (error) {
+ log.warn('archived bot lane could not be resumed; starting a new one', { sessionId: archived, error: String(error) });
+ return null;
+ }
+ return archived;
+}
+
/**
* The Bot's hidden lane for one personal-IM group / topic (or an admitted guest
* DM) once the whole connection is handed to the Bot. Same Profile, Home
@@ -490,7 +517,8 @@ async function ensureBotOwnedLaneSession(input: { botId: string; routeKey: strin
const owner = captureBotOperationOwner();
const client = getDbClient();
const db = client.drizzle;
- const existing = await findBotOwnedLaneSession(input.botId, input.routeKey, role);
+ const existing = await findBotOwnedLaneSession(input.botId, input.routeKey, role)
+ ?? await resumeArchivedBotOwnedLaneSession(input.botId, input.routeKey, role);
if (existing) {
await syncBotLanePermission(existing);
owner.assertCurrent();
diff --git a/apps/desktop/src/main/localDb/ipc/sessions.ts b/apps/desktop/src/main/localDb/ipc/sessions.ts
index 1bb0e14e1d..1faa181352 100644
--- a/apps/desktop/src/main/localDb/ipc/sessions.ts
+++ b/apps/desktop/src/main/localDb/ipc/sessions.ts
@@ -43,7 +43,7 @@ import { getDbClient } from '../client/current';
import * as currentDb from '../client/current';
import type { DbClient } from '../client/DbClient';
import type { SessionsSetTerminalStatusResult } from '../client/tx/types';
-import { sessions, messages } from '../schema';
+import { sessions, messages, botSessionLinks } from '../schema';
import { clearSessionAttention } from '../../appBadgeService';
import {
selectSessionListRows,
@@ -2670,7 +2670,8 @@ export async function restoreArchivedSessionForSend(
if (!isOwnerScopeCurrent(ownerScope)) throwIpcError('PRECONDITION_FAILED', 'Task owner changed');
if (row?.status === 'deleted') throwIpcError('NOT_FOUND', 'Session does not exist');
if (row?.status !== 'archived') return;
- if (row.source === 'bot' || row.orcaRole === 'worker' || row.orcaRemoteLead) {
+ if ((row.source === 'bot' && !(await isTaskListBotLane(db, sessionId)))
+ || row.orcaRole === 'worker' || row.orcaRemoteLead) {
throwIpcError('PRECONDITION_FAILED', 'Restore the managed task before continuing');
}
await patchSessionMetaInDb(sessionId, { status: 'active' }, { ...options, routeLockHeld: true });
@@ -2798,7 +2799,24 @@ export async function patchSessionMetaInDb(
}
/**
- * Bot tasks are absent from the ordinary task pool, so their active/history/
+ * Routine and channel lanes are listed with ordinary tasks (`ordinaryTaskListFilter`)
+ * and hold no Profile pointer, so they archive, restore and delete like ordinary tasks.
+ * Their next trigger resumes an archived lane (`ensureBotOwnedLaneSession`).
+ */
+async function isTaskListBotLane(db: DbClient['drizzle'], sessionId: string): Promise<boolean> {
+ const [link] = await db
+ .select({ role: botSessionLinks.role })
+ .from(botSessionLinks)
+ .where(and(
+ eq(botSessionLinks.sessionId, sessionId),
+ inArray(botSessionLinks.role, ['routine', 'channel']),
+ ))
+ .limit(1);
+ return !!link;
+}
+
+/**
+ * Other Bot tasks are absent from the ordinary task pool, so their active/history/
* route transitions must go through the Bot lifecycle service. That service
* updates the Profile pointer and Session projection atomically.
*/
@@ -2811,7 +2829,7 @@ async function assertGenericSessionLifecycleAllowed(
.from(sessions)
.where(eq(sessions.id, sessionId))
.limit(1);
- if (target?.source === 'bot') {
+ if (target?.source === 'bot' && !(await isTaskListBotLane(db, sessionId))) {
throwIpcError(
'PRECONDITION_FAILED',
'Bot task lifecycle is managed by teammate recovery and history controls',
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index c04b2e1167..d341192dc2 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -2333,6 +2333,8 @@ function sessionsSetStatus(db: Database.Database, args: unknown): Array<{
}>;
}
+const TASK_LIST_BOT_LANE_SQL = "SELECT 1 FROM bot_session_links WHERE session_id = ? AND role IN ('routine', 'channel') LIMIT 1";
+
/** Atomically persist a terminal task status and its local-close fence. */
function sessionsSetTerminalStatus(db: Database.Database, args: unknown): SessionsSetTerminalStatusResult {
const payload = asRecord(args, 'sessions.setTerminalStatus args');
@@ -2344,7 +2346,8 @@ function sessionsSetTerminalStatus(db: Database.Database, args: unknown): Sessio
| { id: string; status: string; source: string } | undefined;
if (!existing) throw Object.assign(new Error('Session not found: ' + sessionId), { code: 'NOT_FOUND' });
if (existing.status === 'deleted') throw Object.assign(new Error('Deleted session cannot change status: ' + sessionId), { code: 'PRECONDITION_FAILED' });
- if (existing.source === 'bot') throw Object.assign(new Error('Bot sessions must use Bot lifecycle: ' + sessionId), { code: 'PRECONDITION_FAILED' });
+ // Routine/channel lanes are listed with ordinary tasks and follow their lifecycle.
+ if (existing.source === 'bot' && !db.prepare(TASK_LIST_BOT_LANE_SQL).get(sessionId)) throw Object.assign(new Error('Bot sessions must use Bot lifecycle: ' + sessionId), { code: 'PRECONDITION_FAILED' });
const now = Date.now();
if (status === 'archived' || status === 'deleted') db.prepare(CLOSE_SHARED_TASKS_FOR_SESSION_SQL).run(now, sessionId);
const updated = db.prepare(
diff --git a/docs/product-rules/bot-routines.md b/docs/product-rules/bot-routines.md
index 3930de18f1..b4f3131592 100644
--- a/docs/product-rules/bot-routines.md
+++ b/docs/product-rules/bot-routines.md
@@ -28,6 +28,8 @@ Bot Market 原生包的例行任务只通过原导入服务保存停用定义,
`sessionMode` 决定触发之间是否保留上下文(2026-10-27):`persistent`(缺省,兼容旧规则)复用上面的持久独立任务;`fresh` 每次触发由宿主新建一条同伙伴身份、同权限的独立任务(`route_key = 'routine:<routineId>:<uuid>'`),运行结束后关闭,下次触发不带旧上下文。两种方式都沿用该规则的 `modelOverride`,历史里的「查看任务」仍可打开每次运行的任务。内置规则可改运行方式(界面「沿用同一任务 / 每次新建任务」),不改指令、频率与权限;夜间学习不提供此项。
+例行任务专线与渠道专线(`role = routine / channel`)进入普通任务列表,生命周期也与普通任务一致(2026-10-30):可以在列表里归档、取消归档、删除。归档后的持久专线在下次触发或下一条渠道消息时恢复原任务并保留上下文,与归档的普通自动化目标一致;删除后下次触发新建。伙伴主聊天、私聊话题、群专线等不在普通任务列表的伙伴 Session 仍由伙伴生命周期管理,通用归档/删除继续拒绝。判定见 `sessions.ts` 的 `isTaskListBotLane` 与终态写入 `sessions.setTerminalStatus`。
+
`modelOverride` 可单独选择完整模型路由(引擎、来源、型号、执行位置、推理强度、Fast);缺失或 null 跟随伙伴模型,显式配置不套用伙伴主模型的备用链。旧客户端省略字段时保留已存选择,null 才清除。保存后下一轮通过普通模型切换与交接入口应用;独立任务内继续交流也使用这份配置。每条例行任务最多一个正在执行的运行;等待事件合成一批,各条规则通过各自任务队列派发。
独立任务保留完整执行记录,历史里的「查看任务」打开原有普通任务页面;静默只控制通知,不隐藏执行正文。它不进入自动跟进的观察列表,避免跟进自己的执行。伙伴迁走后,旧电脑上这条任务仍可回看,但普通发送、内部发送和排队派发都不能重新启动它。合成触发输入沿用原有来源说明。夜间学习已有专门宿主流程,不改为这类任务。