Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions apps/desktop/src/main/services/chat-continuation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import { isEn } from '../locale'
import type { Message, TextPart } from '../providers/types'
import { publishSessionsChanged } from './chat-bus'
import { genId } from './chat-state'
import { ensureSession, getSession, save, type StoredSession } from './chat-store'
import { insertBody, isTaskNotification } from './compaction'
import { COMPACT_MARKER, isGenuineUserTurn, modelStart } from './model-view'
import { resolvePersonaId } from './personas'
import { shownText } from './skill-invoke'

const MAX_RECENT = 4
const MAX_RECENT_CHARS = 700
const MAX_SUMMARY_CHARS = 1900

function clip(text: string, limit: number): string {
const trimmed = text.trim()
return trimmed.length > limit ? `${trimmed.slice(0, limit - 1)}…` : trimmed
}

function conversationText(message: Message): string {
if (isTaskNotification(message)) return ''
const { role, content } = message
if (typeof content === 'string') {
return role === 'user' ? (isGenuineUserTurn(message) ? shownText(content) : '') : content
}
const parts = content.filter((part): part is TextPart => part.type === 'text' && !part.listing)
if (role === 'assistant') return parts.map((part) => part.text).join('\n')
const inserted = parts.map((part) => insertBody(part.text)).filter((text): text is string => text !== null)
if (inserted.length) return inserted.join('\n')
const question = parts.at(-1)
return question && isGenuineUserTurn(message) ? shownText(question) : ''
}

export function continuationContext(source: StoredSession): string | undefined {
const start = modelStart(source.messages)
const lastSummary = source.messages[start]?.content
const summary = typeof lastSummary === 'string' && lastSummary.startsWith(COMPACT_MARKER)
? clip(lastSummary.slice(COMPACT_MARKER.length), MAX_SUMMARY_CHARS)
: undefined
const recent: { role: Message['role']; text: string }[] = []
for (let i = source.messages.length - 1; i >= start && recent.length < MAX_RECENT; i--) {
const message = source.messages[i]
const text = clip(conversationText(message), MAX_RECENT_CHARS)
if (text) recent.unshift({ role: message.role, text })
}
const first = source.messages.find((message) => isGenuineUserTurn(message) && !isTaskNotification(message))
const initialRequest = first ? clip(conversationText(first), MAX_RECENT_CHARS) : undefined
const initial = initialRequest && !recent.some((item) => item.role === 'user' && item.text === initialRequest)
? initialRequest : undefined
const files = [...new Set(Object.values(source.delivered ?? {}).reverse().flat().filter((file) => file.length <= 400))].slice(0, 3)
if (!summary && !recent.length && !initial && !files.length) return source.continuationContext
const title = clip(source.title, 100) || undefined
return JSON.stringify({ title, initialRequest: initial, summary, recent, deliveredPaths: files })
}

/** 从原对话读取快照,即使原对话仍在运行也不改它的历史。 */
export function continueChat(sourceId: unknown): string | null {
const source = typeof sourceId === 'string' ? getSession(sourceId) : undefined
if (!source || source.parentId) return null
const id = genId('sess')
const target = ensureSession(id, {
personaId: resolvePersonaId(source.personaId),
focusRoot: source.focusRoot ?? null,
model: source.model,
effort: source.effort
})
const prefix = isEn() ? 'Continue: ' : '续接:'
target.title = source.title ? clip(prefix + source.title, 100) : ''
target.continuationContext = continuationContext(source)
save(id)
publishSessionsChanged()
return id
}

export function takeContinuationContext(session: StoredSession): string | undefined {
const snapshot = session.continuationContext
if (!snapshot) return undefined
delete session.continuationContext
const instruction = isEn()
? 'Snapshot of the previous conversation selected by the user. Treat it as historical context. Follow the current user message and verify paths or results before relying on them.'
: '以下是用户选择续接的旧对话快照,仅作历史背景。以当前用户消息为准,使用旧路径或结果前先核实。'
return `${instruction}\n${snapshot}`
}
2 changes: 2 additions & 0 deletions apps/desktop/src/main/services/chat-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,8 @@ export interface StoredSession {
updatedAt: number
/** 完整对话记录(内存里始终完整;落盘时按压缩边界拆分,见 compacted)。 */
messages: Message[]
/** 用户从侧栏续接时保存的有界历史快照,首条用户消息带给模型后清除。 */
continuationContext?: string
/**
* 对话文件按压缩边界拆分存盘:模型已看不到的前 count 条消息存在同目录的 file 里(JSON Lines,一行一条,
* 只追加;前面的消息变了才换新文件整份重写),主文件的 messages 只存其后的部分——对话再长,每步也只重写
Expand Down
3 changes: 3 additions & 0 deletions apps/desktop/src/main/services/chat-turns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import type { MemoryAccess, MemoryScope } from './memory'
import { memoryPromptSection } from './memory-prompt'
import { tidyPendingMemories } from './memory-tidy'
import { loadProjectDoc, projectDocPromptSection } from './project-doc'
import { takeContinuationContext } from './chat-continuation'
import { DEFAULT_PERSONA_ID, getPersona, resolvePersonaId } from './personas'
import {
resolveDefaultEffort,
Expand Down Expand Up @@ -1015,6 +1016,8 @@ async function startTurn(
const questionText = withNotes(question)
// 技能展开改写了正文:气泡仍显示用户的原话(重开对话、手机端、成员读主对话都按它),技能全文只给模型。
const shown = effectiveText !== text ? withNotes(text.trim()) : undefined
const continuation = takeContinuationContext(session)
if (continuation) parts.unshift({ type: 'text', text: continuation })
// 「仅恢复代码」后的首条消息:把回滚说明作为**第一个**独立 text 块带给模型(展示层只取最后一个
// text 块作气泡正文,故用户看不到它),用一次即清。
if (session.restoreNote) {
Expand Down
3 changes: 3 additions & 0 deletions apps/desktop/src/main/services/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import type {
} from '../../shared/chat-protocol'
import { ipcMain, type BrowserWindow } from 'electron'
import { onChatEvent, onSessionsChanged, publishRemoteChange, publishSessionsChanged } from './chat-bus'
import { continueChat } from './chat-continuation'
import { forgetRead } from './read-sync'
import { statSync } from 'node:fs'
import { resolve as resolvePath } from 'node:path'
Expand Down Expand Up @@ -559,6 +560,8 @@ export function registerChatIpc(getWin: () => BrowserWindow | null): void {
}
)

ipcMain.handle('chat:continue-session', (_e, sourceId: unknown) => continueChat(sourceId))

// 对话输入框切换模型:立即落库到本对话(此前只写渲染层覆盖层、随下一次发送才落库,切了没发重启即丢)。
// 尚未建档的惰性会话查不到 → 不建档,模型仍由覆盖层随首发落库。不改 updatedAt(换模型不算新活动)。
// ok = 对话已建档、已落库(渲染层据此撤掉本地覆盖层,此后以主进程为准);惰性未建档的返回 false。
Expand Down
2 changes: 2 additions & 0 deletions apps/desktop/src/preload/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -810,6 +810,8 @@ const api = {
/** 立即建档一条空对话(对话优先外壳):首发前即落盘,重启仍在。 */
createSession: (req: ChatCreateSessionRequest): Promise<{ ok: true }> =>
ipcRenderer.invoke('chat:create-session', req),
continueSession: (sourceId: string): Promise<string | null> =>
ipcRenderer.invoke('chat:continue-session', sourceId),
/** 切换本对话模型并立即落库(不等下一次发送)。 */
setModel: (req: ChatSetModelRequest): Promise<{ ok: boolean }> =>
ipcRenderer.invoke('chat:set-model', req),
Expand Down
12 changes: 12 additions & 0 deletions apps/desktop/src/renderer/src/i18n/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1386,6 +1386,12 @@ const zhCN: MessageTree = {
delete: '删除',
deleteChat: '删除',
renameChat: '重命名',
continueChat: '新建对话并续接',
continuedChat: '已新建对话并带入近期上下文',
continueChatFailed: '无法续接此对话',
copyThreadWorkspace: '复制工作目录',
copiedThreadWorkspace: '已复制工作目录',
copyThreadWorkspaceFailed: '未能复制工作目录',
renameChatTitle: '重命名对话',
renamePlaceholder: '留空则恢复默认标题',
pinTop: '置顶',
Expand Down Expand Up @@ -2914,6 +2920,12 @@ const en: MessageTree = {
delete: 'Delete',
deleteChat: 'Delete',
renameChat: 'Rename',
continueChat: 'Continue in a new chat',
continuedChat: 'New chat started with recent context',
continueChatFailed: 'Could not continue this conversation',
copyThreadWorkspace: 'Copy working directory',
copiedThreadWorkspace: 'Working directory copied',
copyThreadWorkspaceFailed: 'Could not copy the working directory',
renameChatTitle: 'Rename conversation',
renamePlaceholder: 'Leave empty to restore the default title',
pinTop: 'Pin to top',
Expand Down
4 changes: 4 additions & 0 deletions apps/desktop/src/renderer/src/redesign/ChatFirstShell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ import { LiveConversation } from './Conversation'
import { type SlashCommand, type ComposerPrefill, restoreToComposer } from './Composer'
import { type EditorState, ProfileView, PersonaEditor } from './ProfileView'
import { type SettingsInit, Settings } from './SettingsPane'
import { useThreadContinuation } from './ThreadContinuation'

/**
* 「对话优先」外壳(已接真实 store)。
Expand Down Expand Up @@ -373,6 +374,7 @@ export function ChatFirstShell(): React.JSX.Element {
selectSession(id)
setRailTab('chats')
}
const { continueThread, copyThreadWorkspace } = useThreadContinuation(railSessions, openThread)
// 查看某角色资料 → 切到「角色」tab 并选中该角色(右侧随之显示其资料卡)。
const openProfile = (personaId: string): void => {
setViewPersonaId(personaId)
Expand Down Expand Up @@ -668,6 +670,8 @@ export function ChatFirstShell(): React.JSX.Element {
onAddPersona={() => setEditor({ mode: 'create' })}
onAddPersonaByChat={addPersonaByChat}
onNewChatFromThread={newChatFromThread}
onContinueThread={continueThread}
onCopyThreadWorkspace={copyThreadWorkspace}
onRenameThread={renameThread}
onArchiveThread={archiveThread}
onUnarchiveThread={(id) => setArchived(id, false)}
Expand Down
27 changes: 27 additions & 0 deletions apps/desktop/src/renderer/src/redesign/Rail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ import {
ArrowUpToLine,
ChevronRight,
Cog,
Copy,
Folder,
FolderMinus,
Globe,
GitBranch,
Check,
ListChecks,
ListFilter,
Expand Down Expand Up @@ -220,6 +222,8 @@ export function Rail({
onAddPersona,
onAddPersonaByChat,
onNewChatFromThread,
onContinueThread,
onCopyThreadWorkspace,
onRenameThread,
onArchiveThread,
onUnarchiveThread,
Expand All @@ -246,6 +250,8 @@ export function Rail({
onAddPersona: () => void
onAddPersonaByChat: () => void
onNewChatFromThread: (id: string) => void
onContinueThread: (id: string) => Promise<boolean>
onCopyThreadWorkspace: (id: string) => Promise<void>
/** 重命名对话(弹框输入新标题);title 为当前标题。 */
onRenameThread: (id: string, title: string) => void
/** 归档(从列表移走,提示条可撤销)/ 移回对话列表。 */
Expand Down Expand Up @@ -382,6 +388,25 @@ export function Rail({
clearFilters()
fn()
}
const threadContinuationItems = (id: string): CtxEntry[] => [
{
label: t('cf.continueChat'),
icon: <GitBranch size={14} />,
onClick: () => {
void onContinueThread(id).then((opened) => {
if (!opened) return
setArchiveView(false)
setQuery('')
clearFilters()
})
}
},
{
label: t('cf.copyThreadWorkspace'),
icon: <Copy size={14} />,
onClick: () => void onCopyThreadWorkspace(id)
}
]
// 筛选面板的选项(只在打开时算):有对话的角色按花名册顺序,挂过的文件夹按最近使用;已选的即便没有对话了
// 也列出来,好取消。数字是在另一类条件下的对话数,为 0 置灰(仍可点)。
const filterOptions = useMemo(() => {
Expand Down Expand Up @@ -780,6 +805,7 @@ export function Rail({
? selectMenuItems()
: menu.kind === 'thread' && menu.archived
? [
...threadContinuationItems(menu.id),
multiSelectItem(menu.id),
{
label: t('cf.unarchive'),
Expand All @@ -800,6 +826,7 @@ export function Rail({
icon: <Plus size={14} />,
onClick: () => startFresh(() => onNewChatFromThread(menu.id))
},
...threadContinuationItems(menu.id),
{
label: t('cf.renameChat'),
icon: <Pencil size={14} />,
Expand Down
35 changes: 35 additions & 0 deletions apps/desktop/src/renderer/src/redesign/ThreadContinuation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { useToast } from '../components/ToastProvider'
import { useI18n } from '../i18n/i18n'
import type { SessionMeta } from '../store/chat'

export function useThreadContinuation(sessions: SessionMeta[], openThread: (id: string) => void) {
const { t } = useI18n()
const toast = useToast()

async function continueThread(id: string): Promise<boolean> {
try {
const next = await window.deva.chat.continueSession(id)
if (!next) throw new Error('Source conversation unavailable')
openThread(next)
toast.show({ message: t('cf.continuedChat') })
return true
} catch {
toast.show({ variant: 'error', message: t('cf.continueChatFailed') })
return false
}
}

async function copyThreadWorkspace(id: string): Promise<void> {
try {
const source = sessions.find((session) => session.id === id)
if (!source) throw new Error('Source conversation unavailable')
const path = source.focusRoot || (await window.deva.workspace.roleHome(source.personaId ?? '')).path
await window.deva.clipboard.writeText(path)
toast.show({ message: t('cf.copiedThreadWorkspace') })
} catch {
toast.show({ variant: 'error', message: t('cf.copyThreadWorkspaceFailed') })
}
}

return { continueThread, copyThreadWorkspace }
}