-
Notifications
You must be signed in to change notification settings - Fork 3.1k
perf: speed up large session forks #11075
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
e17ce0c
perf: speed up large session forks
marius-kilocode a86f60d
fix(cli): adapt fork writer to sync service
marius-kilocode 31eb7e1
test(vscode): avoid TSX import in hydration unit test
marius-kilocode fd566bb
fix(cli): detach background task references
marius-kilocode File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,7 @@ | ||
| --- | ||
| "@kilocode/cli": patch | ||
| "@kilocode/kilo-ui": patch | ||
| "kilo-code": patch | ||
| --- | ||
|
|
||
| Speed up large session forks by retaining final task outcomes instead of duplicating resumable subagent histories, and load completed task details only when expanded. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
41 changes: 41 additions & 0 deletions
41
packages/kilo-vscode/tests/unit/task-tool-hydration.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import { beforeEach, describe, expect, it } from "bun:test" | ||
| import { | ||
| readToolOpen, | ||
| resetToolOpenState, | ||
| toolOpenKey, | ||
| writeToolOpen, | ||
| } from "../../../kilo-ui/src/components/tool-open-state" | ||
| import { taskResult, taskRunning, taskVisible } from "../../webview-ui/src/components/chat/task-tool-state" | ||
|
|
||
| describe("completed task hydration", () => { | ||
| beforeEach(() => resetToolOpenState()) | ||
|
|
||
| it("opens running tasks and collapses completed tasks by default", () => { | ||
| expect(taskRunning("pending")).toBe(true) | ||
| expect(taskRunning("running")).toBe(true) | ||
| expect(taskRunning("completed")).toBe(false) | ||
| expect(readToolOpen(toolOpenKey({ tool: "task", partID: "part-new" }), taskRunning("completed"))).toBe(false) | ||
| }) | ||
|
|
||
| it("keeps expansion state isolated by copied part ID", () => { | ||
| const source = { tool: "task", partID: "part-source", defaultOpen: false } | ||
| const fork = { tool: "task", partID: "part-fork", defaultOpen: false } | ||
| writeToolOpen(toolOpenKey(source), true) | ||
|
|
||
| expect(readToolOpen(toolOpenKey(source), source.defaultOpen)).toBe(true) | ||
| expect(readToolOpen(toolOpenKey(fork), fork.defaultOpen)).toBe(false) | ||
| }) | ||
|
|
||
| it("hydrates and streams a child only while expanded", () => { | ||
| expect(taskVisible(false, "ses_child")).toBeUndefined() | ||
| expect(taskVisible(true, "ses_child")).toBe("ses_child") | ||
| expect(taskVisible(true, undefined)).toBeUndefined() | ||
| }) | ||
|
|
||
| it("renders the retained result when a fork has no child session", () => { | ||
| const output = "task_id: stale\n\n<task_result>\nchild outcome\n</task_result>" | ||
| expect(taskResult(output, undefined)).toBe("child outcome") | ||
| expect(taskResult(output, "ses_child")).toBeUndefined() | ||
| expect(taskResult("plain output", undefined)).toBe("plain output") | ||
| }) | ||
| }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
13 changes: 13 additions & 0 deletions
13
packages/kilo-vscode/webview-ui/src/components/chat/task-tool-state.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| export function taskRunning(status: string | undefined) { | ||
| return status === "pending" || status === "running" | ||
| } | ||
|
|
||
| export function taskVisible(open: boolean | undefined, id: string | undefined) { | ||
| return open ? id : undefined | ||
| } | ||
|
|
||
| export function taskResult(output: string | undefined, id: string | undefined) { | ||
| if (id || typeof output !== "string") return | ||
| const match = /<task_result>\s*([\s\S]*?)\s*<\/task_result>/.exec(output) | ||
| return match?.[1] ?? output | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,71 +1,125 @@ | ||
| import { Effect } from "effect" | ||
| import { Session } from "@/session/session" | ||
| import { MessageV2 } from "@/session/message-v2" | ||
| import { SessionID, PartID } from "@/session/schema" | ||
| import * as Log from "@opencode-ai/core/util/log" | ||
| import { SessionID } from "@/session/schema" | ||
| import { Database } from "@/storage/db" | ||
| import { SyncEvent } from "@/sync" | ||
| import { Effect } from "effect" | ||
|
|
||
| const log = Log.create({ service: "session.fork" }) | ||
| const task = "task" | ||
| const stale = /^[ \t]*task_id:[^\r\n]*(?:(?:\r?\n){1,2}|$)/m | ||
|
|
||
| /** | ||
| * Extracts the child session ID from a task tool part. | ||
| */ | ||
| function childID(part: MessageV2.Part): string | undefined { | ||
| if (part.type !== "tool" || part.tool !== "task") return undefined | ||
| return (part.state as { metadata?: { sessionId?: string } }).metadata?.sessionId | ||
| type Item = { type: "message"; info: MessageV2.Info } | { type: "part"; part: MessageV2.Part; time: number } | ||
|
|
||
| export function writer(sessionID: SessionID, sync: SyncEvent.Interface) { | ||
| const items: Item[] = [] | ||
| return { | ||
| message<T extends MessageV2.Info>(info: T) { | ||
| items.push({ type: "message", info }) | ||
| return info | ||
| }, | ||
| part(part: MessageV2.Part) { | ||
| items.push({ type: "part", part: structuredClone(detachPart(part)), time: Date.now() }) | ||
| }, | ||
| commit() { | ||
| return Effect.sync(() => | ||
| Database.transaction( | ||
| () => { | ||
| // sync.run stays synchronous with publishing disabled, and its nested transaction reuses this active transaction. | ||
| for (const item of items) { | ||
| if (item.type === "message") { | ||
| Effect.runSync(sync.run(MessageV2.Event.Updated, { sessionID, info: item.info }, { publish: false })) | ||
| continue | ||
| } | ||
| Effect.runSync( | ||
| sync.run( | ||
| MessageV2.Event.PartUpdated, | ||
| { sessionID, part: item.part, time: item.time }, | ||
| { publish: false }, | ||
| ), | ||
| ) | ||
| } | ||
| }, | ||
| { behavior: "immediate" }, | ||
| ), | ||
| ) | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| function metadata(value: Record<string, unknown> | undefined) { | ||
| if (!value) return value | ||
| const copy = { ...value } | ||
| delete copy.sessionId | ||
| delete copy.sessionID | ||
| return copy | ||
| } | ||
|
|
||
| function input(value: Record<string, unknown>) { | ||
| const copy = { ...value } | ||
| delete copy.task_id | ||
| return copy | ||
| } | ||
|
|
||
| /** | ||
| * Recursively fork all child (subagent) sessions referenced by task tool parts | ||
| * in the given session, then update the parts to point at the forked copies. | ||
| * Turns copied task calls into detached historical results. | ||
| * | ||
| * This prevents subagent state from leaking between forked sessions in the | ||
| * same worktree: without remapping, two forked sessions would share the same | ||
| * child session references, causing SSE events and permission prompts to bleed | ||
| * across sessions. | ||
| * Child sessions are execution state, not conversation context. Their final | ||
| * result is already embedded in the parent task part, so a fork keeps that | ||
| * result while dropping references that could resume, stream, or route prompts | ||
| * to a child owned by the source session. | ||
| */ | ||
| export function remapChildren( | ||
| sid: SessionID, | ||
| remapped = new Map<string, SessionID>(), | ||
| ): Effect.Effect<void, Session.NotFound, Session.Service> { | ||
| return Effect.gen(function* () { | ||
| const sessions = yield* Session.Service | ||
| const msgs = yield* sessions.messages({ sessionID: sid }) | ||
| const refs: { part: MessageV2.ToolPart; child: string }[] = [] | ||
| for (const msg of msgs) { | ||
| for (const part of msg.parts) { | ||
| const child = childID(part) | ||
| if (child) refs.push({ part: part as MessageV2.ToolPart, child }) | ||
| } | ||
| } | ||
| if (refs.length === 0) return | ||
| function detachPart(part: MessageV2.Part): MessageV2.Part { | ||
| if (part.type !== "tool" || part.tool !== task) return part | ||
|
|
||
| for (const ref of refs) { | ||
| if (remapped.has(ref.child)) continue | ||
| const exists = yield* sessions.get(SessionID.make(ref.child)).pipe(Effect.orElseSucceed(() => undefined)) | ||
| if (!exists) continue | ||
| const forked = yield* sessions.fork({ sessionID: SessionID.make(ref.child) }) | ||
| remapped.set(ref.child, forked.id) | ||
| yield* remapChildren(forked.id, remapped) | ||
| const top = metadata(part.metadata) | ||
| const state = part.state | ||
| if (state.status === "pending") { | ||
| const now = Date.now() | ||
| return { | ||
| ...part, | ||
| metadata: top, | ||
| state: { | ||
| status: "error", | ||
| input: input(state.input), | ||
| error: "Task was still pending when this session was forked.", | ||
| time: { start: now, end: now }, | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| if (remapped.size === 0) return | ||
| if (state.status === "running") { | ||
| return { | ||
| ...part, | ||
| metadata: top, | ||
| state: { | ||
| status: "error", | ||
| input: input(state.input), | ||
| error: "Task was still running when this session was forked.", | ||
| metadata: metadata(state.metadata), | ||
| time: { start: state.time.start, end: Date.now() }, | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| for (const ref of refs) { | ||
| const replacement = remapped.get(ref.child) | ||
| if (!replacement) continue | ||
| const meta = (ref.part.state as { metadata?: Record<string, unknown> }).metadata | ||
| if (!meta) continue | ||
| yield* sessions.updatePart({ | ||
| ...ref.part, | ||
| id: PartID.make(ref.part.id), | ||
| sessionID: SessionID.make(ref.part.sessionID), | ||
| state: { | ||
| ...ref.part.state, | ||
| metadata: { ...meta, sessionId: replacement }, | ||
| }, | ||
| } as MessageV2.ToolPart) | ||
| if (state.status === "error") { | ||
| return { | ||
| ...part, | ||
| metadata: top, | ||
| state: { | ||
| ...state, | ||
| input: input(state.input), | ||
| metadata: metadata(state.metadata), | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| log.info("remapped child sessions", { session: sid, count: remapped.size }) | ||
| }) | ||
| return { | ||
| ...part, | ||
| metadata: top, | ||
| state: { | ||
| ...state, | ||
| input: input(state.input), | ||
| output: state.output.replace(stale, ""), | ||
| metadata: metadata(state.metadata) ?? {}, | ||
| }, | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.