Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(maker-core): 远程 Claude 回合失联后保留上一个成功的会话编号,重发不再丢历史 (#6120)
Praiseb757d646fa42
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/latestAssistantTranscriptUuid.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/latestAssistantTranscriptUuid.test.tsnew file mode 100644index 0000000000..a2404505e9--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/__tests__/latestAssistantTranscriptUuid.test.ts@@ -0,0 +1,127 @@+/**+ * findLatestAssistantTranscriptUuid:会话关闭(如远程电脑断线)后,内存里的「最后一条+ * assistant uuid」被清掉;重发的第一条用户消息靠这个查询从库里补回 transcriptParentUuid。+ * 口径与内存值一致:顶层 assistant(有 uuid、没有 parentUuid),跳过已回退行与清空边界之前的行。+ */+import Database from 'better-sqlite3';+import { drizzle } from 'drizzle-orm/better-sqlite3';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { messages, sessions } from '../../localDb/schema';++const h = vi.hoisted(() => ({+ db: null as ReturnType<typeof drizzle> | null,+}));++vi.mock('../../localDb/client/current', () => ({+ getDbClient: () => ({ drizzle: h.db }),+}));++import { findLatestAssistantTranscriptUuid } from '../latestAssistantTranscriptUuid';++const SESSION = 'session-1';++function createDb(clearedAt: number | null = null): Database.Database {+ const sqlite = new Database(':memory:');+ sqlite.exec(`+ CREATE TABLE sessions (+ id TEXT PRIMARY KEY,+ cleared_at INTEGER+ );+ CREATE TABLE messages (+ id TEXT PRIMARY KEY,+ client_id TEXT NOT NULL,+ session_id TEXT NOT NULL,+ role TEXT NOT NULL,+ content TEXT NOT NULL,+ tool_use_id TEXT,+ agent_meta TEXT,+ agent_kind TEXT,+ created_at INTEGER NOT NULL,+ rewind_at INTEGER+ );+ `);+ sqlite.prepare('INSERT INTO sessions (id, cleared_at) VALUES (?, ?)').run(SESSION, clearedAt);+ h.db = drizzle(sqlite, { schema: { messages, sessions } });+ return sqlite;+}++function insertRow(+ sqlite: Database.Database,+ input: {+ clientId: string;+ role: string;+ createdAt: number;+ agentMeta?: Record<string, unknown> | null;+ rewindAt?: number | null;+ },+): void {+ sqlite+ .prepare(+ `INSERT INTO messages (id, client_id, session_id, role, content, agent_meta, created_at, rewind_at)+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,+ )+ .run(+ `id-${input.clientId}`,+ input.clientId,+ SESSION,+ input.role,+ JSON.stringify({ text: input.clientId }),+ input.agentMeta ? JSON.stringify(input.agentMeta) : null,+ input.createdAt,+ input.rewindAt ?? null,+ );+}++describe('findLatestAssistantTranscriptUuid', () => {+ let sqlite: Database.Database;++ beforeEach(() => {+ sqlite = createDb();+ });++ it('returns the uuid of the newest top-level assistant row', async () => {+ insertRow(sqlite, { clientId: 'a-1', role: 'assistant', createdAt: 100, agentMeta: { uuid: 'uuid-old' } });+ insertRow(sqlite, { clientId: 'u-2', role: 'user', createdAt: 150, agentMeta: { uuid: 'user-uuid' } });+ insertRow(sqlite, { clientId: 'a-2', role: 'assistant', createdAt: 200, agentMeta: { uuid: 'uuid-last' } });++ await expect(findLatestAssistantTranscriptUuid(SESSION)).resolves.toBe('uuid-last');+ });++ it('skips sub-agent rows, rewound rows and rows without a uuid', async () => {+ insertRow(sqlite, { clientId: 'a-1', role: 'assistant', createdAt: 100, agentMeta: { uuid: 'uuid-top' } });+ insertRow(sqlite, {+ clientId: 'a-sub', role: 'assistant', createdAt: 200, agentMeta: { uuid: 'uuid-sub', parentUuid: 'tool-1' },+ });+ insertRow(sqlite, {+ clientId: 'a-rewound', role: 'assistant', createdAt: 300, agentMeta: { uuid: 'uuid-rewound' }, rewindAt: 400,+ });+ insertRow(sqlite, { clientId: 'a-bare', role: 'assistant', createdAt: 350, agentMeta: null });++ await expect(findLatestAssistantTranscriptUuid(SESSION)).resolves.toBe('uuid-top');+ });++ it('keeps looking past a long run of sub-agent rows', async () => {+ insertRow(sqlite, { clientId: 'a-top', role: 'assistant', createdAt: 100, agentMeta: { uuid: 'uuid-top' } });+ for (let i = 0; i < 120; i += 1) {+ insertRow(sqlite, {+ clientId: `a-sub-${i}`, role: 'assistant', createdAt: 200 + i, agentMeta: { uuid: `uuid-sub-${i}`, parentUuid: 'tool-1' },+ });+ }++ await expect(findLatestAssistantTranscriptUuid(SESSION)).resolves.toBe('uuid-top');+ });++ it('ignores assistant rows from before the clear boundary', async () => {+ sqlite = createDb(250);+ insertRow(sqlite, { clientId: 'a-before', role: 'assistant', createdAt: 200, agentMeta: { uuid: 'uuid-before' } });++ await expect(findLatestAssistantTranscriptUuid(SESSION)).resolves.toBeUndefined();+ });++ it('returns undefined for a conversation without assistant replies', async () => {+ insertRow(sqlite, { clientId: 'u-1', role: 'user', createdAt: 100, agentMeta: { uuid: 'user-uuid' } });++ await expect(findLatestAssistantTranscriptUuid(SESSION)).resolves.toBeUndefined();+ });+});diff --git a/apps/desktop/src/main/maker-ipc/latestAssistantTranscriptUuid.ts b/apps/desktop/src/main/maker-ipc/latestAssistantTranscriptUuid.tsnew file mode 100644index 0000000000..c399191882--- /dev/null+++ b/apps/desktop/src/main/maker-ipc/latestAssistantTranscriptUuid.ts@@ -0,0 +1,58 @@+import { and, desc, eq, gt, isNull, sql } from 'drizzle-orm';++import { getDbClient } from '../localDb/client/current';+import { messages, sessions } from '../localDb/schema';++const messageRowid = sql<number>`rowid`;+const SCAN_PAGE_SIZE = 50;+const MAX_SCANNED_ROWS = 1000;++/**+ * 最近一条可见的顶层 assistant 的 SDK uuid(有 uuid、没有 parentUuid,与内存里+ * lastAssistantTranscriptUuid 同口径)。会话关闭会清掉内存值;关闭后再发的第一条用户消息+ * 靠它补回 transcriptParentUuid,让回退锚点不因断线 / 重启而丢失。+ */+export async function findLatestAssistantTranscriptUuid(sessionId: string): Promise<string | undefined> {+ const db = getDbClient().drizzle;+ const [sessionRow] = await db+ .select({ clearedAt: sessions.clearedAt })+ .from(sessions)+ .where(eq(sessions.id, sessionId))+ .limit(1);+ const clearedAt = sessionRow?.clearedAt ?? null;+ // 子 agent 的回复也存成 assistant 行,一次长子任务可能让最近的一整页都不合格,所以分页往前找。+ for (let offset = 0; offset < MAX_SCANNED_ROWS; offset += SCAN_PAGE_SIZE) {+ const rows = await db+ .select({ agentMeta: messages.agentMeta })+ .from(messages)+ .where(and(+ eq(messages.sessionId, sessionId),+ eq(messages.role, 'assistant'),+ isNull(messages.rewindAt),+ clearedAt === null ? undefined : gt(messages.createdAt, clearedAt),+ ))+ .orderBy(desc(messages.createdAt), desc(messageRowid))+ .limit(SCAN_PAGE_SIZE)+ .offset(offset);+ for (const row of rows) {+ const meta = parseAgentMeta(row.agentMeta);+ const uuid = meta?.uuid;+ const parentUuid = meta?.parentUuid;+ if (typeof uuid === 'string' && uuid && !(typeof parentUuid === 'string' && parentUuid)) return uuid;+ }+ if (rows.length < SCAN_PAGE_SIZE) break;+ }+ return undefined;+}++function parseAgentMeta(raw: string | null): Record<string, unknown> | null {+ if (!raw) return null;+ try {+ const parsed: unknown = JSON.parse(raw);+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed)+ ? (parsed as Record<string, unknown>)+ : null;+ } catch {+ return null;+ }+}diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.tsindex 1bf90641dc..04f2b1432d 100644--- a/apps/desktop/src/main/maker-ipc/register.ts+++ b/apps/desktop/src/main/maker-ipc/register.ts@@ -878,6 +878,7 @@ import {stampTrustedDesktopQueuedOrigin,TRUSTED_DESKTOP_QUEUE_ORIGIN,} from './makerSendTransaction.js';+import { findLatestAssistantTranscriptUuid } from './latestAssistantTranscriptUuid.js';import {installDesktopInteractionHandler,installInteractionLifecycleObserver,@@ -15872,13 +15873,18 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)}};try {- return await enqueueDurableWrite(`user:${sessionId}:${message.clientId}`, (ownerScope) => {+ return await enqueueDurableWrite(`user:${sessionId}:${message.clientId}`, async (ownerScope) => {// Coordinator accepts can stamp transcriptParentUuid early; this late FIFO// fallback covers makerSendTransaction/direct createDbMessage paths.- const transcriptParentUuid = getLastAssistantTranscriptUuid(sessionId);const hasTranscriptParent =typeof message.agentMeta?.transcriptParentUuid === 'string' &&message.agentMeta.transcriptParentUuid.length > 0;+ // 会话关闭(如远程电脑断线)会清掉内存里的值,重发的第一条消息就没有锚点;+ // 这时从库里补回上一条 assistant 的 uuid。+ const transcriptParentUuid = hasTranscriptParent+ ? undefined+ : getLastAssistantTranscriptUuid(sessionId)+ ?? await Promise.resolve().then(() => findLatestAssistantTranscriptUuid(sessionId)).catch(() => undefined);const enrichedMessage =transcriptParentUuid && !hasTranscriptParent? { ...message, agentMeta: { ...message.agentMeta, transcriptParentUuid } }diff --git a/packages/maker-core/src/maker.agentDevice.test.ts b/packages/maker-core/src/maker.agentDevice.test.tsindex 348125a57a..5e6c24418a 100644--- a/packages/maker-core/src/maker.agentDevice.test.ts+++ b/packages/maker-core/src/maker.agentDevice.test.ts@@ -5,6 +5,7 @@import { describe, expect, it, vi } from 'vitest';import { Maker } from './maker.js';+import { createAsyncQueue, type AsyncQueue } from './agents/shared/async-queue.js';import type { AgentSessionHandle, BaseAgent } from './agents/base-agent.js';import { NotSupportedError } from './types/capabilities.js';import type { SessionMeta, SessionStorage } from './interfaces/session-storage.js';@@ -183,3 +184,191 @@ describe('Maker: agent on another computer', () => {await maker.shutdown();});});++// ── 远程 Claude Code:fork 出的新编号要等这一轮成功才写成持久编号 ──────────────────+const SDK_A = '11111111-1111-4111-8111-111111111111';+const SDK_B = '22222222-2222-4222-8222-222222222222';++function claudeAgent(): BaseAgent {+ return {+ kind: 'claude-code',+ capabilities: {+ availableModels: [], effortLevels: [], permissionModes: [], reasoning: { supported: false },+ images: { supported: false }, slashCommands: { supported: false }, customSlashCommands: { supported: false },+ memory: { supported: false }, fork: { supported: false }, rewind: { supported: true }, extraDirs: { supported: false },+ },+ startSession: vi.fn(async () => {+ throw new Error('local Claude start is not wired in this test');+ }),+ filterActiveSkillCommands: (result: unknown) => result,+ async dispose() {},+ } as unknown as BaseAgent;+}++/** 一个把事件交给测试的 Claude 句柄;`remote` 决定它走设备通道还是本机通道。 */+async function openClaudeTask(input: { id: string; remote: boolean; persistedSdkSessionId?: string }) {+ const store = storage();+ await store.create({+ id: input.id,+ agentKind: 'claude-code',+ workDir: '/repo',+ title: 't',+ model: 'claude-opus-4-6',+ ...(input.persistedSdkSessionId ? { sdkSessionId: input.persistedSdkSessionId } : {}),+ ...(input.remote ? { agentDeviceId: 'dev-b' } : {}),+ } as SessionMeta);++ const queues: Array<AsyncQueue<AgentEvent>> = [];+ const open = async (): Promise<AgentSessionHandle> => {+ const events = createAsyncQueue<AgentEvent>();+ queues.push(events);+ return {+ id: input.persistedSdkSessionId ?? '<pending>',+ agentKind: 'claude-code',+ model: 'claude-opus-4-6',+ async send() {},+ async steer() {},+ async abort() {},+ async close() { events.end(); },+ events: () => events,+ getUsageSnapshot: () => ({ tokenUsage: 0, contextTokens: 0, contextWindow: 0, costUsd: 0 }),+ setInteractionResolver() {},+ } as unknown as AgentSessionHandle;+ };++ const agent = claudeAgent();+ (agent.startSession as ReturnType<typeof vi.fn>).mockImplementation(open);+ const startDeviceAgentSession = vi.fn<(request: { options: { resumeSessionId?: string } }) => Promise<AgentSessionHandle>>(open);+ const maker = new Maker({+ agents: { 'claude-code': agent },+ storage: store,+ logger,+ ...(input.remote ? { startDeviceAgentSession } : {}),+ });+ const create = (resumeSessionId?: string) => maker.createSession({+ id: input.id,+ agentKind: 'claude-code',+ workingDir: '/repo',+ model: 'claude-opus-4-6',+ ...(resumeSessionId ? { resumeSessionId } : {}),+ ...(input.remote ? { agentDeviceId: 'dev-b' } : {}),+ });+ /** 让已推入的事件和它们排队的持久化都跑完。 */+ const settle = async () => {+ for (let i = 0; i < 5; i += 1) await new Promise((resolve) => setTimeout(resolve, 0));+ };+ return { maker, store, queues, startDeviceAgentSession, create, settle };+}++const connectionLostError: AgentEvent = {+ type: 'error',+ data: {+ message: '[REMOTE_AGENT_EXPIRED] The task is no longer running on the other computer.',+ isTerminal: true,+ reason: 'remote_agent_closed',+ },+ source: 'claude-code',+};++describe('Maker: remote Claude keeps the last good sdkSessionId when a turn is lost', () => {+ it('keeps A after resume reports a new id B and the turn then fails with REMOTE_AGENT_EXPIRED', async () => {+ const task = await openClaudeTask({ id: 'remote-lost', remote: true, persistedSdkSessionId: SDK_A });+ await task.create(SDK_A);++ task.queues[0].push({ type: 'session_id', data: SDK_B, source: 'claude-code' });+ task.queues[0].push(connectionLostError);+ await task.settle();++ // 修复前这里是 B:B 在对方电脑上没有对话记录,下一次 resume 会开出空会话。+ expect((await task.store.get('remote-lost'))?.sdkSessionId).toBe(SDK_A);++ // 失败后重发走 lazy create-session:它读库里的编号去 resume,必须还是 A。+ task.queues[0].end();+ await task.settle();+ const persisted = (await task.maker.getSessionMeta('remote-lost'))?.sdkSessionId;+ await task.create(persisted);+ expect(task.startDeviceAgentSession).toHaveBeenCalledTimes(2);+ expect(task.startDeviceAgentSession.mock.calls[1][0].options.resumeSessionId).toBe(SDK_A);+ await task.maker.shutdown();+ });++ it('keeps A when the remote session closes before the turn finished', async () => {+ const task = await openClaudeTask({ id: 'remote-closed', remote: true, persistedSdkSessionId: SDK_A });+ await task.create(SDK_A);++ task.queues[0].push({ type: 'session_id', data: SDK_B, source: 'claude-code' });+ task.queues[0].end();+ await task.settle();++ expect((await task.store.get('remote-closed'))?.sdkSessionId).toBe(SDK_A);+ await task.maker.shutdown();+ });++ it('keeps A when the remote stream crashes after reporting B', async () => {+ const task = await openClaudeTask({ id: 'remote-crashed', remote: true, persistedSdkSessionId: SDK_A });+ await task.create(SDK_A);++ task.queues[0].push({ type: 'session_id', data: SDK_B, source: 'claude-code' });+ task.queues[0].push({+ type: 'error',+ data: { message: 'stream crashed', isTerminal: true },+ source: 'claude-code',+ });+ // 崩溃收尾:终止错误之后还会补一条 done(reason: sdk_stream_crashed),它不能把 B 提交掉。+ task.queues[0].push({ type: 'done', data: { reason: 'sdk_stream_crashed' }, source: 'claude-code' });+ await task.settle();++ expect((await task.store.get('remote-crashed'))?.sdkSessionId).toBe(SDK_A);+ await task.maker.shutdown();+ });++ it('still commits B when the user stops the remote turn', async () => {+ const task = await openClaudeTask({ id: 'remote-stopped', remote: true, persistedSdkSessionId: SDK_A });+ await task.create(SDK_A);++ task.queues[0].push({ type: 'session_id', data: SDK_B, source: 'claude-code' });+ // Stop 之后 Claude 已写下这一轮的记录,下一轮要接着 B 走。+ task.queues[0].push({ type: 'done', data: { reason: 'user_stop_unconfirmed_wake_tasks' }, source: 'claude-code' });+ await task.settle();++ expect((await task.store.get('remote-stopped'))?.sdkSessionId).toBe(SDK_B);+ await task.maker.shutdown();+ });++ it('commits B once the remote turn finishes', async () => {+ const task = await openClaudeTask({ id: 'remote-ok', remote: true, persistedSdkSessionId: SDK_A });+ await task.create(SDK_A);++ task.queues[0].push({ type: 'session_id', data: SDK_B, source: 'claude-code' });+ await task.settle();+ expect((await task.store.get('remote-ok'))?.sdkSessionId).toBe(SDK_A);++ task.queues[0].push({ type: 'done', data: { reason: 'completed' }, source: 'claude-code' });+ await task.settle();+ expect((await task.store.get('remote-ok'))?.sdkSessionId).toBe(SDK_B);+ await task.maker.shutdown();+ });++ it('saves the first id right away when there is nothing to fall back to', async () => {+ const task = await openClaudeTask({ id: 'remote-first', remote: true });+ await task.create();++ task.queues[0].push({ type: 'session_id', data: SDK_B, source: 'claude-code' });+ await task.settle();++ expect((await task.store.get('remote-first'))?.sdkSessionId).toBe(SDK_B);+ await task.maker.shutdown();+ });++ it('still saves a local Claude session_id right away', async () => {+ const task = await openClaudeTask({ id: 'local-claude', remote: false, persistedSdkSessionId: SDK_A });+ await task.create(SDK_A);++ task.queues[0].push({ type: 'session_id', data: SDK_B, source: 'claude-code' });+ task.queues[0].push(connectionLostError);+ await task.settle();++ expect((await task.store.get('local-claude'))?.sdkSessionId).toBe(SDK_B);+ await task.maker.shutdown();+ });+});diff --git a/packages/maker-core/src/maker.ts b/packages/maker-core/src/maker.tsindex ea3b2fde95..27d08e94fa 100644--- a/packages/maker-core/src/maker.ts+++ b/packages/maker-core/src/maker.ts@@ -22,7 +22,12 @@ import { clearTimeout as clearNodeTimeout, setTimeout as setNodeTimeout } from 'import type { AgentKind } from './types/common.js';import type { Capabilities } from './types/capabilities.js';-import type { AgentEvent, ForkSdkSessionOptions, ForkSdkSessionResult } from './types/events.js';+import {+ isTerminalAgentErrorEvent,+ type AgentEvent,+ type ForkSdkSessionOptions,+ type ForkSdkSessionResult,+} from './types/events.js';import type {ScanAtResourcesOptions,ScanAtResourcesResult,@@ -430,6 +435,37 @@ interface FailedHandleCleanup {onCleaned?: () => void;}+/**+ * 在另一台电脑上运行的 Claude Code 会话,其新 vendor id(fork / 重建出的 id)要等这一轮+ * 成功结束才写成持久编号。`pending` 只在同一 session 的持久化队列里读写,保证与事件同序。+ */+interface DeferredSdkSessionCommit {+ pending?: string;+}++/**+ * 这一轮没有正常落地:与对方电脑失联,或对方的 Claude 流中途崩溃 / resume 失败。+ * 这类回合里新 fork 出的编号可能还没有对话记录,不能写成持久编号。+ * 用户主动 Stop 等其它收尾不在此列:Claude 已经收下输入并写了记录,下一轮应接着它走。+ */+const UNFINISHED_TURN_REASONS = new Set([+ 'remote_agent_closed',+ 'remote_agent_lost',+ 'sdk_stream_crashed',+ 'bridge_sdk_stream_crashed',+ 'resume_session_not_found',+ 'resume_session_recovery_failed',+]);++function isUnfinishedRemoteTurnEvent(evt: AgentEvent): boolean {+ const data = evt.data;+ if (!data || typeof data !== 'object' || Array.isArray(data)) return false;+ const { reason, message } = data as { reason?: unknown; message?: unknown };+ if (typeof reason === 'string' && UNFINISHED_TURN_REASONS.has(reason)) return true;+ return typeof message === 'string'+ && /\[REMOTE_AGENT_(EXPIRED|DEVICE_UNREACHABLE|NOT_FOUND|UNAVAILABLE)\]/.test(message);+}+export class Maker {protected readonly agents: Partial<Record<AgentKind, BaseAgent>>;protected readonly storage: SessionStorage;@@ -1071,6 +1107,11 @@ export class Maker {toolLoopReviewer: this.toolLoopReviewer,});+ // 另一台电脑上的 Claude Code:新编号等这一轮成功结束才落库。失联的回合里,对方可能还没写出+ // 这个编号的对话记录,提前落库会让下次发送 resume 到一个空会话,丢掉全部历史。+ const deferredSdkSessionCommit: DeferredSdkSessionCommit | undefined =+ opts.agentKind === 'claude-code' && startOpts.agentDeviceId ? {} : undefined;+// 当 SDK 回填 sdkSessionId 时持久化session.onEvent((evt) => {if (evt.type === 'session_id' && typeof evt.data === 'string' && evt.data) {@@ -1096,14 +1137,24 @@ export class Maker {return;}}- void this.persistSdkSessionId(meta.id, evt.data).catch((e) => {+ void this.persistSdkSessionId(meta.id, evt.data, deferredSdkSessionCommit).catch((e) => {this.logger.warn('failed to persist sdkSessionId', { error: String(e) });});+ return;+ }+ if (!deferredSdkSessionCommit) return;+ if (evt.type === 'done' && !isUnfinishedRemoteTurnEvent(evt)) {+ void this.commitDeferredSdkSessionId(meta.id, deferredSdkSessionCommit).catch((e) => {+ this.logger.warn('failed to commit deferred sdkSessionId', { error: String(e) });+ });+ } else if (evt.type === 'done' || (isTerminalAgentErrorEvent(evt) && isUnfinishedRemoteTurnEvent(evt))) {+ void this.discardDeferredSdkSessionId(meta.id, deferredSdkSessionCommit);}});session.onStatusChange((status) => {if (status === 'closed') {+ if (deferredSdkSessionCommit) void this.discardDeferredSdkSessionId(meta.id, deferredSdkSessionCommit);codexThreadClaim?.release();// 不再持久化运行态: 'closed' 是 SDK 子进程的瞬态, 重启即灭, 无意义存盘。this.activeSessions.delete(meta.id);@@ -1169,8 +1220,16 @@ export class Maker {);}- /** 串行持久化有效 vendor id,并屏蔽已判失效 query 的晚到事件。 */- private persistSdkSessionId(sessionId: string, sdkSessionId: string): Promise<void> {+ /**+ * 串行持久化有效 vendor id,并屏蔽已判失效 query 的晚到事件。+ * 传入 `deferred` 时:库里已有另一个编号,就先只记在 `deferred.pending`,等这一轮成功再提交;+ * 库里还没有编号(首轮)时没有可回退的对象,仍立即落库。+ */+ private persistSdkSessionId(+ sessionId: string,+ sdkSessionId: string,+ deferred?: DeferredSdkSessionCommit,+ ): Promise<void> {return this.enqueueSdkSessionPersistence(sessionId, async () => {if (this.invalidSdkSessionIds.get(sessionId)?.has(sdkSessionId)) {this.logger.debug('ignored stale sdkSessionId event after invalid-resume recovery', {@@ -1179,10 +1238,46 @@ export class Maker {});return;}+ if (deferred) {+ const current = (await this.storage.get(sessionId))?.sdkSessionId;+ if (current && current !== sdkSessionId) {+ deferred.pending = sdkSessionId;+ this.logger.debug('deferred sdkSessionId until the remote turn succeeds', {+ sessionId,+ sdkSessionId,+ });+ return;+ }+ deferred.pending = undefined;+ }+ await this.storage.update(sessionId, { sdkSessionId });+ });+ }++ /** 这一轮成功结束:把暂存的新 vendor id 写成持久编号(与 persistSdkSessionId 同一条队列,保序)。 */+ private commitDeferredSdkSessionId(sessionId: string, deferred: DeferredSdkSessionCommit): Promise<void> {+ return this.enqueueSdkSessionPersistence(sessionId, async () => {+ const sdkSessionId = deferred.pending;+ deferred.pending = undefined;+ if (!sdkSessionId) return;+ if (this.invalidSdkSessionIds.get(sessionId)?.has(sdkSessionId)) return;await this.storage.update(sessionId, { sdkSessionId });});}+ /** 这一轮失联结束或会话关闭:丢掉暂存编号,库里保持上一个成功的编号。 */+ private discardDeferredSdkSessionId(sessionId: string, deferred: DeferredSdkSessionCommit): Promise<void> {+ return this.enqueueSdkSessionPersistence(sessionId, async () => {+ if (deferred.pending) {+ this.logger.warn('dropped uncommitted sdkSessionId after the remote turn did not finish', {+ sessionId,+ sdkSessionId: deferred.pending,+ });+ }+ deferred.pending = undefined;+ });+ }+/** 拿到一个已激活的 session(不发起恢复) */getSession(id: string): Session | undefined {return this.activeSessions.get(id);