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。

Migrated from makecindy/cindy-temp#556 (#237)

Lizi51440f675cbc
diff --git a/apps/desktop/src/main/im/__tests__/binding.test.ts b/apps/desktop/src/main/im/__tests__/binding.test.ts
new file mode 100644
index 0000000000..9a4b21cad6
--- /dev/null
+++ b/apps/desktop/src/main/im/__tests__/binding.test.ts
@@ -0,0 +1,302 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { BindingChangeEvent, IdentityKey } from '@cindy/im';
+
+const mocks = vi.hoisted(() => ({
+ rows: [] as Array<{
+ channel: string;
+ botContextId: string;
+ userId: string;
+ scopeKey: string;
+ targetSessionId: string;
+ attachedAt: number;
+ attachedViaCardMessageId: string | null;
+ }>,
+ deleteWhere: vi.fn(async () => undefined),
+ tx: vi.fn(async () => undefined),
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+}));
+
+vi.mock('drizzle-orm', () => ({
+ and: vi.fn((...conditions: unknown[]) => conditions),
+ eq: vi.fn((column: unknown, value: unknown) => ({ column, value })),
+}));
+vi.mock('../../logger', () => ({ createLogger: () => mocks.logger }));
+vi.mock('../../localDb/schema', () => ({
+ imBindings: {
+ channel: 'channel',
+ botContextId: 'botContextId',
+ userId: 'userId',
+ scopeKey: 'scopeKey',
+ targetSessionId: 'targetSessionId',
+ },
+}));
+vi.mock('../../localDb/client/current', () => ({
+ getDbClient: () => ({
+ tx: mocks.tx,
+ drizzle: {
+ select: () => ({ from: async () => [...mocks.rows] }),
+ delete: () => ({ where: mocks.deleteWhere }),
+ },
+ }),
+}));
+
+import { SqliteBindingStore } from '../binding';
+
+const feishuIdentity: IdentityKey = {
+ channel: 'feishu',
+ botContextId: 'feishu-bot',
+ userId: 'ou_owner',
+};
+const discordIdentity: IdentityKey = {
+ channel: 'discord',
+ botContextId: 'discord-bot',
+ userId: '123456',
+};
+
+function deferred<T>() {
+ let resolve!: (value: T | PromiseLike<T>) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+describe('SqliteBindingStore single-owner reverse index', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.rows.length = 0;
+ });
+
+ it('replaces the previous channel when another identity attaches the same session', async () => {
+ const store = new SqliteBindingStore();
+ const events: BindingChangeEvent<string>[] = [];
+ store.onChange((event) => events.push(event));
+ await store.preload();
+
+ await store.attach(feishuIdentity, 'desktop-session', {
+ attachedViaCardMessageId: 'feishu-card',
+ });
+ const attachResult = await store.attachWithResult(discordIdentity, 'desktop-session');
+
+ expect(store.get(feishuIdentity)).toBeNull();
+ expect(store.get(discordIdentity)).toBe('desktop-session');
+ expect(store.findByTarget('desktop-session')).toEqual(discordIdentity);
+ expect(store.listAttachedTargets()).toEqual(['desktop-session']);
+ expect(attachResult).toEqual({
+ displaced: {
+ identity: feishuIdentity,
+ attachedViaCardMessageId: 'feishu-card',
+ },
+ });
+ expect(events).toEqual([
+ { identity: feishuIdentity, value: 'desktop-session', prevValue: null },
+ { identity: feishuIdentity, value: null, prevValue: 'desktop-session' },
+ { identity: discordIdentity, value: 'desktop-session', prevValue: null },
+ ]);
+
+ await store.detach(discordIdentity);
+ expect(store.findByTarget('desktop-session')).toBeNull();
+ expect(store.listAttachedTargets()).toEqual([]);
+ });
+
+ it('keeps the previous binding and emits no events when replacement persistence fails', async () => {
+ const store = new SqliteBindingStore();
+ const events: BindingChangeEvent<string>[] = [];
+ store.onChange((event) => events.push(event));
+ await store.preload();
+ await store.attach(feishuIdentity, 'desktop-session', {
+ attachedViaCardMessageId: 'feishu-card',
+ });
+ const eventsBeforeReplacement = [...events];
+ mocks.tx.mockRejectedValueOnce(new Error('db locked'));
+
+ await expect(
+ store.attach(discordIdentity, 'desktop-session', {
+ attachedViaCardMessageId: 'discord-card',
+ }),
+ ).rejects.toThrow('db locked');
+
+ expect(store.get(feishuIdentity)).toBe('desktop-session');
+ expect(store.get(discordIdentity)).toBeNull();
+ expect(store.findByTarget('desktop-session')).toEqual(feishuIdentity);
+ expect(store.getAttachCardMessageId(feishuIdentity)).toBe('feishu-card');
+ expect(events).toEqual(eventsBeforeReplacement);
+ });
+
+ it('serializes concurrent attachments before reading and updating the indexes', async () => {
+ const store = new SqliteBindingStore();
+ const events: BindingChangeEvent<string>[] = [];
+ const firstTransaction = deferred<undefined>();
+ store.onChange((event) => events.push(event));
+ await store.preload();
+ mocks.tx.mockImplementationOnce(() => firstTransaction.promise);
+
+ const firstAttach = store.attach(feishuIdentity, 'desktop-session', {
+ attachedViaCardMessageId: 'feishu-card',
+ });
+ const secondAttach = store.attach(discordIdentity, 'desktop-session', {
+ attachedViaCardMessageId: 'discord-card',
+ });
+
+ await vi.waitFor(() => expect(mocks.tx).toHaveBeenCalledTimes(1));
+ expect(store.findByTarget('desktop-session')).toBeNull();
+
+ firstTransaction.resolve(undefined);
+ await firstAttach;
+ await secondAttach;
+
+ expect(mocks.tx).toHaveBeenCalledTimes(2);
+ expect(store.get(feishuIdentity)).toBeNull();
+ expect(store.get(discordIdentity)).toBe('desktop-session');
+ expect(store.findByTarget('desktop-session')).toEqual(discordIdentity);
+ expect(store.getAttachCardMessageId(feishuIdentity)).toBeNull();
+ expect(store.getAttachCardMessageId(discordIdentity)).toBe('discord-card');
+ expect(events).toEqual([
+ { identity: feishuIdentity, value: 'desktop-session', prevValue: null },
+ { identity: feishuIdentity, value: null, prevValue: 'desktop-session' },
+ { identity: discordIdentity, value: 'desktop-session', prevValue: null },
+ ]);
+ });
+
+ it('ignores a queued detach after the identity moves to another target', async () => {
+ const store = new SqliteBindingStore();
+ await store.preload();
+ await store.attach(feishuIdentity, 'desktop-session-a');
+ mocks.deleteWhere.mockClear();
+ const moveTransaction = deferred<undefined>();
+ mocks.tx.mockImplementationOnce(() => moveTransaction.promise);
+
+ const move = store.attach(feishuIdentity, 'desktop-session-b');
+ await vi.waitFor(() => expect(mocks.tx).toHaveBeenCalledTimes(2));
+ const staleDetach = store.detachIfTarget(feishuIdentity, 'desktop-session-a');
+
+ moveTransaction.resolve(undefined);
+ await move;
+ await expect(staleDetach).resolves.toBe(false);
+
+ expect(store.get(feishuIdentity)).toBe('desktop-session-b');
+ expect(store.findByTarget('desktop-session-a')).toBeNull();
+ expect(store.findByTarget('desktop-session-b')).toEqual(feishuIdentity);
+ expect(mocks.deleteWhere).not.toHaveBeenCalled();
+ });
+
+ it('repairs persisted duplicate targets by keeping the latest takeover', async () => {
+ mocks.rows.push(
+ {
+ channel: 'feishu',
+ botContextId: 'feishu-bot',
+ userId: 'ou_owner',
+ scopeKey: '',
+ targetSessionId: 'desktop-session',
+ attachedAt: 100,
+ attachedViaCardMessageId: 'feishu-card',
+ },
+ {
+ channel: 'discord',
+ botContextId: 'discord-bot',
+ userId: '123456',
+ scopeKey: '',
+ targetSessionId: 'desktop-session',
+ attachedAt: 200,
+ attachedViaCardMessageId: 'discord-card',
+ },
+ );
+ const store = new SqliteBindingStore();
+
+ await store.preload();
+
+ expect(store.get(feishuIdentity)).toBeNull();
+ expect(store.get(discordIdentity)).toBe('desktop-session');
+ expect(store.findByTarget('desktop-session')).toEqual(discordIdentity);
+ expect(store.getAttachCardMessageId(discordIdentity)).toBe('discord-card');
+ expect(mocks.tx).toHaveBeenCalledWith('im.deleteBindings', {
+ identities: [
+ {
+ channel: 'feishu',
+ botContextId: 'feishu-bot',
+ userId: 'ou_owner',
+ scopeKey: '',
+ },
+ ],
+ });
+ expect(mocks.deleteWhere).not.toHaveBeenCalled();
+ });
+
+ it('publishes winner indexes and allows retry when duplicate cleanup fails', async () => {
+ mocks.rows.push(
+ {
+ channel: 'feishu',
+ botContextId: 'feishu-bot',
+ userId: 'ou_owner',
+ scopeKey: '',
+ targetSessionId: 'desktop-session',
+ attachedAt: 100,
+ attachedViaCardMessageId: 'feishu-card',
+ },
+ {
+ channel: 'discord',
+ botContextId: 'discord-bot',
+ userId: '123456',
+ scopeKey: '',
+ targetSessionId: 'desktop-session',
+ attachedAt: 200,
+ attachedViaCardMessageId: 'discord-card',
+ },
+ );
+ mocks.tx.mockRejectedValueOnce(new Error('db locked'));
+ const store = new SqliteBindingStore();
+
+ await expect(store.preload()).rejects.toThrow('db locked');
+
+ expect(store.get(feishuIdentity)).toBeNull();
+ expect(store.get(discordIdentity)).toBe('desktop-session');
+ expect(store.findByTarget('desktop-session')).toEqual(discordIdentity);
+ expect(store.getAttachCardMessageId(discordIdentity)).toBe('discord-card');
+
+ await store.preload();
+
+ expect(mocks.tx).toHaveBeenCalledTimes(2);
+ expect(store.get(discordIdentity)).toBe('desktop-session');
+ expect(store.findByTarget('desktop-session')).toEqual(discordIdentity);
+ });
+
+ it('purges every persisted owner of a target when its visible winner detaches', async () => {
+ mocks.rows.push(
+ {
+ channel: 'feishu',
+ botContextId: 'feishu-bot',
+ userId: 'ou_owner',
+ scopeKey: '',
+ targetSessionId: 'desktop-session',
+ attachedAt: 100,
+ attachedViaCardMessageId: 'feishu-card',
+ },
+ {
+ channel: 'discord',
+ botContextId: 'discord-bot',
+ userId: '123456',
+ scopeKey: '',
+ targetSessionId: 'desktop-session',
+ attachedAt: 200,
+ attachedViaCardMessageId: 'discord-card',
+ },
+ );
+ mocks.tx.mockRejectedValueOnce(new Error('db locked'));
+ const store = new SqliteBindingStore();
+ await expect(store.preload()).rejects.toThrow('db locked');
+
+ await expect(
+ store.detachIfTarget(discordIdentity, 'desktop-session'),
+ ).resolves.toBe(true);
+
+ expect(mocks.deleteWhere).toHaveBeenCalledWith({
+ column: 'targetSessionId',
+ value: 'desktop-session',
+ });
+ expect(store.findByTarget('desktop-session')).toBeNull();
+ expect(store.get(discordIdentity)).toBeNull();
+ });
+});
diff --git a/apps/desktop/src/main/im/binding.ts b/apps/desktop/src/main/im/binding.ts
index 858dd62102..ea5aa46a02 100644
--- a/apps/desktop/src/main/im/binding.ts
+++ b/apps/desktop/src/main/im/binding.ts
@@ -25,7 +25,7 @@
* 保证两边一致。
*/
-import { and, eq } from 'drizzle-orm';
+import { eq } from 'drizzle-orm';
import type {
BindingChangeEvent,
@@ -46,7 +46,14 @@ function keyOf(id: IdentityKey): string {
return [id.channel, id.botContextId, id.userId, id.scopeKey ?? ''].join('\u0000');
}
-class SqliteBindingStore implements BindingStore<string> {
+export interface BindingAttachResult {
+ displaced: {
+ identity: IdentityKey;
+ attachedViaCardMessageId: string | null;
+ } | null;
+}
+
+export class SqliteBindingStore implements BindingStore<string> {
/** identity-key (string) → desktop sessionId */
private readonly forward = new Map<string, string>();
/** desktop sessionId → identity (反向索引, 给"收回"按钮反查用) */
@@ -59,31 +66,88 @@ class SqliteBindingStore implements BindingStore<string> {
private readonly attachCardIds = new Map<string, string>();
private readonly listeners = new Set<BindingChangeListener<string>>();
private preloaded = false;
+ /** Serialize persisted writes with their matching in-memory index updates. */
+ private mutationQueue: Promise<void> = Promise.resolve();
+
+ preload(): Promise<void> {
+ return this.enqueueMutation(async () => {
+ if (this.preloaded) return;
+ // 走 DbClient async 代理: MR2.2 后 main 侧 _drizzle 在 worker takeover
+ // 时被释放, getDrizzle() 会抛 'localDb not ready'。代理把 query 转发给
+ // worker 内的真 better-sqlite3 实例, await 已经是 await Promise(原 await
+ // sync value 是 no-op, 现在变成真 async, 调用形态不变)。
+ const dbClient = getDbClient();
+ const rows = await dbClient.drizzle.select().from(imBindings);
+ const winnersByTarget = new Map<
+ string,
+ { identity: IdentityKey; attachedAt: number; cardMessageId: string | null }
+ >();
+ const staleIdentities: IdentityKey[] = [];
- async preload(): Promise<void> {
- if (this.preloaded) return;
- // 走 DbClient async 代理: MR2.2 后 main 侧 _drizzle 在 worker takeover
- // 时被释放, getDrizzle() 会抛 'localDb not ready'。代理把 query 转发给
- // worker 内的真 better-sqlite3 实例, await 已经是 await Promise(原 await
- // sync value 是 no-op, 现在变成真 async, 调用形态不变)。
- const db = getDbClient().drizzle;
- const rows = await db.select().from(imBindings);
- for (const row of rows) {
- const id: IdentityKey = {
- channel: row.channel,
- botContextId: row.botContextId,
- userId: row.userId,
- // '' = 无 scope(feishu);非空 = slack thread root ts
- ...(row.scopeKey ? { scopeKey: row.scopeKey } : {}),
- };
- this.forward.set(keyOf(id), row.targetSessionId);
- this.reverse.set(row.targetSessionId, id);
- if (row.attachedViaCardMessageId) {
- this.attachCardIds.set(keyOf(id), row.attachedViaCardMessageId);
+ for (const row of rows) {
+ const id: IdentityKey = {
+ channel: row.channel,
+ botContextId: row.botContextId,
+ userId: row.userId,
+ // '' = 无 scope(feishu);非空 = slack thread root ts
+ ...(row.scopeKey ? { scopeKey: row.scopeKey } : {}),
+ };
+
+ // Older builds allowed multiple identities to point at one desktop
+ // session even though the session has only one interaction listener.
+ // Recover deterministically by keeping the most recent takeover and
+ // deleting stale rows before opening the ingress gate.
+ const existing = winnersByTarget.get(row.targetSessionId);
+ const candidateWins =
+ !existing ||
+ row.attachedAt > existing.attachedAt ||
+ (row.attachedAt === existing.attachedAt && keyOf(id) > keyOf(existing.identity));
+ if (candidateWins) {
+ if (existing) staleIdentities.push(existing.identity);
+ winnersByTarget.set(row.targetSessionId, {
+ identity: id,
+ attachedAt: row.attachedAt,
+ cardMessageId: row.attachedViaCardMessageId,
+ });
+ } else {
+ staleIdentities.push(id);
+ }
}
- }
- this.preloaded = true;
- log.info(`preload loaded ${rows.length} im_bindings`);
+
+ // Publish a complete winner snapshot before the best-effort persisted
+ // repair. If cleanup fails, initialization may continue, but ingress
+ // still routes through the deterministic winners instead of an empty
+ // runtime index. A later preload retry rebuilds these maps from its
+ // freshly selected snapshot before attempting cleanup again.
+ this.forward.clear();
+ this.reverse.clear();
+ this.attachCardIds.clear();
+ for (const [sessionId, winner] of winnersByTarget) {
+ const k = keyOf(winner.identity);
+ this.forward.set(k, sessionId);
+ this.reverse.set(sessionId, winner.identity);
+ if (winner.cardMessageId) {
+ this.attachCardIds.set(k, winner.cardMessageId);
+ }
+ }
+ if (staleIdentities.length > 0) {
+ await dbClient.tx('im.deleteBindings', {
+ identities: staleIdentities.map((identity) => ({
+ channel: identity.channel,
+ botContextId: identity.botContextId,
+ userId: identity.userId,
+ scopeKey: identity.scopeKey ?? '',
+ })),
+ });
+ }
+ this.preloaded = true;
+ log.info(
+ `preload loaded ${winnersByTarget.size} im_bindings` +
+ (staleIdentities.length > 0
+ ? ` (removed ${staleIdentities.length} stale takeover(s))`
+ : ''),
+ );
+ });
}
/**
@@ -140,93 +204,138 @@ class SqliteBindingStore implements BindingStore<string> {
return out;
}
- async attach(
+ attach(
identity: IdentityKey,
value: string,
options?: { attachedViaCardMessageId?: string },
): Promise<void> {
- const now = Date.now();
- const db = getDbClient().drizzle;
-
- // INSERT OR REPLACE 语义: drizzle 没有内置, 走"先 delete 同主键再 insert"
- // 在事务里, 等价于 last-write-wins。同一 identity 的旧 binding (可能 attach
- // 在不同 sessionId 上) 被覆盖 — 反向索引也要清理旧 sessionId。
- const oldSessionId = this.forward.get(keyOf(identity));
- await db
- .delete(imBindings)
- .where(
- and(
- eq(imBindings.channel, identity.channel),
- eq(imBindings.botContextId, identity.botContextId),
- eq(imBindings.userId, identity.userId),
- eq(imBindings.scopeKey, identity.scopeKey ?? ''),
- ),
+ return this.attachWithResult(identity, value, options).then(() => undefined);
+ }
+
+ /**
+ * Same mutation as attach(), plus the target owner actually displaced from
+ * inside the serialized operation. Card cleanup callers must use this result
+ * instead of a pre-attach reverse-index snapshot.
+ */
+ attachWithResult(
+ identity: IdentityKey,
+ value: string,
+ options?: { attachedViaCardMessageId?: string },
+ ): Promise<BindingAttachResult> {
+ return this.enqueueMutation(async () => {
+ const now = Date.now();
+ const dbClient = getDbClient();
+ const identityKey = keyOf(identity);
+ const displacedIdentity = this.reverse.get(value);
+ const displaced =
+ displacedIdentity !== undefined && keyOf(displacedIdentity) !== identityKey
+ ? {
+ identity: displacedIdentity,
+ attachedViaCardMessageId:
+ this.attachCardIds.get(keyOf(displacedIdentity)) ?? null,
+ }
+ : null;
+
+ // 同一 identity 的旧 target 与同一 target 的旧 identity 必须在一个 worker
+ // transaction 里替换。新 INSERT 失败时 SQLite 会恢复旧 binding;因此内存
+ // 索引和 interaction listener 也仍保持旧接管,不会出现两边都失效的窗口。
+ const oldSessionId = this.forward.get(identityKey);
+ await dbClient.tx('im.replaceBinding', {
+ channel: identity.channel,
+ botContextId: identity.botContextId,
+ userId: identity.userId,
+ scopeKey: identity.scopeKey ?? '',
+ targetSessionId: value,
+ attachedAt: now,
+ attachedViaCardMessageId: options?.attachedViaCardMessageId ?? null,
+ });
+
+ // 持久化成功后再更新内存
+ if (oldSessionId && oldSessionId !== value) {
+ const reverseIdentity = this.reverse.get(oldSessionId);
+ if (reverseIdentity && keyOf(reverseIdentity) === identityKey) {
+ this.reverse.delete(oldSessionId);
+ }
+ }
+ if (displaced) {
+ const displacedKey = keyOf(displaced.identity);
+ this.forward.delete(displacedKey);
+ this.attachCardIds.delete(displacedKey);
+ }
+ this.forward.set(identityKey, value);
+ this.reverse.set(value, identity);
+ if (options?.attachedViaCardMessageId) {
+ this.attachCardIds.set(identityKey, options.attachedViaCardMessageId);
+ } else {
+ this.attachCardIds.delete(identityKey);
+ }
+
+ log.info(
+ `attach channel=${identity.channel} bot=...${identity.botContextId.slice(-6)} ` +
+ `user=...${identity.userId.slice(-8)} → session=...${value.slice(-8)}` +
+ (oldSessionId && oldSessionId !== value
+ ? ` (replaced old session=...${oldSessionId.slice(-8)})`
+ : ''),
);
- await db.insert(imBindings).values({
- channel: identity.channel,
- botContextId: identity.botContextId,
- userId: identity.userId,
- scopeKey: identity.scopeKey ?? '',
- targetSessionId: value,
- attachedAt: now,
- attachedViaCardMessageId: options?.attachedViaCardMessageId ?? null,
+ // prevValue 给 listener 区分"新 attach"vs"同 identity 切换 target"用,
+ // 后者 channel cleanup 需要先清理旧 session 上挂的 hook。
+ if (displaced) {
+ this.emit({ identity: displaced.identity, value: null, prevValue: value });
+ }
+ this.emit({ identity, value, prevValue: oldSessionId ?? null });
+ return { displaced };
});
+ }
- // 持久化成功后再更新内存
- if (oldSessionId && oldSessionId !== value) {
- this.reverse.delete(oldSessionId);
- }
- this.forward.set(keyOf(identity), value);
- this.reverse.set(value, identity);
- if (options?.attachedViaCardMessageId) {
- this.attachCardIds.set(keyOf(identity), options.attachedViaCardMessageId);
- } else {
- this.attachCardIds.delete(keyOf(identity));
- }
-
- log.info(
- `attach channel=${identity.channel} bot=...${identity.botContextId.slice(-6)} ` +
- `user=...${identity.userId.slice(-8)} → session=...${value.slice(-8)}` +
- (oldSessionId && oldSessionId !== value
- ? ` (replaced old session=...${oldSessionId.slice(-8)})`
- : ''),
- );
- // prevValue 给 listener 区分"新 attach"vs"同 identity 切换 target"用,
- // 后者 channel cleanup 需要先清理旧 session 上挂的 hook。
- this.emit({ identity, value, prevValue: oldSessionId ?? null });
+ detach(identity: IdentityKey): Promise<void> {
+ return this.detachIfTarget(identity).then(() => undefined);
}
- async detach(identity: IdentityKey): Promise<void> {
- const k = keyOf(identity);
- const oldSessionId = this.forward.get(k);
- if (!oldSessionId) {
- log.debug(
- `detach noop (not attached) channel=${identity.channel} user=...${identity.userId.slice(-8)}`,
- );
- return;
- }
- const db = getDbClient().drizzle;
- await db
- .delete(imBindings)
- .where(
- and(
- eq(imBindings.channel, identity.channel),
- eq(imBindings.botContextId, identity.botContextId),
- eq(imBindings.userId, identity.userId),
- eq(imBindings.scopeKey, identity.scopeKey ?? ''),
- ),
- );
- this.forward.delete(k);
- this.reverse.delete(oldSessionId);
- this.attachCardIds.delete(k);
+ /**
+ * Detach only while the identity still owns the expected target. Persisted
+ * deletion is target-wide so stale duplicate owners left by a failed preload
+ * repair cannot resurrect after the visible winner is revoked.
+ */
+ detachIfTarget(
+ identity: IdentityKey,
+ expectedTargetSessionId?: string,
+ ): Promise<boolean> {
+ return this.enqueueMutation(async () => {
+ const k = keyOf(identity);
+ const oldSessionId = this.forward.get(k);
+ if (!oldSessionId) {
+ log.debug(
+ `detach noop (not attached) channel=${identity.channel} user=...${identity.userId.slice(-8)}`,
+ );
+ return false;
+ }
+ if (expectedTargetSessionId && oldSessionId !== expectedTargetSessionId) {
+ log.debug(
+ `detach noop (target changed) channel=${identity.channel} ` +
+ `expected=...${expectedTargetSessionId.slice(-8)} actual=...${oldSessionId.slice(-8)}`,
+ );
+ return false;
+ }
+ const db = getDbClient().drizzle;
+ await db
+ .delete(imBindings)
+ .where(eq(imBindings.targetSessionId, oldSessionId));
+ this.forward.delete(k);
+ const reverseIdentity = this.reverse.get(oldSessionId);
+ if (reverseIdentity && keyOf(reverseIdentity) === k) {
+ this.reverse.delete(oldSessionId);
+ }
+ this.attachCardIds.delete(k);
- log.info(
- `detach channel=${identity.channel} bot=...${identity.botContextId.slice(-6)} ` +
- `user=...${identity.userId.slice(-8)} (was session=...${oldSessionId.slice(-8)})`,
- );
- // prevValue 必须带上 — channel cleanup (e.g. detachFeishuFromSession) 需要
- // 它来定位 in-process state 是哪个 session 的; 否则就得反向 import。
- this.emit({ identity, value: null, prevValue: oldSessionId });
+ log.info(
+ `detach channel=${identity.channel} bot=...${identity.botContextId.slice(-6)} ` +
+ `user=...${identity.userId.slice(-8)} (was session=...${oldSessionId.slice(-8)})`,
+ );
+ // prevValue 必须带上 — channel cleanup (e.g. detachFeishuFromSession) 需要
+ // 它来定位 in-process state 是哪个 session 的; 否则就得反向 import。
+ this.emit({ identity, value: null, prevValue: oldSessionId });
+ return true;
+ });
}
onChange(listener: BindingChangeListener<string>): () => void {
@@ -246,6 +355,15 @@ class SqliteBindingStore implements BindingStore<string> {
}
}
}
+
+ private enqueueMutation<T>(operation: () => Promise<T>): Promise<T> {
+ const result = this.mutationQueue.then(operation, operation);
+ this.mutationQueue = result.then(
+ () => undefined,
+ () => undefined,
+ );
+ return result;
+ }
}
// Singleton — 整个 main 进程共享一份 store。
@@ -292,7 +410,10 @@ export async function executeDetach(
}
try {
- await bindingStore.detach(identity);
+ const detached = await bindingStore.detachIfTarget(identity, targetSessionId);
+ if (!detached) {
+ return { wasAttached: false, targetSessionId: null };
+ }
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
log.error(`executeDetach: bindingStore.detach failed: ${msg}`);
diff --git a/apps/desktop/src/main/im/index.ts b/apps/desktop/src/main/im/index.ts
index dc72dcb35c..beb0b71ba1 100644
--- a/apps/desktop/src/main/im/index.ts
+++ b/apps/desktop/src/main/im/index.ts
@@ -239,7 +239,10 @@ export function startImOrchestrators(): void {
if (!identity) {
return { ok: true, alreadyDetached: true };
}
- await executeDetach(identity, 'desktop-revoke');
+ const detached = await executeDetach(identity, 'desktop-revoke');
+ if (!detached.wasAttached) {
+ return { ok: true, alreadyDetached: true };
+ }
// 通知对应的 IM 用户 — 渠道注册表驱动, 用各渠道自己的文案包。
const orchestrator = getImOrchestrator(identity.channel);
if (orchestrator) {
diff --git a/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts b/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts
index bfc630e714..772f5cfa73 100644
--- a/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/cardActionTakeoverReplace.test.ts
@@ -1,11 +1,9 @@
/**
* cardActionHandler — control:session-pick 重复接管替换流程(thread 模型)。
*
- * 语义: 目标 desktop session 已被另一个 thread 接管时, 不再拒绝
- * (旧 alreadyTakenOver), 而是中断旧接管由新 thread 替换:
- * 1. executeDetach(旧 identity) — 失败必须中止(防双 thread 路由同一 session)
- * 2. 旧锚点/root 卡收口为 takeoverReplaced(同渠道才 patch)
- * 3. 新 thread 正常 attach + 锚点卡 morph
+ * 语义: 目标 desktop session 已被另一个 thread 接管时, attach 原子替换
+ * persisted owner;成功后才收口旧锚点并 prewire 新渠道。attach 失败时旧
+ * binding / listener / 锚点都保持原状。
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
@@ -16,8 +14,7 @@ const mocks = vi.hoisted(() => ({
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
bindingGet: vi.fn(),
bindingAttach: vi.fn(),
- bindingFindByTarget: vi.fn(),
- bindingGetAttachCardMessageId: vi.fn(),
+ bindingAttachWithResult: vi.fn(),
executeDetach: vi.fn(),
generateTakeoverSummary: vi.fn(),
getMaker: vi.fn(),
@@ -63,8 +60,7 @@ vi.mock('../../binding', () => ({
bindingStore: {
get: mocks.bindingGet,
attach: mocks.bindingAttach,
- findByTarget: mocks.bindingFindByTarget,
- getAttachCardMessageId: mocks.bindingGetAttachCardMessageId,
+ attachWithResult: mocks.bindingAttachWithResult,
},
executeDetach: mocks.executeDetach,
}));
@@ -169,8 +165,9 @@ function slackThreadUi(): NonNullable<typeof slackUi.thread> {
async function pressSessionPick(
im: ChannelIM,
overrides?: Partial<IMCardActionEvent>,
+ testAdapter: ImChannelAdapter = adapter,
): Promise<void> {
- const attach = createCardActionHandler(adapter, cards, turnRunner);
+ const attach = createCardActionHandler(testAdapter, cards, turnRunner);
let handler: ((e: IMCardActionEvent) => Promise<void>) | null = null;
(im.onCardAction as ReturnType<typeof vi.fn>).mockImplementation((cb) => {
handler = cb;
@@ -199,6 +196,7 @@ beforeEach(() => {
(resolvePending as ReturnType<typeof vi.fn>).mockReturnValue(false);
mocks.generateTakeoverSummary.mockResolvedValue('brief');
mocks.bindingAttach.mockResolvedValue(undefined);
+ mocks.bindingAttachWithResult.mockResolvedValue({ displaced: null });
mocks.executeDetach.mockResolvedValue({ wasAttached: true, targetSessionId: 'sess-target' });
mocks.readModelRouteSnapshot.mockResolvedValue(null);
mocks.readPermissionMode.mockResolvedValue('auto');
@@ -293,21 +291,24 @@ describe('plan_review IM 卡片决策', () => {
});
describe('control:session-pick 重复接管替换', () => {
- it('已被旧 thread 接管 → detach 旧 binding + 旧锚点卡收口 + 新 attach 照常', async () => {
+ it('按串行 attach 实际替换的 owner 收口旧锚点', async () => {
const oldIdentity = {
channel: 'slack',
botContextId: 'BOT1',
userId: 'U_OLD',
scopeKey: 'anchor-old.ts',
};
- mocks.bindingFindByTarget.mockReturnValue(oldIdentity);
- mocks.bindingGetAttachCardMessageId.mockReturnValue('anchor-old');
+ mocks.bindingAttachWithResult.mockResolvedValueOnce({
+ displaced: {
+ identity: oldIdentity,
+ attachedViaCardMessageId: 'anchor-old',
+ },
+ });
const im = makeIm();
await pressSessionPick(im);
- // 旧接管被中断
- expect(mocks.executeDetach).toHaveBeenCalledWith(oldIdentity, 'slack-slash');
+ expect(mocks.executeDetach).not.toHaveBeenCalled();
// 旧锚点卡收口为 takeoverReplaced
expect(im.updateInteractiveCard).toHaveBeenCalledWith(
'anchor-old',
@@ -316,11 +317,19 @@ describe('control:session-pick 重复接管替换', () => {
}),
);
// 新 thread 正常 attach(identity 带新 scopeKey)
- expect(mocks.bindingAttach).toHaveBeenCalledWith(
+ expect(mocks.bindingAttachWithResult).toHaveBeenCalledWith(
expect.objectContaining({ userId: 'U_NEW', scopeKey: 'anchor-new.ts' }),
'sess-target',
expect.anything(),
);
+ const oldAnchorPatchIndex = (
+ im.updateInteractiveCard as ReturnType<typeof vi.fn>
+ ).mock.calls.findIndex(([messageId]) => messageId === 'anchor-old');
+ expect(mocks.bindingAttachWithResult.mock.invocationCallOrder[0]).toBeLessThan(
+ (im.updateInteractiveCard as ReturnType<typeof vi.fn>).mock.invocationCallOrder[
+ oldAnchorPatchIndex
+ ]!,
+ );
// 新锚点卡 morph 成已接管(带 🚪 按钮)
expect(im.updateInteractiveCard).toHaveBeenCalledWith(
'anchor-new',
@@ -330,23 +339,18 @@ describe('control:session-pick 重复接管替换', () => {
);
});
- it('detach 旧 binding 失败 → 中止, 不 attach(防双 thread 路由)', async () => {
- mocks.bindingFindByTarget.mockReturnValue({
- channel: 'slack',
- botContextId: 'BOT1',
- userId: 'U_OLD',
- scopeKey: 'anchor-old.ts',
- });
- mocks.bindingGetAttachCardMessageId.mockReturnValue('anchor-old');
- mocks.executeDetach.mockRejectedValue(new Error('db locked'));
+ it('新 thread attach 失败 → 旧 binding/listener/锚点保持不变', async () => {
+ mocks.bindingAttachWithResult.mockRejectedValueOnce(new Error('db locked'));
const im = makeIm();
await pressSessionPick(im);
- expect(mocks.bindingAttach).not.toHaveBeenCalled();
- // picker 卡收口为 attachFailed
+ expect(mocks.bindingAttachWithResult).toHaveBeenCalled();
+ expect(mocks.executeDetach).not.toHaveBeenCalled();
+ expect(turnRunner.prewireAttachedSession).not.toHaveBeenCalled();
+ // 新锚点显示写入失败
expect(im.updateInteractiveCard).toHaveBeenCalledWith(
- 'picker-msg',
+ 'anchor-new',
expect.objectContaining({
body: slackUi.cards.control.attachFailed('db locked'),
}),
@@ -355,30 +359,74 @@ describe('control:session-pick 重复接管替换', () => {
expect(im.updateInteractiveCard).not.toHaveBeenCalledWith('anchor-old', expect.anything());
});
- it('跨渠道旧 binding(feishu)→ detach 但不 patch 旧卡(本 im 实例 patch 不动)', async () => {
- mocks.bindingFindByTarget.mockReturnValue({
- channel: 'feishu',
- botContextId: 'FBOT',
- userId: 'ou_old',
+ it('跨渠道旧 binding(feishu)→ 原子替换但不 patch 旧卡(本 im 实例 patch 不动)', async () => {
+ mocks.bindingAttachWithResult.mockResolvedValueOnce({
+ displaced: {
+ identity: {
+ channel: 'feishu',
+ botContextId: 'FBOT',
+ userId: 'ou_old',
+ },
+ attachedViaCardMessageId: 'om_feishu_card',
+ },
});
- mocks.bindingGetAttachCardMessageId.mockReturnValue('om_feishu_card');
const im = makeIm();
await pressSessionPick(im);
- expect(mocks.executeDetach).toHaveBeenCalled();
+ expect(mocks.executeDetach).not.toHaveBeenCalled();
expect(im.updateInteractiveCard).not.toHaveBeenCalledWith('om_feishu_card', expect.anything());
+ expect(mocks.bindingAttachWithResult).toHaveBeenCalled();
+ });
+
+ it('Discord 接管普通会话由 attach 原子替换 Feishu,再 prewire Discord', async () => {
+ const discordAdapter = {
+ ...adapter,
+ channel: 'discord',
+ threadScoped: false,
+ } as ImChannelAdapter;
+
+ const im = makeIm();
+ await pressSessionPick(im, undefined, discordAdapter);
+
+ expect(mocks.executeDetach).not.toHaveBeenCalled();
+ expect(mocks.bindingAttach).toHaveBeenCalledWith(
+ expect.objectContaining({ channel: 'discord', userId: 'U_NEW' }),
+ 'sess-target',
+ expect.anything(),
+ );
+ expect(turnRunner.prewireAttachedSession).toHaveBeenCalledWith('BOT1', 'U_NEW');
+ expect(mocks.bindingAttach.mock.invocationCallOrder[0]).toBeLessThan(
+ turnRunner.prewireAttachedSession.mock.invocationCallOrder[0]!,
+ );
+ });
+
+ it('普通渠道新 attach 失败时不显式 detach 旧 binding', async () => {
+ mocks.bindingAttach.mockRejectedValueOnce(new Error('db locked'));
+ const discordAdapter = {
+ ...adapter,
+ channel: 'discord',
+ threadScoped: false,
+ } as ImChannelAdapter;
+
+ const im = makeIm();
+ await pressSessionPick(im, undefined, discordAdapter);
+
expect(mocks.bindingAttach).toHaveBeenCalled();
+ expect(mocks.executeDetach).not.toHaveBeenCalled();
+ expect(turnRunner.prewireAttachedSession).not.toHaveBeenCalled();
+ expect(im.updateInteractiveCard).toHaveBeenCalledWith(
+ 'picker-msg',
+ expect.objectContaining({ body: slackUi.cards.control.attachFailed('db locked') }),
+ );
});
it('无旧 binding → 不 detach, 直接 attach', async () => {
- mocks.bindingFindByTarget.mockReturnValue(null);
-
const im = makeIm();
await pressSessionPick(im);
expect(mocks.executeDetach).not.toHaveBeenCalled();
- expect(mocks.bindingAttach).toHaveBeenCalled();
+ expect(mocks.bindingAttachWithResult).toHaveBeenCalled();
});
});
diff --git a/apps/desktop/src/main/im/shared/__tests__/inboundMessage.test.ts b/apps/desktop/src/main/im/shared/__tests__/inboundMessage.test.ts
new file mode 100644
index 0000000000..5da33f0644
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/__tests__/inboundMessage.test.ts
@@ -0,0 +1,52 @@
+import { describe, expect, it } from 'vitest';
+
+import type { IMAttachment } from '@cindy/im';
+
+import { buildImUserMessage } from '../inboundMessage';
+
+describe('attached IM delivery context', () => {
+ it('uses a history-safe delivery rule without a persistent channel destination', () => {
+ const message = buildImUserMessage('测试discord', [], true);
+
+ expect(message).toEqual({
+ type: 'user',
+ content: expect.stringContaining('<cindy_delivery_context>'),
+ });
+ expect(message.content).toEqual(expect.stringContaining('automatically delivers'));
+ expect(message.content).toEqual(expect.stringContaining('bot, webhook, or outbound integration'));
+ expect(message.content).toEqual(expect.stringContaining('transport-independent'));
+ expect(message.content).not.toEqual(expect.stringMatching(/Discord|Feishu|Slack|source=/));
+ expect(message.content).toEqual(expect.stringContaining('\n\n测试discord'));
+ });
+
+ it('keeps the delivery context ahead of attachment content blocks', () => {
+ const attachment: IMAttachment = {
+ kind: 'image',
+ absPath: 'C:\\tmp\\image.png',
+ originalName: 'image.png',
+ mimeType: 'image/png',
+ };
+
+ expect(buildImUserMessage('', [attachment], true)).toEqual({
+ type: 'user',
+ content: [
+ {
+ type: 'text',
+ text: expect.stringContaining('<cindy_delivery_context>'),
+ },
+ {
+ type: 'image',
+ path: attachment.absPath,
+ mimeType: attachment.mimeType,
+ },
+ ],
+ });
+ });
+
+ it('keeps non-takeover IM messages byte-for-byte unchanged', () => {
+ expect(buildImUserMessage('普通飞书消息', [])).toEqual({
+ type: 'user',
+ content: '普通飞书消息',
+ });
+ });
+});
diff --git a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
index c1d9289524..aafc1cba0b 100644
--- a/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
+++ b/apps/desktop/src/main/im/shared/__tests__/turnRunnerThreadRouting.test.ts
@@ -108,11 +108,13 @@ import { ui as slackUi } from './threadUiFixture';
interface SessionHarness {
session: Session;
send: ReturnType<typeof vi.fn>;
+ unsubscribe: ReturnType<typeof vi.fn>;
emit(event: AgentEvent): void;
}
function makeSessionHarness(sessionId: string): SessionHarness {
const listeners: Array<(event: AgentEvent) => void> = [];
+ const unsubscribe = vi.fn();
const send = vi.fn(
async (
_message: Parameters<Session['send']>[0],
@@ -129,7 +131,11 @@ function makeSessionHarness(sessionId: string): SessionHarness {
isTurnRunning: vi.fn(() => false),
onEvent(listener: (event: AgentEvent) => void) {
listeners.push(listener);
- return () => {};
+ return () => {
+ unsubscribe();
+ const index = listeners.indexOf(listener);
+ if (index >= 0) listeners.splice(index, 1);
+ };
},
setInteractionListener: vi.fn(),
close: vi.fn(async () => undefined),
@@ -137,6 +143,7 @@ function makeSessionHarness(sessionId: string): SessionHarness {
return {
session,
send,
+ unsubscribe,
emit(event: AgentEvent) {
for (const l of [...listeners]) l(event);
},
@@ -364,6 +371,12 @@ describe('turnRunner thread = session 路由(slack threadScoped)', () => {
// 接管路由: 不经 repo 建行, 直接 wire desktop session + IPC fanout
expect(fakeRepo.createSession).not.toHaveBeenCalled();
expect(harnesses.get('desktop-sess-1')!.send).toHaveBeenCalledTimes(1);
+ expect(harnesses.get('desktop-sess-1')!.send).toHaveBeenCalledWith(
+ expect.objectContaining({
+ content: expect.stringContaining('<cindy_delivery_context>'),
+ }),
+ expect.anything(),
+ );
expect(mocks.wireSessionToIpcExternal).toHaveBeenCalledTimes(1);
// binding 验证走了带 scopeKey 的 identity
expect(mocks.bindingGet).toHaveBeenCalledWith(
@@ -371,6 +384,58 @@ describe('turnRunner thread = session 路由(slack threadScoped)', () => {
);
});
+ it('replacement detach keeps the old listener until its active turn drains', async () => {
+ mocks.bindingGet.mockImplementation(
+ (id: { scopeKey?: string }) =>
+ id.scopeKey === '300.3' || id.scopeKey === '400.4' ? 'desktop-sess-1' : null,
+ );
+ mocks.dbSelect.mockReturnValue({
+ from: () => ({
+ where: () => ({
+ limit: async () => [
+ {
+ id: 'desktop-sess-1',
+ agentKind: 'cc',
+ workingDir: '/tmp/desktop-wd',
+ model: 'claude-opus-4-7',
+ effort: 'xhigh',
+ permissionMode: 'auto',
+ fastMode: false,
+ sdkSessionId: 'sdk-1',
+ title: 'T',
+ },
+ ],
+ }),
+ }),
+ });
+ const stream = streamingHandleStub();
+ mocks.slackIm.startStreamingText.mockResolvedValue(stream);
+ await runTurn('300.3');
+ const harness = harnesses.get('desktop-sess-1')!;
+
+ runner.detachFromSession('desktop-sess-1');
+ expect(harness.unsubscribe).not.toHaveBeenCalled();
+ expect(mocks.installDesktopInteractionListener).not.toHaveBeenCalled();
+ let rewireResolved = false;
+ const rewire = runner.prewireAttachedSession('T1', 'U2', '400.4').then(() => {
+ rewireResolved = true;
+ });
+ await Promise.resolve();
+ expect(rewireResolved).toBe(false);
+
+ harness.emit({ type: 'text', data: { text: 'late output' } } as AgentEvent);
+ await vi.waitFor(() => expect(mocks.slackIm.startStreamingText).toHaveBeenCalled());
+ harness.emit({ type: 'done' } as AgentEvent);
+
+ await vi.waitFor(() => {
+ expect(stream.finalize).toHaveBeenCalledWith('late output');
+ expect(harness.unsubscribe).toHaveBeenCalledOnce();
+ expect(mocks.installDesktopInteractionListener).toHaveBeenCalledWith(harness.session);
+ });
+ await rewire;
+ expect(rewireResolved).toBe(true);
+ });
+
it('新 thread 首条消息: 名片卡先发进 thread, 续聊不再发', async () => {
await runTurn('100.1');
expect(mocks.slackIm.sendInteractiveCard).toHaveBeenCalledTimes(1);
diff --git a/apps/desktop/src/main/im/shared/cardActionHandler.ts b/apps/desktop/src/main/im/shared/cardActionHandler.ts
index 518a16485e..7d9bb1f702 100644
--- a/apps/desktop/src/main/im/shared/cardActionHandler.ts
+++ b/apps/desktop/src/main/im/shared/cardActionHandler.ts
@@ -53,7 +53,7 @@ import {
} from './controlProjects';
import { exitControl } from './controlState';
import { startThreadControlFlow } from './controlFlow';
-import { bindingStore, executeDetach } from '../binding';
+import { bindingStore, executeDetach, type BindingAttachResult } from '../binding';
import { generateTakeoverSummary } from './sessionSummary';
import { broadcastSessionCreated } from './sessionBroadcast';
import type { IdentityKey } from '@cindy/im';
@@ -129,9 +129,10 @@ export function createCardActionHandler(
scopeKey: string;
card: { title: string; body: string };
},
- ): Promise<boolean> {
+ ): Promise<BindingAttachResult | null> {
+ let attachResult: BindingAttachResult;
try {
- await bindingStore.attach(
+ attachResult = await bindingStore.attachWithResult(
{
channel,
botContextId: args.botContextId,
@@ -152,7 +153,7 @@ export function createCardActionHandler(
} catch {
/* swallow */
}
- return false;
+ return null;
}
try {
await im.updateInteractiveCard(args.anchorMessageId, {
@@ -164,7 +165,7 @@ export function createCardActionHandler(
const msg = err instanceof Error ? err.message : String(err);
log.warn(`anchor card morph failed (non-fatal): ${msg}`);
}
- return true;
+ return attachResult;
}
/**
@@ -181,7 +182,11 @@ export function createCardActionHandler(
sessionId: string;
card: { title: string; body: string };
},
- ): Promise<{ scopeKey: string; rootMessageId: string } | null> {
+ ): Promise<{
+ scopeKey: string;
+ rootMessageId: string;
+ displaced: BindingAttachResult['displaced'];
+ } | null> {
if (!threadUi || !im.threadKeyForMessage) return null;
let rootMessageId: string;
try {
@@ -203,8 +208,9 @@ export function createCardActionHandler(
return null;
}
const scopeKey = im.threadKeyForMessage(rootMessageId);
+ let attachResult: BindingAttachResult;
try {
- await bindingStore.attach(
+ attachResult = await bindingStore.attachWithResult(
{ channel, botContextId: args.botContextId, userId: args.userId, scopeKey },
args.sessionId,
{ attachedViaCardMessageId: rootMessageId },
@@ -223,7 +229,7 @@ export function createCardActionHandler(
}
return null;
}
- return { scopeKey, rootMessageId };
+ return { scopeKey, rootMessageId, displaced: attachResult.displaced };
}
async function handleModelPick(im: ChannelIM, event: IMCardActionEvent): Promise<void> {
@@ -574,46 +580,6 @@ export function createCardActionHandler(
// 顶层发"已接管"root 卡 → 卡 ts 即 scopeKey → attach(identity+scope) →
// brief 总结发进该 thread → picker 卡 patch 为 resolved。
if (threadScoped && threadUi) {
- // 该 desktop session 已被某个 thread 接管 → 中断旧接管, 由新 thread 替换:
- // 先 executeDetach(旧 identity) 把 binding/in-process state 清干净(否则
- // 旧 thread 的 forward 项还指着同一 session, 双 thread 同时路由), 再把旧
- // 锚点/root 卡收口成"已转移"。detach 失败必须中止 — 不能在双路由风险下
- // 继续 attach。
- const existing = bindingStore.findByTarget(sessionId);
- if (existing) {
- const oldAnchorId = bindingStore.getAttachCardMessageId(existing);
- try {
- await executeDetach(existing, `${channel}-slash`);
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- log.error(`session-pick replace: detach old binding failed: ${msg}`);
- exitControl(botContextId, event.senderId);
- try {
- await im.updateInteractiveCard(
- event.messageId,
- cards.buildResolvedCard(ui.cards.control.attachFailed(msg)),
- );
- } catch {
- /* swallow */
- }
- return;
- }
- // 旧锚点卡收口 — 仅同渠道(跨渠道的旧卡片这个 im 实例 patch 不动);
- // 旧锚点就是本次锚点(同 thread 重复选)时跳过, 后面 morph 会覆盖。
- const anchorIdInPayload = String(event.payload.anchorMessageId ?? '');
- if (oldAnchorId && existing.channel === channel && oldAnchorId !== anchorIdInPayload) {
- try {
- await im.updateInteractiveCard(
- oldAnchorId,
- cards.buildResolvedCard(threadUi.takeoverReplaced(sessionTitle)),
- );
- } catch (err) {
- const msg = err instanceof Error ? err.message : String(err);
- log.warn(`session-pick replace: old anchor patch failed (non-fatal): ${msg}`);
- }
- }
- }
-
try {
await im.patchMarkdownCard(
event.messageId,
@@ -625,10 +591,13 @@ export function createCardActionHandler(
}
const anchorMessageId = String(event.payload.anchorMessageId ?? '');
- let established: { scopeKey: string } | null = null;
+ let established: {
+ scopeKey: string;
+ displaced: BindingAttachResult['displaced'];
+ } | null = null;
if (anchorMessageId && event.scopeKey) {
// 锚点流程: 选择卡就在锚点 thread 里, scopeKey = 锚点 ts
- const ok = await bindTakeoverToAnchor(im, {
+ const attachResult = await bindTakeoverToAnchor(im, {
botContextId,
userId: event.senderId,
sessionId,
@@ -636,7 +605,9 @@ export function createCardActionHandler(
scopeKey: event.scopeKey,
card: threadUi.takeoverCard(sessionTitle, displayName),
});
- established = ok ? { scopeKey: event.scopeKey } : null;
+ established = attachResult
+ ? { scopeKey: event.scopeKey, displaced: attachResult.displaced }
+ : null;
} else {
established = await establishThreadTakeover(im, {
botContextId,
@@ -658,6 +629,28 @@ export function createCardActionHandler(
return;
}
+ // New binding is committed now. Only after that point may the old root
+ // card claim its takeover was replaced. Cross-channel cards cannot be
+ // patched through this adapter, and the current anchor is morphed below.
+ const anchorIdInPayload = String(event.payload.anchorMessageId ?? '');
+ const displacedAnchorId = established.displaced?.attachedViaCardMessageId;
+ if (
+ established.displaced &&
+ displacedAnchorId &&
+ established.displaced.identity.channel === channel &&
+ displacedAnchorId !== anchorIdInPayload
+ ) {
+ try {
+ await im.updateInteractiveCard(
+ displacedAnchorId,
+ cards.buildResolvedCard(threadUi.takeoverReplaced(sessionTitle)),
+ );
+ } catch (err) {
+ const msg = err instanceof Error ? err.message : String(err);
+ log.warn(`session-pick replace: old anchor patch failed (non-fatal): ${msg}`);
+ }
+ }
+
// picker 卡收口(顶层) — root 卡才是这次接管的"家"
try {
await im.updateInteractiveCard(
diff --git a/apps/desktop/src/main/im/shared/inboundMessage.ts b/apps/desktop/src/main/im/shared/inboundMessage.ts
new file mode 100644
index 0000000000..a5f6346e4c
--- /dev/null
+++ b/apps/desktop/src/main/im/shared/inboundMessage.ts
@@ -0,0 +1,47 @@
+import type { UserContentBlock, UserMessage } from '@cindy/maker-core';
+import type { IMAttachment } from '@cindy/im';
+
+const TAKEOVER_DELIVERY_CONTEXT =
+ '<cindy_delivery_context>' +
+ 'Reply normally to the user message in this turn. Cindy automatically delivers your final response ' +
+ 'to the conversation that sent it. Do not ask the user to configure a bot, webhook, or outbound ' +
+ 'integration, and do not use a proactive outbound tool unless the user explicitly requests a separate ' +
+ 'outbound message. This delivery rule is transport-independent; never infer a persistent destination ' +
+ 'from earlier turns.' +
+ '</cindy_delivery_context>';
+
+/**
+ * Build the model-facing message for an IM turn.
+ *
+ * Attached desktop sessions are created without channel vendor options, so the
+ * model needs to know that normal replies are already delivered. Native agents
+ * may retain this UserMessage in their own history; consequently the hint is a
+ * transport-invariant rule and deliberately contains no vendor or destination.
+ * The local transcript still receives the original user text in turnRunner.
+ */
+export function buildImUserMessage(
+ text: string,
+ attachments: IMAttachment[],
+ attachedTakeover = false,
+): UserMessage {
+ const deliveryContext = attachedTakeover ? TAKEOVER_DELIVERY_CONTEXT : null;
+
+ if (attachments.length === 0) {
+ return {
+ type: 'user',
+ content: deliveryContext ? `${deliveryContext}\n\n${text}` : text,
+ };
+ }
+
+ const blocks: UserContentBlock[] = [];
+ if (deliveryContext) blocks.push({ type: 'text', text: deliveryContext });
+ if (text) blocks.push({ type: 'text', text });
+ for (const att of attachments) {
+ blocks.push({
+ type: att.kind === 'image' ? 'image' : 'file',
+ path: att.absPath,
+ mimeType: att.mimeType,
+ });
+ }
+ return { type: 'user', content: blocks };
+}
diff --git a/apps/desktop/src/main/im/shared/turnRunner.ts b/apps/desktop/src/main/im/shared/turnRunner.ts
index b20140921d..0f7b593ce0 100644
--- a/apps/desktop/src/main/im/shared/turnRunner.ts
+++ b/apps/desktop/src/main/im/shared/turnRunner.ts
@@ -64,6 +64,7 @@ import type { IMAttachment, InteractiveCardSpec, StreamingTextHandle } from '@ci
import { persistUserMessage } from '../messagePersistence';
import { bindingStore } from '../binding';
+import { buildImUserMessage } from './inboundMessage';
import {
wireSessionToIpcExternal,
installDesktopInteractionListener,
@@ -164,6 +165,8 @@ interface QueuedSend {
notified: boolean;
}
+type DetachDrainOutcome = 'rewire' | 'cancelled';
+
interface SessionState {
/** Maker session (in-process). */
makerSession: MakerSession;
@@ -179,6 +182,13 @@ interface SessionState {
dispatchRetryTimer: ReturnType<typeof setTimeout> | null;
/** Cleanup fns from session.onEvent / setInteractionListener. */
unsubscribers: Array<() => void>;
+ /**
+ * Replacement detach waits for the current IM-owned turn to finish before
+ * removing its event listener. New wiring for the same channel/session waits
+ * on this promise instead of reusing the retiring state.
+ */
+ detachDrainPromise: Promise<DetachDrainOutcome> | null;
+ resolveDetachDrain: ((outcome: DetachDrainOutcome) => void) | null;
/**
* true = 这个 session 是 desktop 那个 row 被本渠道接管 (C 状态);
* false = 渠道默认 session (B' 状态)。
@@ -562,7 +572,7 @@ export function createTurnRunner(
const item: QueuedSend = {
turn,
- userMessage: buildUserMessage(text, attachments),
+ userMessage: buildImUserMessage(text, attachments, target.attached),
rowId: row.id,
text,
attachments,
@@ -673,6 +683,11 @@ export function createTurnRunner(
if (normalized.reason === 'SESSION_RUNNING') {
const i = state.queue.indexOf(item.turn);
if (i >= 0) state.queue.splice(i, 1);
+ if (state.detachDrainPromise) {
+ await completeTurnCallbackAfterAck(item.turn);
+ finishDeferredDetachIfIdle(state);
+ return;
+ }
state.sendQueue.unshift(item);
log.info(
`SESSION_RUNNING race for session=${rowId.slice(-8)} — requeued at head (pendingSends=${state.sendQueue.length})`,
@@ -806,7 +821,16 @@ export function createTurnRunner(
async function ensureSessionWired(target: RouteTarget, userId: string): Promise<SessionState> {
const existing = sessionStates.get(target.row.id);
- if (existing) return existing;
+ if (existing) {
+ if (existing.detachDrainPromise) {
+ const outcome = await existing.detachDrainPromise;
+ if (outcome === 'cancelled') {
+ throw new Error(`session wiring cancelled during cleanup: ${target.row.id}`);
+ }
+ return ensureSessionWired(target, userId);
+ }
+ return existing;
+ }
const inFlight = wiringInFlight.get(target.row.id);
if (inFlight) return inFlight;
@@ -949,6 +973,8 @@ export function createTurnRunner(
sendQueue: [],
dispatchRetryTimer: null,
unsubscribers: [],
+ detachDrainPromise: null,
+ resolveDetachDrain: null,
attached,
scheduledTranspond: null,
};
@@ -1220,22 +1246,6 @@ export function createTurnRunner(
}
}
- function buildUserMessage(text: string, attachments: IMAttachment[]): UserMessage {
- if (attachments.length === 0) {
- return { type: 'user', content: text };
- }
- const blocks: import('@cindy/maker-core').UserContentBlock[] = [];
- if (text) blocks.push({ type: 'text', text });
- for (const att of attachments) {
- blocks.push({
- type: att.kind === 'image' ? 'image' : 'file',
- path: att.absPath,
- mimeType: att.mimeType,
- });
- }
- return { type: 'user', content: blocks };
- }
-
// ── event routing ───────────────────────────────────────────────────────────
function handleEventFor(localSessionId: string, userId: string) {
@@ -1666,6 +1676,7 @@ export function createTurnRunner(
} catch {
/* 忽略失败:派发失败提示不能再阻塞收口。 */
}
+ if (finishDeferredDetachIfIdle(state)) return;
// 一条 pre-dispatch failure 不能卡死后面的排队消息 — 继续放行。
maybeDispatchNextQueued(state, userId);
}
@@ -1858,6 +1869,7 @@ export function createTurnRunner(
log.info(
`turn done for session=...${(state.makerSession.id ?? '').slice(-8)}, queueDepth=${state.queue.length}`,
);
+ if (finishDeferredDetachIfIdle(state)) return;
// 收口完成(最终卡片已 finalize)后再派发下一条排队消息 — IM 时间线保持
// "上一轮输出 → 下一条开始流式"的自然顺序。
maybeDispatchNextQueued(state, userId);
@@ -1892,6 +1904,7 @@ export function createTurnRunner(
/* swallow */
}
}
+ if (finishDeferredDetachIfIdle(state)) return;
// error 收口同样要继续放行排队消息 — 一条失败不能卡死后面的队列。
maybeDispatchNextQueued(state, userId);
}
@@ -2087,23 +2100,44 @@ export function createTurnRunner(
function detachFromSession(sessionId: string): void {
const state = sessionStates.get(sessionId);
if (!state?.attached) return;
- clearPendingSends(state);
- clearQueuedTurnTimers(state);
- for (const u of state.unsubscribers) {
- try {
- u();
- } catch {
- /* swallow */
+ if (state.queue.length > 0) {
+ clearPendingSends(state);
+ if (!state.detachDrainPromise) {
+ state.detachDrainPromise = new Promise<DetachDrainOutcome>((resolve) => {
+ state.resolveDetachDrain = resolve;
+ });
}
+ log.info(
+ `deferring ${channel} detach until active turn drains session=${sessionId.slice(-8)}`,
+ );
+ return;
}
- state.unsubscribers = [];
+ detachSessionStateNow(sessionId, state);
+ }
+
+ function finishDeferredDetachIfIdle(state: SessionState): boolean {
+ if (!state.detachDrainPromise || state.queue.length > 0) return false;
+ detachSessionStateNow(state.makerSession.id, state);
+ return true;
+ }
+
+ function detachSessionStateNow(sessionId: string, state: SessionState): void {
+ sessionStates.delete(sessionId);
+ cleanupSessionState(state);
// 还原 desktop 版 interaction listener — 接管期间被本渠道版覆盖了,
// 不还原 desktop renderer 永远收不到 permission 弹窗。
installDesktopInteractionListener(state.makerSession);
- sessionStates.delete(sessionId);
+ settleDetachDrain(state, 'rewire');
log.info(`detached ${channel} hook from session=${sessionId.slice(-8)}`);
}
+ function settleDetachDrain(state: SessionState, outcome: DetachDrainOutcome): void {
+ const resolveDetachDrain = state.resolveDetachDrain;
+ state.detachDrainPromise = null;
+ state.resolveDetachDrain = null;
+ resolveDetachDrain?.(outcome);
+ }
+
function disposeAllSessions(): Promise<void> {
const aborts: Promise<void>[] = [];
for (const [, state] of sessionStates) {
@@ -2112,6 +2146,7 @@ export function createTurnRunner(
// queue stays empty; logout must not abort that desktop-owned work.
const hasImTurnInFlight = state.queue.length > 0;
cleanupSessionState(state);
+ settleDetachDrain(state, 'cancelled');
if (hasImTurnInFlight) {
aborts.push(
state.makerSession.abort().catch((err) => {
@@ -2172,6 +2207,7 @@ export function createTurnRunner(
if (!state) return;
sessionStates.delete(sessionId);
cleanupSessionState(state);
+ settleDetachDrain(state, 'cancelled');
try {
await state.makerSession.close();
} catch (err) {
@@ -2185,6 +2221,7 @@ export function createTurnRunner(
if (!state) return;
sessionStates.delete(sessionId);
cleanupSessionState(state);
+ settleDetachDrain(state, 'cancelled');
log.info(`forgot cached ${channel} session=${sessionId.slice(-8)} after ${reason}`);
}
diff --git a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
index bc201df741..a930cd8a80 100644
--- a/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
+++ b/apps/desktop/src/main/localDb/client/WorkerThreadTransport.ts
@@ -306,6 +306,10 @@ function dispatchTx(readyDb, payload) {
return sessionAgentSwitchFallback(readyDb, request.args);
case 'message.delete':
return messageDelete(readyDb, request.args);
+ case 'im.deleteBindings':
+ return imDeleteBindings(readyDb, request.args);
+ case 'im.replaceBinding':
+ return imReplaceBinding(readyDb, request.args);
case 'session.importShare':
return sessionImportShare(readyDb, request.args);
default:
@@ -313,6 +317,61 @@ function dispatchTx(readyDb, payload) {
}
}
+// ⚠️ 与 worker/opHandlers/tx.ts 的 imDeleteBindings 保持一致。
+function imDeleteBindings(readyDb, args) {
+ const payload = asRecord(args, 'im.deleteBindings args');
+ const identities = expectArray(payload.identities, 'identities').map((raw, index) => {
+ const identity = asRecord(raw, 'identities.' + index);
+ return {
+ channel: expectString(identity.channel, 'identities.' + index + '.channel'),
+ botContextId: expectString(identity.botContextId, 'identities.' + index + '.botContextId'),
+ userId: expectString(identity.userId, 'identities.' + index + '.userId'),
+ scopeKey: expectString(identity.scopeKey, 'identities.' + index + '.scopeKey'),
+ };
+ });
+ const deleteBinding = readyDb.prepare(
+ 'DELETE FROM im_bindings WHERE channel = ? AND bot_context_id = ? AND user_id = ? AND scope_key = ?',
+ );
+ return readyDb.transaction(() => {
+ for (const identity of identities) {
+ deleteBinding.run(
+ identity.channel,
+ identity.botContextId,
+ identity.userId,
+ identity.scopeKey,
+ );
+ }
+ })();
+}
+
+// ⚠️ 与 worker/opHandlers/tx.ts 的 imReplaceBinding 保持一致。
+function imReplaceBinding(readyDb, args) {
+ const payload = asRecord(args, 'im.replaceBinding args');
+ const channel = expectString(payload.channel, 'channel');
+ const botContextId = expectString(payload.botContextId, 'botContextId');
+ const userId = expectString(payload.userId, 'userId');
+ const scopeKey = expectString(payload.scopeKey, 'scopeKey');
+ const targetSessionId = expectString(payload.targetSessionId, 'targetSessionId');
+ const attachedAt = expectNumber(payload.attachedAt, 'attachedAt');
+ const attachedViaCardMessageId = nullableString(payload.attachedViaCardMessageId);
+ return readyDb.transaction(() => {
+ readyDb.prepare(
+ 'DELETE FROM im_bindings WHERE target_session_id = ? OR (channel = ? AND bot_context_id = ? AND user_id = ? AND scope_key = ?)',
+ ).run(targetSessionId, channel, botContextId, userId, scopeKey);
+ readyDb.prepare(
+ 'INSERT INTO im_bindings (channel, bot_context_id, user_id, scope_key, target_session_id, attached_at, attached_via_card_message_id) VALUES (?, ?, ?, ?, ?, ?, ?)',
+ ).run(
+ channel,
+ botContextId,
+ userId,
+ scopeKey,
+ targetSessionId,
+ attachedAt,
+ attachedViaCardMessageId,
+ );
+ })();
+}
+
// ⚠️ 与 worker/opHandlers/tx.ts 的同名事务保持一致。
function sessionAgentSwitchFallback(readyDb, args) {
const payload = asRecord(args, 'session.agentSwitchFallback args');
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 1ca95eec7d..bec6f012ab 100644
--- a/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
+++ b/apps/desktop/src/main/localDb/client/__tests__/tx.test.ts
@@ -88,6 +88,17 @@ CREATE TABLE messages (
rewind_at INTEGER,
UNIQUE(session_id, client_id)
);
+CREATE TABLE im_bindings (
+ channel TEXT NOT NULL,
+ bot_context_id TEXT NOT NULL,
+ user_id TEXT NOT NULL,
+ scope_key TEXT NOT NULL DEFAULT '',
+ target_session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
+ attached_at INTEGER NOT NULL,
+ attached_via_card_message_id TEXT,
+ PRIMARY KEY(channel, bot_context_id, user_id, scope_key)
+);
+CREATE INDEX idx_im_bindings_target ON im_bindings(target_session_id);
CREATE TABLE embedding_jobs (
rowid INTEGER PRIMARY KEY AUTOINCREMENT,
source TEXT NOT NULL,
@@ -860,6 +871,197 @@ describe('db worker tx handlers', () => {
});
});
+ it('im.replaceBinding atomically replaces the target owner and the identity old target', async () => {
+ await withClient(async (client) => {
+ await seedSession(client, 'desktop-target');
+ await seedSession(client, 'discord-old-target');
+ await client.exec(
+ `INSERT INTO im_bindings (
+ channel, bot_context_id, user_id, scope_key, target_session_id,
+ attached_at, attached_via_card_message_id
+ ) VALUES (?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?)`,
+ [
+ 'feishu',
+ 'feishu-bot',
+ 'ou_old',
+ '',
+ 'desktop-target',
+ 100,
+ 'feishu-card',
+ 'discord',
+ 'discord-bot',
+ '123456',
+ '',
+ 'discord-old-target',
+ 150,
+ 'discord-old-card',
+ ],
+ );
+
+ await client.tx('im.replaceBinding', {
+ channel: 'discord',
+ botContextId: 'discord-bot',
+ userId: '123456',
+ scopeKey: '',
+ targetSessionId: 'desktop-target',
+ attachedAt: 200,
+ attachedViaCardMessageId: 'discord-card',
+ });
+
+ await expect(
+ client.query(
+ `SELECT channel, bot_context_id, user_id, scope_key, target_session_id,
+ attached_at, attached_via_card_message_id
+ FROM im_bindings`,
+ ),
+ ).resolves.toEqual([
+ {
+ channel: 'discord',
+ bot_context_id: 'discord-bot',
+ user_id: '123456',
+ scope_key: '',
+ target_session_id: 'desktop-target',
+ attached_at: 200,
+ attached_via_card_message_id: 'discord-card',
+ },
+ ]);
+ });
+ });
+
+ it('im.replaceBinding restores the previous owner when the new insert fails', async () => {
+ await withClient(async (client) => {
+ await seedSession(client, 'desktop-target');
+ await client.exec(
+ `INSERT INTO im_bindings (
+ channel, bot_context_id, user_id, scope_key, target_session_id,
+ attached_at, attached_via_card_message_id
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ ['feishu', 'feishu-bot', 'ou_old', '', 'desktop-target', 100, 'feishu-card'],
+ );
+ await client.exec(
+ `CREATE TRIGGER reject_discord_binding
+ BEFORE INSERT ON im_bindings
+ WHEN NEW.channel = 'discord'
+ BEGIN
+ SELECT RAISE(ABORT, 'simulated binding insert failure');
+ END`,
+ );
+
+ await expect(
+ client.tx('im.replaceBinding', {
+ channel: 'discord',
+ botContextId: 'discord-bot',
+ userId: '123456',
+ scopeKey: '',
+ targetSessionId: 'desktop-target',
+ attachedAt: 200,
+ attachedViaCardMessageId: 'discord-card',
+ }),
+ ).rejects.toThrow('simulated binding insert failure');
+
+ await expect(
+ client.query(
+ `SELECT channel, bot_context_id, user_id, scope_key, target_session_id,
+ attached_at, attached_via_card_message_id
+ FROM im_bindings`,
+ ),
+ ).resolves.toEqual([
+ {
+ channel: 'feishu',
+ bot_context_id: 'feishu-bot',
+ user_id: 'ou_old',
+ scope_key: '',
+ target_session_id: 'desktop-target',
+ attached_at: 100,
+ attached_via_card_message_id: 'feishu-card',
+ },
+ ]);
+ });
+ });
+
+ it('im.deleteBindings rolls back every startup cleanup when a later delete fails', async () => {
+ await withClient(async (client) => {
+ await seedSession(client, 'desktop-target');
+ await client.exec(
+ `INSERT INTO im_bindings (
+ channel, bot_context_id, user_id, scope_key, target_session_id,
+ attached_at, attached_via_card_message_id
+ ) VALUES (?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?)`,
+ [
+ 'feishu',
+ 'feishu-bot',
+ 'ou_old',
+ '',
+ 'desktop-target',
+ 100,
+ 'feishu-card',
+ 'discord',
+ 'discord-bot',
+ '123456',
+ '',
+ 'desktop-target',
+ 150,
+ 'discord-card',
+ ],
+ );
+ await client.exec(
+ `CREATE TRIGGER reject_discord_binding_delete
+ BEFORE DELETE ON im_bindings
+ WHEN OLD.channel = 'discord'
+ BEGIN
+ SELECT RAISE(ABORT, 'simulated binding delete failure');
+ END`,
+ );
+
+ await expect(
+ client.tx('im.deleteBindings', {
+ identities: [
+ {
+ channel: 'feishu',
+ botContextId: 'feishu-bot',
+ userId: 'ou_old',
+ scopeKey: '',
+ },
+ {
+ channel: 'discord',
+ botContextId: 'discord-bot',
+ userId: '123456',
+ scopeKey: '',
+ },
+ ],
+ }),
+ ).rejects.toThrow('simulated binding delete failure');
+
+ await expect(
+ client.query(
+ `SELECT channel, bot_context_id, user_id, scope_key, target_session_id,
+ attached_at, attached_via_card_message_id
+ FROM im_bindings
+ ORDER BY attached_at`,
+ ),
+ ).resolves.toEqual([
+ {
+ channel: 'feishu',
+ bot_context_id: 'feishu-bot',
+ user_id: 'ou_old',
+ scope_key: '',
+ target_session_id: 'desktop-target',
+ attached_at: 100,
+ attached_via_card_message_id: 'feishu-card',
+ },
+ {
+ channel: 'discord',
+ bot_context_id: 'discord-bot',
+ user_id: '123456',
+ scope_key: '',
+ target_session_id: 'desktop-target',
+ attached_at: 150,
+ attached_via_card_message_id: 'discord-card',
+ },
+ ]);
+ });
+ });
+
it('embedding.markDone marks jobs done without writing vectors', async () => {
await withClient(async (client) => {
const rowid = await insertJob(client, { sourceId: 'm1' });
diff --git a/apps/desktop/src/main/localDb/client/tx/types.ts b/apps/desktop/src/main/localDb/client/tx/types.ts
index c05bbda011..712ebd0ece 100644
--- a/apps/desktop/src/main/localDb/client/tx/types.ts
+++ b/apps/desktop/src/main/localDb/client/tx/types.ts
@@ -18,6 +18,8 @@ export type DbTxName =
| 'sessions.setStatus'
| 'session.agentSwitchFallback'
| 'message.delete'
+ | 'im.deleteBindings'
+ | 'im.replaceBinding'
| 'session.importShare';
export interface CodexImportMessagesArgs {
@@ -331,6 +333,29 @@ export interface SessionImportShareArgs {
}>;
}
+/**
+ * Atomically replace every persisted owner of a desktop session with one IM
+ * identity. The same identity may already point at another session.
+ */
+export interface ImReplaceBindingArgs {
+ channel: string;
+ botContextId: string;
+ userId: string;
+ scopeKey: string;
+ targetSessionId: string;
+ attachedAt: number;
+ attachedViaCardMessageId: string | null;
+}
+
+export interface ImDeleteBindingsArgs {
+ identities: Array<{
+ channel: string;
+ botContextId: string;
+ userId: string;
+ scopeKey: string;
+ }>;
+}
+
export type DbTxArgsByName = {
'codex.importMessages': CodexImportMessagesArgs;
'claude.importMessages': ClaudeImportMessagesArgs;
@@ -351,6 +376,8 @@ export type DbTxArgsByName = {
'sessions.setStatus': SessionsSetStatusArgs;
'session.agentSwitchFallback': SessionAgentSwitchFallbackArgs;
'message.delete': MessageDeleteArgs;
+ 'im.deleteBindings': ImDeleteBindingsArgs;
+ 'im.replaceBinding': ImReplaceBindingArgs;
'session.importShare': SessionImportShareArgs;
};
@@ -374,5 +401,7 @@ export type DbTxResultByName = {
'sessions.setStatus': SessionsSetStatusResultItem[];
'session.agentSwitchFallback': undefined;
'message.delete': MessageDeleteResult;
+ 'im.deleteBindings': undefined;
+ 'im.replaceBinding': undefined;
'session.importShare': { messageCount: number };
};
diff --git a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
index 1895ef4652..36bec8feac 100644
--- a/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
+++ b/apps/desktop/src/main/localDb/worker/opHandlers/tx.ts
@@ -54,6 +54,10 @@ export function tx(db: Database.Database, args: unknown): unknown {
return sessionAgentSwitchFallback(db, txArgs);
case 'message.delete':
return messageDelete(db, txArgs);
+ case 'im.deleteBindings':
+ return imDeleteBindings(db, txArgs);
+ case 'im.replaceBinding':
+ return imReplaceBinding(db, txArgs);
case 'session.importShare':
return sessionImportShare(db, txArgs);
default:
@@ -61,6 +65,73 @@ export function tx(db: Database.Database, args: unknown): unknown {
}
}
+/** Remove every stale startup binding as one all-or-nothing repair. */
+function imDeleteBindings(db: Database.Database, args: unknown): void {
+ const payload = asRecord(args, 'im.deleteBindings args');
+ const identities = expectArray(payload.identities, 'identities').map((raw, index) => {
+ const identity = asRecord(raw, `identities.${index}`);
+ return {
+ channel: expectString(identity.channel, `identities.${index}.channel`),
+ botContextId: expectString(identity.botContextId, `identities.${index}.botContextId`),
+ userId: expectString(identity.userId, `identities.${index}.userId`),
+ scopeKey: expectString(identity.scopeKey, `identities.${index}.scopeKey`),
+ };
+ });
+ const deleteBinding = db.prepare(
+ `DELETE FROM im_bindings
+ WHERE channel = ? AND bot_context_id = ? AND user_id = ? AND scope_key = ?`,
+ );
+ const transaction = db.transaction(() => {
+ for (const identity of identities) {
+ deleteBinding.run(
+ identity.channel,
+ identity.botContextId,
+ identity.userId,
+ identity.scopeKey,
+ );
+ }
+ });
+ transaction();
+}
+
+/**
+ * IM takeover replacement must not expose the delete-before-insert gap: if
+ * the insert fails, SQLite restores both the previous target owner and this
+ * identity's previous target.
+ */
+function imReplaceBinding(db: Database.Database, args: unknown): void {
+ const payload = asRecord(args, 'im.replaceBinding args');
+ const channel = expectString(payload.channel, 'channel');
+ const botContextId = expectString(payload.botContextId, 'botContextId');
+ const userId = expectString(payload.userId, 'userId');
+ const scopeKey = expectString(payload.scopeKey, 'scopeKey');
+ const targetSessionId = expectString(payload.targetSessionId, 'targetSessionId');
+ const attachedAt = expectNumber(payload.attachedAt, 'attachedAt');
+ const attachedViaCardMessageId = nullableString(payload.attachedViaCardMessageId);
+ const transaction = db.transaction(() => {
+ db.prepare(
+ `DELETE FROM im_bindings
+ WHERE target_session_id = ?
+ OR (channel = ? AND bot_context_id = ? AND user_id = ? AND scope_key = ?)`,
+ ).run(targetSessionId, channel, botContextId, userId, scopeKey);
+ db.prepare(
+ `INSERT INTO im_bindings (
+ channel, bot_context_id, user_id, scope_key, target_session_id,
+ attached_at, attached_via_card_message_id
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)`,
+ ).run(
+ channel,
+ botContextId,
+ userId,
+ scopeKey,
+ targetSessionId,
+ attachedAt,
+ attachedViaCardMessageId,
+ );
+ });
+ transaction();
+}
+
/** 清失效停泊 id 与改写交接边界必须同成同败,防止重启后重建出错误 pending。 */
function sessionAgentSwitchFallback(db: Database.Database, args: unknown): void {
const payload = asRecord(args, 'session.agentSwitchFallback args');