feat: add independent conversation branching

Local conversations can now continue in a new branch after stable content is persisted. Each branch uses new conversation and message IDs, keeps its source visible, and remains independent without copying Tasks, queue items, runs, memories, or artifact ownership.

Conversation Task rows are also denser, align status markers at the right edge, and use an accessible checked success marker without redundant completion text.

Release note: 本地会话现在可从“在新会话中继续”创建独立分支并显示来源;Task 子项布局更紧凑,状态统一显示在右侧。
This commit is contained in:
mesalogo
2026-08-20 17:13:57 +08:00
parent 65c3ab9ab0
commit aa339a73d6
25 changed files with 1392 additions and 67 deletions
+361 -4
View File
@@ -6,6 +6,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'
import {
builtInDefaultProjectSeedDescription,
builtInDefaultProjectSeedName,
conversationSnapshotSchema,
isUntouchedBuiltInDefaultProject
} from '../../shared/assistant-contracts'
import { AssistantDatabase } from './assistant-database'
@@ -161,7 +162,7 @@ describe('AssistantDatabase', () => {
database.close()
})
it('migrates existing databases to schema version 25', async () => {
it('migrates existing databases to schema version 26', async () => {
const directory = await mkdtemp(
join(tmpdir(), 'goodbuddy-assistant-migration-')
)
@@ -190,7 +191,7 @@ describe('AssistantDatabase', () => {
user_version: number
}
).user_version
).toBe(25)
).toBe(26)
expect(
current
.prepare(
@@ -213,6 +214,18 @@ describe('AssistantDatabase', () => {
})
])
)
expect(
current
.prepare('PRAGMA table_info(conversations)')
.all()
).toEqual(
expect.arrayContaining([
expect.objectContaining({
name: 'branch_source_conversation_id'
}),
expect.objectContaining({ name: 'branch_source_title' })
])
)
const foreignKeys = current
.prepare('PRAGMA foreign_key_list(model_usage_calls)')
.all() as Array<{
@@ -275,6 +288,15 @@ describe('AssistantDatabase', () => {
)
.get()
).toEqual({ name: 'conversation_queue_items' })
expect(
current
.prepare(
`SELECT name FROM sqlite_master
WHERE type = 'index'
AND name = 'conversations_branch_source_idx'`
)
.get()
).toEqual({ name: 'conversations_branch_source_idx' })
current.close()
})
@@ -476,7 +498,7 @@ describe('AssistantDatabase', () => {
user_version: number
}
).user_version
).toBe(25)
).toBe(26)
expect(
current
.prepare(
@@ -614,7 +636,7 @@ describe('AssistantDatabase', () => {
const inspected = new DatabaseSync(databasePath)
expect(
inspected.prepare('PRAGMA user_version').get()
).toEqual({ user_version: 25 })
).toEqual({ user_version: 26 })
expect(
inspected
.prepare(
@@ -2503,6 +2525,341 @@ describe('AssistantDatabase', () => {
database.close()
})
it('atomically branches a stable local conversation without cloning owned work', async () => {
const directory = await mkdtemp(
join(tmpdir(), 'goodbuddy-branched-conversation-')
)
temporaryDirectories.push(directory)
const databasePath = join(directory, 'assistant.sqlite')
const database = new AssistantDatabase(databasePath)
database.initialize('C:\\Workspace')
const project = database.listProjects()[0]!
const sourceConversationId =
'00000000-0000-4000-8000-000000000541'
const sourceMessageIds = [
'00000000-0000-4000-8000-000000000542',
'00000000-0000-4000-8000-000000000543'
]
database.replaceConversations([
{
id: sourceConversationId,
projectId: project.id,
runtimeSelection: {
provider: 'model',
profileId: channelDefaultProfileId
},
knowledgeRetrievalMode: 'always',
contextMetrics: {
runtimeSelectionKey: `model:${channelDefaultProfileId}`,
contextTokens: 4_096,
source: 'estimated',
basis: 'conversation'
},
contextCompressionState: {
coveredHistoryDigest: 'b'.repeat(64),
coveredMessageCount: 2,
coveredFromMessageId: sourceMessageIds[0],
coveredThroughMessageId: sourceMessageIds[1],
summary: '来源会话摘要'
},
title: '发布方案讨论',
updatedAt: 1_775_000_000_000,
messages: [
{
id: sourceMessageIds[0]!,
role: 'user',
content: '比较两个发布方案',
createdAt: 1_775_000_000_000,
state: 'complete',
attachments: [
{
id: '00000000-0000-4000-8000-000000000544',
name: '发布清单.md',
size: 128,
preview: '发布步骤',
kind: 'text'
}
]
},
{
id: sourceMessageIds[1]!,
role: 'assistant',
content: '可以从风险和成本两个方向比较。',
createdAt: 1_775_000_001_000,
state: 'complete',
task: {
id: '00000000-0000-4000-8000-000000000545',
title: '来源任务'
},
artifactIds: [
'00000000-0000-4000-8000-000000000546'
]
}
]
}
])
const raw = new DatabaseSync(databasePath)
raw
.prepare(
`UPDATE messages
SET request_id = ?
WHERE id = ?`
)
.run(
'00000000-0000-4000-8000-000000000547',
sourceMessageIds[1]!
)
const sourceMetadataRow = raw
.prepare(
`SELECT metadata_json
FROM messages
WHERE id = ?`
)
.get(sourceMessageIds[1]!) as { metadata_json: string }
raw
.prepare(
`UPDATE messages
SET metadata_json = ?
WHERE id = ?`
)
.run(
JSON.stringify({
...(JSON.parse(sourceMetadataRow.metadata_json) as object),
subagents: [
{
childTaskId:
'00000000-0000-4000-8000-000000000549',
expertId:
'00000000-0000-4000-8000-000000000550',
expertName: '来源专家',
routingMode: 'manual',
state: 'completed'
}
]
}),
sourceMessageIds[1]!
)
raw.close()
const sourceBefore = database.getConversation(sourceConversationId)
const branch = database.branchLocalConversation({
sourceConversationId,
title: '发布方案讨论 · 分支'
})
expect(conversationSnapshotSchema.safeParse(branch).success).toBe(true)
expect(branch).toMatchObject({
projectId: project.id,
runtimeSelection: {
provider: 'model',
profileId: channelDefaultProfileId
},
knowledgeRetrievalMode: 'always',
branch: {
sourceConversationId,
sourceTitle: '发布方案讨论'
},
title: '发布方案讨论 · 分支'
})
expect(branch).not.toHaveProperty('contextMetrics')
expect(branch).not.toHaveProperty('contextCompressionState')
expect(branch.id).not.toBe(sourceConversationId)
expect(branch.messages.map((message) => message.content)).toEqual(
sourceBefore.messages.map((message) => message.content)
)
expect(
branch.messages.every(
(message) => !sourceMessageIds.includes(message.id)
)
).toBe(true)
expect(branch.messages[0]?.attachments).toEqual(
sourceBefore.messages[0]?.attachments
)
expect(branch.messages[1]?.task).toBeUndefined()
expect(branch.messages[1]?.artifactIds).toBeUndefined()
expect(database.getConversation(sourceConversationId)).toEqual(
sourceBefore
)
const durable = new DatabaseSync(databasePath)
expect(
durable
.prepare(
`SELECT sequence, request_id
FROM messages
WHERE conversation_id = ?
ORDER BY sequence`
)
.all(branch.id)
).toEqual([
{ sequence: 0, request_id: null },
{ sequence: 1, request_id: null }
])
const branchMetadataRow = durable
.prepare(
`SELECT metadata_json
FROM messages
WHERE conversation_id = ? AND sequence = 1`
)
.get(branch.id) as { metadata_json: string }
const branchMetadata = JSON.parse(
branchMetadataRow.metadata_json
) as Record<string, unknown>
expect(branchMetadata).not.toHaveProperty('artifactIds')
expect(branchMetadata).not.toHaveProperty('subagents')
expect(branchMetadata).not.toHaveProperty('task')
durable.close()
database.saveLocalConversations([
{
header: {
id: branch.id,
projectId: branch.projectId,
runtimeSelection: branch.runtimeSelection,
knowledgeRetrievalMode: branch.knowledgeRetrievalMode,
branch: branch.branch,
title: '发布方案讨论 · 分支(独立更新)',
updatedAt: 1_775_000_003_000
},
messages: [
{
id: '00000000-0000-4000-8000-000000000548',
role: 'user',
content: '只在分支中继续',
createdAt: 1_775_000_003_000,
state: 'complete'
}
]
}
])
expect(database.getConversation(sourceConversationId)).toEqual(
sourceBefore
)
expect(database.getConversation(branch.id)).toMatchObject({
title: '发布方案讨论 · 分支(独立更新)',
messages: [
{ content: '比较两个发布方案' },
{ content: '可以从风险和成本两个方向比较。' },
{ content: '只在分支中继续' }
]
})
expect(database.deleteLocalConversation(sourceConversationId)).toBe(
true
)
expect(database.getConversation(branch.id)).toMatchObject({
branch: {
sourceConversationId,
sourceTitle: '发布方案讨论'
},
messages: [
{ content: '比较两个发布方案' },
{ content: '可以从风险和成本两个方向比较。' },
{ content: '只在分支中继续' }
]
})
database.close()
})
it('rejects unstable or remote branch sources and rolls back copy failures', async () => {
const directory = await mkdtemp(
join(tmpdir(), 'goodbuddy-conversation-branch-guards-')
)
temporaryDirectories.push(directory)
const databasePath = join(directory, 'assistant.sqlite')
const database = new AssistantDatabase(databasePath)
database.initialize('C:\\Workspace')
const sourceConversationId =
'00000000-0000-4000-8000-000000000551'
const sourceMessageId =
'00000000-0000-4000-8000-000000000552'
database.replaceConversations([
{
id: sourceConversationId,
title: '必须稳定后分支',
updatedAt: 1,
messages: [
{
id: sourceMessageId,
role: 'user',
content: '稳定内容',
createdAt: 1,
state: 'complete'
}
]
}
])
const queued = database.enqueueConversationUserInput({
conversationId: sourceConversationId,
label: '待发送内容',
payloadJson: '{}'
})
expect(() =>
database.branchLocalConversation({
sourceConversationId,
title: '不应创建的队列分支'
})
).toThrow('仍有待发送内容')
database.removeConversationUserQueueItem(queued.id)
const taskId = '00000000-0000-4000-8000-000000000553'
database.createTask({
id: taskId,
conversationId: sourceConversationId,
title: '运行中的任务',
instructions: '保持运行',
workMode: 'ask'
})
database.updateTaskStatus(taskId, 'running')
expect(() =>
database.branchLocalConversation({
sourceConversationId,
title: '不应创建的运行分支'
})
).toThrow('仍有正在运行的任务')
database.updateTaskStatus(taskId, 'completed')
const channelProject = database.ensureChannelProjects(
'C:\\Users\\test',
channelDefaultProfileId
)[0]!
const remote = database.getOrCreateRemoteConversation({
projectId: channelProject.id,
channel: 'weixin',
accountId: 'default',
externalConversationId: 'branch-protected',
conversationType: 'direct',
title: '远程来源',
accountDisplay: '发送者 ****0551'
})
expect(() =>
database.branchLocalConversation({
sourceConversationId: remote.id,
title: '不应创建的远程分支'
})
).toThrow('只能从现有的本地会话创建分支')
const countBeforeFailure = database.listConversations().length
const raw = new DatabaseSync(databasePath)
raw.exec(`
CREATE TRIGGER reject_branched_message
BEFORE INSERT ON messages
WHEN NEW.conversation_id != '${sourceConversationId}'
BEGIN
SELECT RAISE(ABORT, 'forced branch copy failure');
END;
`)
raw.close()
expect(() =>
database.branchLocalConversation({
sourceConversationId,
title: '必须完整回滚'
})
).toThrow('forced branch copy failure')
expect(database.listConversations()).toHaveLength(countBeforeFailure)
database.close()
})
it('keeps incremental local conversation storage bounded to 500 messages', async () => {
const directory = await mkdtemp(
join(tmpdir(), 'goodbuddy-bounded-local-conversation-')
+198 -11
View File
@@ -19,6 +19,7 @@ import type {
AssistantSchedule,
AssistantTask,
ConversationQueueItem,
ConversationBranchInput,
ConversationMessage,
ConversationSnapshot,
ExpertCreateInput,
@@ -122,6 +123,8 @@ type ConversationRow = {
external_conversation_id: string | null
conversation_type: 'direct' | 'group' | null
account_display: string | null
branch_source_conversation_id: string | null
branch_source_title: string | null
updated_at: string
}
@@ -892,6 +895,16 @@ function toConversationSnapshot(
}
}
: {}),
...(conversation.branch_source_conversation_id &&
conversation.branch_source_title
? {
branch: {
sourceConversationId:
conversation.branch_source_conversation_id,
sourceTitle: conversation.branch_source_title
}
}
: {}),
title: conversation.title,
updatedAt: Date.parse(conversation.updated_at),
messages: messages.map((message) => {
@@ -1525,7 +1538,9 @@ export class AssistantDatabase {
`SELECT id, project_id, runtime_selection_json,
knowledge_retrieval_mode, context_state_json, title, channel,
external_account_id, external_conversation_id,
conversation_type, account_display, updated_at
conversation_type, account_display,
branch_source_conversation_id, branch_source_title,
updated_at
FROM conversations
WHERE status = 'active'
ORDER BY updated_at DESC
@@ -1560,7 +1575,9 @@ export class AssistantDatabase {
`SELECT id, project_id, runtime_selection_json,
knowledge_retrieval_mode, context_state_json, title, channel,
external_account_id, external_conversation_id,
conversation_type, account_display, updated_at
conversation_type, account_display,
branch_source_conversation_id, branch_source_title,
updated_at
FROM conversations
WHERE id = ? AND status = 'active'`
)
@@ -1686,9 +1703,10 @@ export class AssistantDatabase {
const insertConversation = database.prepare(
`INSERT INTO conversations
(id, project_id, runtime_selection_json, knowledge_retrieval_mode,
context_state_json, work_mode, title, status, created_at,
updated_at)
VALUES (?, ?, ?, ?, ?, 'ask', ?, 'active', ?, ?)`
context_state_json, work_mode, title,
branch_source_conversation_id, branch_source_title, status,
created_at, updated_at)
VALUES (?, ?, ?, ?, ?, 'ask', ?, ?, ?, 'active', ?, ?)`
)
const insertMessage = database.prepare(
`INSERT INTO messages
@@ -1710,6 +1728,8 @@ export class AssistantDatabase {
conversation.knowledgeRetrievalMode ?? null,
serializeConversationContextState(conversation),
conversation.title,
conversation.branch?.sourceConversationId ?? null,
conversation.branch?.sourceTitle ?? null,
updatedAt,
updatedAt
)
@@ -1743,15 +1763,17 @@ export class AssistantDatabase {
const insertConversation = database.prepare(
`INSERT INTO conversations
(id, project_id, runtime_selection_json, knowledge_retrieval_mode,
context_state_json, work_mode, title, status, created_at,
updated_at)
VALUES (?, ?, ?, ?, ?, 'ask', ?, 'active', ?, ?)`
context_state_json, work_mode, title,
branch_source_conversation_id, branch_source_title, status,
created_at, updated_at)
VALUES (?, ?, ?, ?, ?, 'ask', ?, ?, ?, 'active', ?, ?)`
)
const updateConversation = database.prepare(
`UPDATE conversations
SET project_id = ?, runtime_selection_json = ?,
knowledge_retrieval_mode = ?, context_state_json = ?,
title = ?, status = 'active',
title = ?, branch_source_conversation_id = ?,
branch_source_title = ?, status = 'active',
updated_at = MAX(updated_at, ?)
WHERE id = ? AND channel IS NULL`
)
@@ -1807,6 +1829,8 @@ export class AssistantDatabase {
header.knowledgeRetrievalMode ?? null,
serializeConversationContextState(header),
header.title,
header.branch?.sourceConversationId ?? null,
header.branch?.sourceTitle ?? null,
updatedAt,
header.id
)
@@ -1823,6 +1847,8 @@ export class AssistantDatabase {
header.knowledgeRetrievalMode ?? null,
serializeConversationContextState(header),
header.title,
header.branch?.sourceConversationId ?? null,
header.branch?.sourceTitle ?? null,
updatedAt,
updatedAt
)
@@ -1878,6 +1904,128 @@ export class AssistantDatabase {
}
}
branchLocalConversation(
input: ConversationBranchInput
): ConversationSnapshot {
const database = this.requireDatabase()
const destinationConversationId = randomUUID()
const now = new Date().toISOString()
database.exec('BEGIN IMMEDIATE')
try {
const source = database
.prepare(
`SELECT id, project_id, runtime_selection_json,
knowledge_retrieval_mode, title
FROM conversations
WHERE id = ? AND status = 'active' AND channel IS NULL`
)
.get(input.sourceConversationId) as
| {
id: string
project_id: string | null
runtime_selection_json: string | null
knowledge_retrieval_mode: 'auto' | 'always' | null
title: string
}
| undefined
if (!source) {
throw new Error('只能从现有的本地会话创建分支')
}
const activeTask = database
.prepare(
`SELECT 1
FROM tasks
WHERE conversation_id = ?
AND status IN ('running', 'waiting_approval')
LIMIT 1`
)
.get(source.id)
if (activeTask) {
throw new Error('当前会话仍有正在运行的任务,请等待完成后再创建分支')
}
const queuedItem = database
.prepare(
`SELECT 1
FROM conversation_queue_items
WHERE conversation_id = ?
AND status IN ('pending', 'dispatching')
LIMIT 1`
)
.get(source.id)
if (queuedItem) {
throw new Error('当前会话仍有待发送内容,请处理后再创建分支')
}
const messageStates = database
.prepare(
`SELECT state
FROM messages
WHERE conversation_id = ?
ORDER BY sequence ASC`
)
.all(source.id) as Array<{ state: MessageRow['state'] }>
if (
messageStates.some((message) => message.state === 'streaming')
) {
throw new Error('当前会话仍在生成内容,请等待完成后再创建分支')
}
database
.prepare(
`INSERT INTO conversations
(id, project_id, runtime_selection_json,
knowledge_retrieval_mode, context_state_json, work_mode,
title, branch_source_conversation_id, branch_source_title,
status, created_at, updated_at)
VALUES (?, ?, ?, ?, NULL, 'ask', ?, ?, ?, 'active', ?, ?)`
)
.run(
destinationConversationId,
source.project_id,
source.runtime_selection_json,
source.knowledge_retrieval_mode,
input.title,
source.id,
source.title,
now,
now
)
const copiedMessages = database
.prepare(
`INSERT INTO messages
(id, conversation_id, request_id, role, content, state,
sequence, metadata_json, created_at)
SELECT lower(
hex(randomblob(4)) || '-' ||
hex(randomblob(2)) || '-4' ||
substr(hex(randomblob(2)), 2) || '-' ||
substr('89ab', (random() & 3) + 1, 1) ||
substr(hex(randomblob(2)), 2) || '-' ||
hex(randomblob(6))
),
?, NULL, role, content, state,
ROW_NUMBER() OVER (ORDER BY sequence) - 1,
json_remove(
metadata_json,
'$.artifactIds',
'$.subagents',
'$.task'
),
created_at
FROM messages
WHERE conversation_id = ?
ORDER BY sequence`
)
.run(destinationConversationId, source.id)
if (copiedMessages.changes !== messageStates.length) {
throw new Error('分支消息复制不完整')
}
database.exec('COMMIT')
} catch (error) {
database.exec('ROLLBACK')
throw error
}
return this.getConversation(destinationConversationId)
}
deleteLocalConversation(conversationId: string): boolean {
const database = this.requireDatabase()
database.exec('BEGIN IMMEDIATE')
@@ -5799,12 +5947,12 @@ export class AssistantDatabase {
const version = database
.prepare('PRAGMA user_version')
.get() as { user_version: number }
if (version.user_version > 25) {
if (version.user_version > 26) {
throw new Error(
`当前 GoodBuddy 不支持助理数据库版本 ${version.user_version},请升级应用后重试`
)
}
if (version.user_version === 25) {
if (version.user_version === 26) {
return
}
if (version.user_version < 1) {
@@ -5837,6 +5985,8 @@ export class AssistantDatabase {
work_mode TEXT NOT NULL DEFAULT 'ask'
CHECK(work_mode IN ('ask', 'execute')),
title TEXT NOT NULL,
branch_source_conversation_id TEXT,
branch_source_title TEXT,
status TEXT NOT NULL DEFAULT 'active'
CHECK(status IN ('active', 'archived')),
created_at TEXT NOT NULL,
@@ -5855,6 +6005,9 @@ export class AssistantDatabase {
created_at TEXT NOT NULL,
UNIQUE(conversation_id, sequence)
);
CREATE INDEX conversations_branch_source_idx
ON conversations(branch_source_conversation_id)
WHERE branch_source_conversation_id IS NOT NULL;
CREATE TABLE tasks (
id TEXT PRIMARY KEY,
project_id TEXT REFERENCES projects(id) ON DELETE SET NULL,
@@ -7177,6 +7330,40 @@ export class AssistantDatabase {
throw error
}
}
if (version.user_version < 26) {
const conversationColumns = new Set(
(
database.prepare('PRAGMA table_info(conversations)').all() as Array<{
name: string
}>
).map((column) => column.name)
)
database.exec('BEGIN IMMEDIATE')
try {
if (!conversationColumns.has('branch_source_conversation_id')) {
database.exec(`
ALTER TABLE conversations
ADD COLUMN branch_source_conversation_id TEXT;
`)
}
if (!conversationColumns.has('branch_source_title')) {
database.exec(`
ALTER TABLE conversations
ADD COLUMN branch_source_title TEXT;
`)
}
database.exec(`
CREATE INDEX IF NOT EXISTS conversations_branch_source_idx
ON conversations(branch_source_conversation_id)
WHERE branch_source_conversation_id IS NOT NULL;
PRAGMA user_version = 26;
COMMIT;
`)
} catch (error) {
database.exec('ROLLBACK')
throw error
}
}
}
private requireDatabase(): DatabaseSync {
@@ -102,7 +102,7 @@ describe('AssistantDatabase heartbeat persistence', () => {
).count
check.close()
migrated.close()
expect(version).toBe(25)
expect(version).toBe(26)
expect(heartbeatTableCount).toBe(4)
})
+57 -1
View File
@@ -2734,7 +2734,7 @@ describe('registerIpcHandlers local conversation persistence', () => {
vi.clearAllMocks()
})
it('validates and forwards incremental saves and explicit deletions', async () => {
it('validates and forwards incremental saves, branches, and explicit deletions', async () => {
const conversationId =
'00000000-0000-4000-8000-000000000301'
const queuedAttachmentId =
@@ -2774,6 +2774,16 @@ describe('registerIpcHandlers local conversation persistence', () => {
})
),
saveLocalConversations: vi.fn(),
branchLocalConversation: vi.fn((input) => ({
id: '00000000-0000-4000-8000-000000000305',
branch: {
sourceConversationId: input.sourceConversationId,
sourceTitle: '增量会话'
},
title: input.title,
updatedAt: 2,
messages: []
})),
deleteLocalConversation: vi.fn(() => true)
}
const contextManager = {
@@ -2838,6 +2848,21 @@ describe('registerIpcHandlers local conversation persistence', () => {
expect(
assistantDatabase.saveLocalConversations
).toHaveBeenCalledWith(batch)
const branchInput = {
sourceConversationId: conversationId,
title: '增量会话 · 分支'
}
expect(
electronMocks.handlers.get(
ipcChannels.conversationsBranchLocal
)?.(event, branchInput)
).toMatchObject({
branch: { sourceConversationId: conversationId },
title: branchInput.title
})
expect(
assistantDatabase.branchLocalConversation
).toHaveBeenCalledWith(branchInput)
expect(
electronMocks.handlers.get(
ipcChannels.conversationsDeleteLocal
@@ -2867,6 +2892,14 @@ describe('registerIpcHandlers local conversation persistence', () => {
}
])
).toThrow()
expect(() =>
electronMocks.handlers.get(
ipcChannels.conversationsBranchLocal
)?.(event, {
sourceConversationId: 'not-a-uuid',
title: '无效分支'
})
).toThrow()
expect(() =>
electronMocks.handlers.get(
ipcChannels.conversationsDeleteLocal
@@ -3348,6 +3381,17 @@ describe('registerIpcHandlers agent terminal state', () => {
queueDueSchedules: vi.fn(() => []),
queueScheduleNow: vi.fn(),
completeScheduleRun: vi.fn(),
branchLocalConversation: vi.fn(() => ({
id: '00000000-0000-4000-8000-000000000403',
branch: {
sourceConversationId:
'00000000-0000-4000-8000-000000000402',
sourceTitle: '来源会话'
},
title: '来源会话 · 分支',
updatedAt: Date.now(),
messages: []
})),
listSchedules: vi.fn(() => []),
createSchedule: vi.fn(),
setScheduleEnabled: vi.fn(),
@@ -3471,6 +3515,9 @@ describe('registerIpcHandlers agent terminal state', () => {
handler: electronMocks.handlers.get(ipcChannels.agentRun),
statusHandler: electronMocks.handlers.get(ipcChannels.agentStatus),
cancelHandler: electronMocks.handlers.get(ipcChannels.agentCancel),
branchHandler: electronMocks.handlers.get(
ipcChannels.conversationsBranchLocal
),
knowledgeSearchHandler: electronMocks.handlers.get(
ipcChannels.knowledgeSearch
),
@@ -4016,6 +4063,15 @@ describe('registerIpcHandlers agent terminal state', () => {
})
).rejects.toThrow('当前对话已有执行中的请求')
expect(selectedRuntimes.getRuntime).toHaveBeenCalledOnce()
expect(() =>
harness.branchHandler?.(trustedEvent(harness.webContents), {
sourceConversationId: conversationId,
title: '等待 Runtime · 分支'
})
).toThrow('当前会话仍有正在执行的请求')
expect(
harness.assistantDatabase.branchLocalConversation
).not.toHaveBeenCalled()
resolveRuntime?.(runtime)
await firstRun
+15
View File
@@ -152,6 +152,7 @@ import {
} from '../shared/magic-notes-contracts'
import {
assistantIdSchema,
conversationBranchInputSchema,
conversationSnapshotsSchema,
localConversationSaveBatchSchema,
memoryCreateSchema,
@@ -4623,6 +4624,20 @@ export function registerIpcHandlers(
}
)
registerHandler(
ipcChannels.conversationsBranchLocal,
(event, input: unknown) => {
assertTrustedSender(event, window)
const parsed = conversationBranchInputSchema.parse(input)
if (isConversationExecuting(parsed.sourceConversationId)) {
throw new Error('当前会话仍有正在执行的请求,请等待完成后再创建分支')
}
return assistantDatabase.branchLocalConversation(
parsed
)
}
)
registerHandler(
ipcChannels.conversationsDeleteLocal,
(event, input: unknown) => {