
上一篇最后看到sessionManager中为branchWithSummary单独写了一个session操作方法,我们可以点进去看看对session有哪些基础操作。
Tree Traversal 内的方法大致可以分为三类
get,直接返回树上的信息:
// =========================================================================
// Tree Traversal
// =========================================================================
getLeafId(): string | null {
return this.leafId;
}
getLeafEntry(): SessionEntry | undefined {
return this.leafId ? this.byId.get(this.leafId) : undefined;
}
getEntry(id: string): SessionEntry | undefined {
return this.byId.get(id);
}
/**
* Get all direct children of an entry.
*/
getChildren(parentId: string): SessionEntry[] {
const children: SessionEntry[] = [];
for (const entry of this.byId.values()) {
if (entry.parentId === parentId) {
children.push(entry);
}
}
return children;
}
/**
* Get the label for an entry, if any.
*/
getLabel(id: string): string | undefined {
return this.labelsById.get(id);
}
/**
* Walk from entry to root, returning all entries in path order.
* Includes all entry types (messages, compaction, model changes, etc.).
* Use buildSessionContext() to get the resolved messages for the LLM.
*/
getBranch(fromId?: string): SessionEntry[] {
const path: SessionEntry[] = [];
const startId = fromId ?? this.leafId;
let current = startId ? this.byId.get(startId) : undefined;
while (current) {
path.push(current);
current = current.parentId ? this.byId.get(current.parentId) : undefined;
}
path.reverse();
return path;
}针对老的entry进行更新操作(apend 一条变更记录)
/**
* Set or clear a label on an entry.
* Labels are user-defined markers for bookmarking/navigation.
* Pass undefined or empty string to clear the label.
*/
appendLabelChange(targetId: string, label: string | undefined): string {
if (!this.byId.has(targetId)) {
throw new Error(`Entry ${targetId} not found`);
}
const entry: LabelEntry = {
type: "label",
id: generateId(this.byId),
parentId: this.leafId,
timestamp: new Date().toISOString(),
targetId,
label,
};
this._appendEntry(entry);
if (label) {
this.labelsById.set(targetId, label);
this.labelTimestampsById.set(targetId, entry.timestamp);
} else {
this.labelsById.delete(targetId);
this.labelTimestampsById.delete(targetId);
}
return entry.id;
}build,根据session 创建Projection,然后从Projection中提取信息:
/**
* Build the active, compaction-aware entry list for context/rendering.
* Uses tree traversal from current leaf.
*/
buildContextEntries(): SessionEntry[] {
return buildContextEntries(this.getEntries(), this.leafId, this.byId);
}
/**
* Build the session context (what gets sent to the LLM).
* Uses tree traversal from current leaf.
*/
buildSessionProjection(): SessionProjection {
return buildSessionProjection(this.getEntries(), this.leafId, this.byId);
}
buildSessionContext(): SessionContext {
const { messages, thinkingLevel, model } = this.buildSessionProjection();
return { messages, thinkingLevel, model };
}然后就是这次我关注到的:
branchWithSummary 直接在 session 里面 append 一条BranchSummaryEntry
/**
* Start a new branch with a summary of the abandoned path.
* Same as branch(), but also appends a branch_summary entry that captures
* context from the abandoned conversation path.
*/
branchWithSummary(
branchFromId: string | null,
summary: string,
details?: unknown,
fromHook?: boolean,
usage?: Usage,
): string {
if (branchFromId !== null && !this.byId.has(branchFromId)) {
throw new Error(`Entry ${branchFromId} not found`);
}
const fromId = this.leafId ?? "root";
this.leafId = branchFromId;
const entry: BranchSummaryEntry = {
type: "branch_summary",
id: generateId(this.byId),
parentId: branchFromId,
timestamp: new Date().toISOString(),
fromId,
summary,
details,
usage,
fromHook,
};
this._appendEntry(entry);
return entry.id;
}发现还有一个 创建新session方法,看了一下注释是从一个entry创建一个新的conversation,会创建一个新的session 文件。emm..这不是fork的功能嘛?
/**
* Create a new session file containing only the path from root to the specified leaf.
* Useful for extracting a single conversation path from a branched session.
* Returns the new session file path, or undefined if not persisting.
*/
createBranchedSession(leafId: string): string | undefined {
const previousSessionFile = this.sessionFile;
const path = this.getBranch(leafId);
if (path.length === 0) {
throw new Error(`Entry ${leafId} not found`);
}
// Filter out LabelEntry from path - we'll recreate them from the resolved map.
// Because labels are real tree entries, later entries can be children of labels;
// removing labels requires re-chaining the retained path to avoid orphaned subtrees.
const pathWithoutLabels: SessionEntry[] = [];
const replacementByLabelId = new Map<string, string>();
const pendingLabelIds: string[] = [];
let pathParentId: string | null = null;
for (const entry of path) {
if (entry.type === "label") {
pendingLabelIds.push(entry.id);
continue;
}
for (const labelId of pendingLabelIds) {
replacementByLabelId.set(labelId, entry.id);
}
pendingLabelIds.length = 0;
pathWithoutLabels.push(
entry.type === "compaction"
? {
...entry,
parentId: pathParentId,
firstKeptEntryId:
entry.firstKeptEntryId === entry.id
? entry.id
: (replacementByLabelId.get(entry.firstKeptEntryId) ?? entry.firstKeptEntryId),
}
: { ...entry, parentId: pathParentId },
);
pathParentId = entry.id;
}
const newSessionId = createSessionId();
const timestamp = new Date().toISOString();
const fileTimestamp = timestamp.replace(/[:.]/g, "-");
const newSessionFile = join(this.getSessionDir(), `${fileTimestamp}_${newSessionId}.jsonl`);
const header: SessionHeader = {
type: "session",
version: CURRENT_SESSION_VERSION,
id: newSessionId,
timestamp,
cwd: this.cwd,
parentSession: this.persist ? previousSessionFile : undefined,
};
// Collect labels for entries in the path
const pathEntryIds = new Set(pathWithoutLabels.map((e) => e.id));
const labelsToWrite: Array<{ targetId: string; label: string; timestamp: string }> = [];
for (const [targetId, label] of this.labelsById) {
if (pathEntryIds.has(targetId)) {
labelsToWrite.push({ targetId, label, timestamp: this.labelTimestampsById.get(targetId)! });
}
}
if (this.persist) {
// Build label entries
const lastEntryId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
let parentId = lastEntryId;
const labelEntries: LabelEntry[] = [];
for (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {
const labelEntry: LabelEntry = {
type: "label",
id: generateId(new Set(pathEntryIds)),
parentId,
timestamp: labelTimestamp,
targetId,
label,
};
pathEntryIds.add(labelEntry.id);
labelEntries.push(labelEntry);
parentId = labelEntry.id;
}
this.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];
this.sessionId = newSessionId;
this.sessionFile = newSessionFile;
this._buildIndex();
// Use the same rule as _persist(): write now if the branched path already
// has a conversation, otherwise let _persist() create the file later.
if (this._hasConversation()) {
this._rewriteFile();
this.flushed = true;
} else {
this.flushed = false;
}
return newSessionFile;
}
// In-memory mode: replace current session with the path + labels
const labelEntries: LabelEntry[] = [];
let parentId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
for (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {
const labelEntry: LabelEntry = {
type: "label",
id: generateId(new Set([...pathEntryIds, ...labelEntries.map((e) => e.id)])),
parentId,
timestamp: labelTimestamp,
targetId,
label,
};
labelEntries.push(labelEntry);
parentId = labelEntry.id;
}
this.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];
this.sessionId = newSessionId;
this._buildIndex();
return undefined;
}找了一下调用点,果然是fork的时候调用的,之前对fork的理解非常简单,直接把整个session文件复制一份不就完成了嘛,看了一下代码还是做了一些清理操作的:
async fork(
entryId: string,
options?: { position?: "before" | "at"; withSession?: (ctx: ReplacedSessionContext) => Promise<void> },
): Promise<{ cancelled: boolean; selectedText?: string }> {
const position = options?.position ?? "before";
const beforeResult = await this.emitBeforeFork(entryId, { position });
if (beforeResult.cancelled) {
return { cancelled: true };
}
let targetLeafId: string | null;
let selectedText: string | undefined;
const selectedEntry = this.session.sessionManager.getEntry(entryId);
if (!selectedEntry) {
throw new Error("Invalid entry ID for forking");
}
if (position === "at") {
targetLeafId = selectedEntry.id;
} else {
if (selectedEntry.type !== "message" || selectedEntry.message.role !== "user") {
throw new Error("Invalid entry ID for forking");
}
targetLeafId = selectedEntry.parentId;
selectedText = extractUserMessageText(selectedEntry.message.content);
}
const previousSessionFile = this.session.sessionFile;
if (this.session.sessionManager.isPersisted()) {
const currentSessionFile = this.session.sessionFile;
if (!currentSessionFile) {
throw new Error("Persisted session is missing a session file");
}
const sessionDir = this.session.sessionManager.getSessionDir();
if (!targetLeafId) {
const sessionManager = SessionManager.create(this.cwd, sessionDir);
sessionManager.newSession({ parentSession: currentSessionFile });
await this.teardownCurrent("fork", sessionManager.getSessionFile());
this.apply(
await this.createRuntime({
cwd: this.cwd,
agentDir: this.services.agentDir,
sessionManager,
sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile },
}),
);
await this.finishSessionReplacement(options?.withSession);
return { cancelled: false, selectedText };
}
if (!existsSync(currentSessionFile)) {
throw new Error("This session has not been saved yet. Send a message before cloning or forking it.");
}
const sessionManager = SessionManager.open(currentSessionFile, sessionDir);
const forkedSessionPath = sessionManager.createBranchedSession(targetLeafId);
if (!forkedSessionPath) {
throw new Error("Failed to create forked session");
}
await this.teardownCurrent("fork", sessionManager.getSessionFile());
this.apply(
await this.createRuntime({
cwd: sessionManager.getCwd(),
agentDir: this.services.agentDir,
sessionManager,
sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile },
}),
);
await this.finishSessionReplacement(options?.withSession);
return { cancelled: false, selectedText };
}
const sessionManager = this.session.sessionManager;
await this.teardownCurrent("fork", sessionManager.getSessionFile());
if (!targetLeafId) {
sessionManager.newSession({ parentSession: previousSessionFile });
} else {
sessionManager.createBranchedSession(targetLeafId);
}
this.apply(
await this.createRuntime({
cwd: this.cwd,
agentDir: this.services.agentDir,
sessionManager,
sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile },
}),
);
await this.finishSessionReplacement(options?.withSession);
return { cancelled: false, selectedText };
}打开pi实际操作了一下,fork的时候可选的是user_query,fork之后会生成一条全新的对话,把选中的一轮query回退到输入框中允许修改后发送(和tree一致)。

fork之后再resume,可以看到新session是从哪个老session fork出来的。

通过getBranch获取 从fork点到root的path。
通过path构建 pathWithoutLabels-无标签的sessionEntry
这里又提到了一个之前没见过的entry-label ,作用是给之前的一条entry加一个显示的label(连这种事情都要单独append 一条entry吗,现在处理的时候增加了好多复杂度)
还好虽然append-only session虽然记录一些看起来不重要的entry,在fork的时候也一次性整理了。
在pi里使用 /tree 命令打开 entries,选中一条 输入 shift+L ,即可给这条entry起一个label。

开始处理path
如果entry类型是 label,跳过不往 pathWithoutLabels 里添加,并记录在pendingLabelIds中。
继续朝后遍历entry,直到第一个非label的 entry时候,将这批labelid 都指向这个非label的entry id上。并在replacementByLabelId 中记录。
如果entry类型是compact,检查firstKeptEntryId ,因为压缩时没有刻意限制,边界id可能指向的是一条 label entry。 所以此处要根据之前记录的 replacementByLabelId 来完成firstKeptEntryId的替换,从label entry调整为label后的第一个非label entry。
完成整理之后,就开始创建新的session文件了。创建新的session header。
然后又重新收集了一遍label,如果在之前整理的 pathWithoutLabels 中有 label 的targetid匹配的label,继续追加到session最后面。
再往下看 发现 pi还有一个 In-memory mode,在这种模式下不会持久化session,而是全部在内存中操作,主要针对SDK场景,对我们流程的理解没有影响,所以略过。
/**
* Create a new session file containing only the path from root to the specified leaf.
* Useful for extracting a single conversation path from a branched session.
* Returns the new session file path, or undefined if not persisting.
*/
createBranchedSession(leafId: string): string | undefined {
const previousSessionFile = this.sessionFile;
const path = this.getBranch(leafId);
if (path.length === 0) {
throw new Error(`Entry ${leafId} not found`);
}
// Filter out LabelEntry from path - we'll recreate them from the resolved map.
// Because labels are real tree entries, later entries can be children of labels;
// removing labels requires re-chaining the retained path to avoid orphaned subtrees.
const pathWithoutLabels: SessionEntry[] = [];
const replacementByLabelId = new Map<string, string>();
const pendingLabelIds: string[] = [];
let pathParentId: string | null = null;
for (const entry of path) {
if (entry.type === "label") {
pendingLabelIds.push(entry.id);
continue;
}
for (const labelId of pendingLabelIds) {
replacementByLabelId.set(labelId, entry.id);
}
pendingLabelIds.length = 0;
pathWithoutLabels.push(
entry.type === "compaction"
? {
...entry,
parentId: pathParentId,
firstKeptEntryId:
entry.firstKeptEntryId === entry.id
? entry.id
: (replacementByLabelId.get(entry.firstKeptEntryId) ?? entry.firstKeptEntryId),
}
: { ...entry, parentId: pathParentId },
);
pathParentId = entry.id;
}
const newSessionId = createSessionId();
const timestamp = new Date().toISOString();
const fileTimestamp = timestamp.replace(/[:.]/g, "-");
const newSessionFile = join(this.getSessionDir(), `${fileTimestamp}_${newSessionId}.jsonl`);
const header: SessionHeader = {
type: "session",
version: CURRENT_SESSION_VERSION,
id: newSessionId,
timestamp,
cwd: this.cwd,
parentSession: this.persist ? previousSessionFile : undefined,
};
// Collect labels for entries in the path
const pathEntryIds = new Set(pathWithoutLabels.map((e) => e.id));
const labelsToWrite: Array<{ targetId: string; label: string; timestamp: string }> = [];
for (const [targetId, label] of this.labelsById) {
if (pathEntryIds.has(targetId)) {
labelsToWrite.push({ targetId, label, timestamp: this.labelTimestampsById.get(targetId)! });
}
}
if (this.persist) {
// Build label entries
const lastEntryId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
let parentId = lastEntryId;
const labelEntries: LabelEntry[] = [];
for (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {
const labelEntry: LabelEntry = {
type: "label",
id: generateId(new Set(pathEntryIds)),
parentId,
timestamp: labelTimestamp,
targetId,
label,
};
pathEntryIds.add(labelEntry.id);
labelEntries.push(labelEntry);
parentId = labelEntry.id;
}
this.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];
this.sessionId = newSessionId;
this.sessionFile = newSessionFile;
this._buildIndex();
// Use the same rule as _persist(): write now if the branched path already
// has a conversation, otherwise let _persist() create the file later.
if (this._hasConversation()) {
this._rewriteFile();
this.flushed = true;
} else {
this.flushed = false;
}
return newSessionFile;
}
// In-memory mode: replace current session with the path + labels
const labelEntries: LabelEntry[] = [];
let parentId = pathWithoutLabels[pathWithoutLabels.length - 1]?.id || null;
for (const { targetId, label, timestamp: labelTimestamp } of labelsToWrite) {
const labelEntry: LabelEntry = {
type: "label",
id: generateId(new Set([...pathEntryIds, ...labelEntries.map((e) => e.id)])),
parentId,
timestamp: labelTimestamp,
targetId,
label,
};
labelEntries.push(labelEntry);
parentId = labelEntry.id;
}
this.fileEntries = [header, ...pathWithoutLabels, ...labelEntries];
this.sessionId = newSessionId;
this._buildIndex();
return undefined;回到fork() 外层:
在完成session的fork操作之后,停止当前轮次的操作,向扩展发布 session_shutdown 事件。
注意到这句注释,当前正在进行的turn 会正常执行完,持久化完成才会abort,当然这个的实现方式我们已经在agent loop中看到过了,abort的时机设置。(当时还嫌怎么每个异步后面都加,加的到处都是,现在一看还是加的很克制的):
Settle any active response first so the aborted turn (including tool results) is persisted to the outgoing session before it is replaced
在界面上创建一个新的对话,绑定到fork出来的新session上。
private async teardownCurrent(reason: SessionShutdownEvent["reason"], targetSessionFile?: string): Promise<void> {
// Settle any active response first so the aborted turn (including tool
// results) is persisted to the outgoing session before it is replaced.
await this.session.abort();
await emitSessionShutdownEvent(this.session.extensionRunner, {
type: "session_shutdown",
reason,
targetSessionFile,
});
this.beforeSessionInvalidate?.();
this.session.dispose();
} const forkedSessionPath = sessionManager.createBranchedSession(targetLeafId);
if (!forkedSessionPath) {
throw new Error("Failed to create forked session");
}
await this.teardownCurrent("fork", sessionManager.getSessionFile());
this.apply(
await this.createRuntime({
cwd: sessionManager.getCwd(),
agentDir: this.services.agentDir,
sessionManager,
sessionStartEvent: { type: "session_start", reason: "fork", previousSessionFile },
}),
);
await this.finishSessionReplacement(options?.withSession);
return { cancelled: false, selectedText };最后再回到一开始的问题,fork和完整复制session的区别
然后又发现pi也有一个命令 /clone
这clone 总得是 完整复制session了吧?
点进去一看发现clone也不是复制完整session。
clone其实也是复用了fork的方法,只是fork点设置为了叶子节点,position:"at"。
这又解除了之前的一个困惑:我在界面上操作不管选哪个entry,都会回退到query发送之前:对应代码里面的position是"before"。
原来position:"at" 的触发点竟然是单独的clone命令。
private async handleCloneCommand(): Promise<void> {
const leafId = this.sessionManager.getLeafId();
if (!leafId) {
this.showStatus("Nothing to clone yet");
return;
}
try {
const result = await this.runtimeHost.fork(leafId, { position: "at" });
if (result.cancelled) {
this.ui.requestRender();
return;
}
this.editor.setText("");
this.showStatus("Cloned to new session");
} catch (error: unknown) {
this.showError(error instanceof Error ? error.message : String(error));
}
}完整复制,fork和clone的区别,我做了一个对比:
pi 中不存在任何做整文件复制的命令——连名为 clone 的命令都走提取路径。append-only 的原始文件永远是唯一的全量持有者,一切“复制”类操作都是视图提取。
维度 | 完整复制 | fork | clone |
|---|---|---|---|
带走什么 | 全部历史 | 从指定的一条branch中提取 | 从当前所处的叶子节点branch中提取 |
新文件形状 | 原树原样 | 主链 + 清洗label 统一放到尾部 | 同fork |
善后成本 | 无 | 重排 parentId + 修compaction entry 的指针 + 重建 label | 同fork |
后续动作 | 手动切换 | 自动停止当前轮对话,切换到新对话 ,回到指定query轮次正在输入状态,可修改 | 切换到新对话,在当前进度继续聊 |
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。