Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 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
5 changes: 5 additions & 0 deletions .changeset/agent-terminal-switch.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"kilo-code": patch
---

Add Agent Manager terminal switching so existing session terminals are revealed when changing sessions.
3 changes: 3 additions & 0 deletions .husky/_/post-commit
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/sh
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-commit' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
git lfs post-commit "$@"
3 changes: 3 additions & 0 deletions .husky/_/post-merge
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/sh
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'post-merge' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
git lfs post-merge "$@"
3 changes: 3 additions & 0 deletions .husky/_/pre-push
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/sh
command -v git-lfs >/dev/null 2>&1 || { printf >&2 "\n%s\n\n" "This repository is configured for Git LFS but 'git-lfs' was not found on your path. If you no longer wish to use Git LFS, remove this hook by deleting the 'pre-push' file in the hooks directory (set by 'core.hookspath'; usually '.git/hooks')."; exit 2; }
git lfs pre-push "$@"
6 changes: 6 additions & 0 deletions src/__tests__/common-mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,12 @@ export function setupCommonMocks() {
joinPath: vi.fn(),
file: vi.fn(),
},
RelativePattern: vi.fn().mockImplementation((base, pattern) => ({ base, pattern })),
Disposable: {
from: vi.fn().mockImplementation((...disposables) => ({
dispose: vi.fn(),
})),
},
CodeActionKind: {
QuickFix: { value: "quickfix" },
RefactorRewrite: { value: "refactor.rewrite" },
Expand Down
39 changes: 37 additions & 2 deletions src/core/kilocode/agent-manager/AgentManagerProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { t } from "i18next"
import { AgentRegistry } from "./AgentRegistry"
import { renameMapKey } from "./mapUtils"
import {
buildParallelModeWorktreePath,
parseParallelModeBranch,
parseParallelModeWorktreePath,
isParallelModeCompletionMessage,
Expand Down Expand Up @@ -37,6 +38,7 @@ import type { ClineProvider } from "../../webview/ClineProvider"
import { extractSessionConfigs, MAX_VERSION_COUNT } from "./multiVersionUtils"
import { SessionManager } from "../../../shared/kilocode/cli-sessions/core/SessionManager"
import { WorkspaceGitService } from "./WorkspaceGitService"
import { SessionTerminalManager } from "./SessionTerminalManager"

/**
* AgentManagerProvider
Expand All @@ -53,6 +55,7 @@ export class AgentManagerProvider implements vscode.Disposable {
private remoteSessionService: RemoteSessionService
private processHandler: CliProcessHandler
private eventProcessor: KilocodeEventProcessor
private terminalManager: SessionTerminalManager
private sessionLauncher: CliSessionLauncher
private sessionMessages: Map<string, ClineMessage[]> = new Map()
// Track first api_req_started per session to filter user-input echoes
Expand All @@ -72,6 +75,7 @@ export class AgentManagerProvider implements vscode.Disposable {
) {
this.registry = new AgentRegistry()
this.remoteSessionService = new RemoteSessionService({ outputChannel })
this.terminalManager = new SessionTerminalManager(this.registry, this.outputChannel)

// Initialize session launcher with pre-warming
// Pre-warming starts slow lookups (CLI: 500-2000ms, git: 50-100ms) immediately
Expand Down Expand Up @@ -296,6 +300,9 @@ export class AgentManagerProvider implements vscode.Disposable {
case "agentManager.refreshSessionMessages":
void this.refreshSessionMessages(message.sessionId as string)
break
case "agentManager.showTerminal":
this.terminalManager.showTerminal(message.sessionId as string)
break
case "agentManager.sessionShare":
SessionManager.init()
?.shareSession(message.sessionId as string)
Expand Down Expand Up @@ -640,17 +647,42 @@ export class AgentManagerProvider implements vscode.Disposable {
}

/**
* Handle welcome event from CLI - extracts worktree branch for parallel mode sessions
* Handle welcome event from CLI - extracts worktree branch and path for parallel mode sessions
*/
private handleWelcomeEvent(sessionId: string, event: WelcomeStreamEvent): void {
let updated = false
const session = this.registry.getSession(sessionId)
const existingWorktreePath = session?.parallelMode?.worktreePath

if (event.worktreeBranch) {
this.outputChannel.appendLine(
`[AgentManager] Session ${sessionId} worktree branch: ${event.worktreeBranch}`,
)
if (this.registry.updateParallelModeInfo(sessionId, { branch: event.worktreeBranch })) {
this.postStateToWebview()
updated = true
}
}

if (event.worktreePath) {
this.outputChannel.appendLine(`[AgentManager] Session ${sessionId} worktree path: ${event.worktreePath}`)
if (this.registry.updateParallelModeInfo(sessionId, { worktreePath: event.worktreePath })) {
updated = true
}
}

if (!event.worktreePath && event.worktreeBranch && !existingWorktreePath) {
const derivedWorktreePath = buildParallelModeWorktreePath(event.worktreeBranch)
this.outputChannel.appendLine(
`[AgentManager] Session ${sessionId} derived worktree path: ${derivedWorktreePath}`,
)
if (this.registry.updateParallelModeInfo(sessionId, { worktreePath: derivedWorktreePath })) {
updated = true
}
}

if (updated) {
this.postStateToWebview()
}
}

private handleKilocodeEvent(sessionId: string, event: KilocodeStreamEvent): void {
Expand All @@ -670,6 +702,8 @@ export class AgentManagerProvider implements vscode.Disposable {

if (!sessionId) return

this.terminalManager.showExistingTerminal(sessionId)

// Check if we have cached messages to send immediately
const cachedMessages = this.sessionMessages.get(sessionId)
if (cachedMessages) {
Expand Down Expand Up @@ -1136,6 +1170,7 @@ export class AgentManagerProvider implements vscode.Disposable {

public dispose(): void {
this.processHandler.dispose()
this.terminalManager.dispose()
this.sessionMessages.clear()
this.firstApiReqStarted.clear()
this.sessionLauncher.clearPrewarm()
Expand Down
34 changes: 22 additions & 12 deletions src/core/kilocode/agent-manager/AgentRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,13 +152,16 @@ export class AgentRegistry {
info: Partial<Omit<ParallelModeInfo, "enabled">>,
): AgentSession | undefined {
const session = this.sessions.get(id)
if (!session || !session.parallelMode?.enabled) {
if (!session) {
return undefined
}

const currentParallelMode = session.parallelMode ?? { enabled: true }

session.parallelMode = {
...session.parallelMode,
...currentParallelMode,
...info,
enabled: true,
}

return session
Expand Down Expand Up @@ -214,19 +217,26 @@ export class AgentRegistry {
* Used when upgrading a provisional session to a real session ID.
*/
public renameSession(oldId: string, newId: string): boolean {
const session = this.sessions.get(oldId)
if (!session) {
return false
if (oldId === newId) {
return this.sessions.has(oldId)
}

// Update the session's internal ID
session.sessionId = newId

// Move in the map
this.sessions.delete(oldId)
this.sessions.set(newId, session)
const oldSession = this.sessions.get(oldId)
if (!oldSession) {
return false
}

// Update selectedId if it was pointing to the old ID
const targetSession = this.sessions.get(newId)
if (targetSession) {
// Prefer keeping the target session object (e.g. resuming an existing session),
// but merge in any provisional logs so early streaming isn't lost.
targetSession.logs = [...oldSession.logs, ...targetSession.logs]
this.sessions.delete(oldId)
} else {
this.sessions.delete(oldId)
oldSession.sessionId = newId
this.sessions.set(newId, oldSession)
}
if (this._selectedId === oldId) {
this._selectedId = newId
}
Expand Down
79 changes: 77 additions & 2 deletions src/core/kilocode/agent-manager/CliOutputParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ export interface SessionCreatedStreamEvent {
export interface WelcomeStreamEvent {
streamEventType: "welcome"
worktreeBranch?: string
worktreePath?: string
timestamp: number
}

Expand Down Expand Up @@ -143,8 +144,20 @@ export function parseCliChunk(chunk: string, buffer: string = ""): ParseResult {
continue
}

// Not JSON - strip VT characters before treating as plain text output event
// Fallback: handle concatenated JSON objects on a single line
const cleanLine = stripVTControlCharacters(trimmedLine)
const extracted = extractJsonObjects(cleanLine)
if (extracted.length > 0) {
for (const obj of extracted) {
const extractedEvent = toStreamEvent(obj)
if (extractedEvent !== null) {
events.push(extractedEvent)
}
}
continue
}

// Not JSON - treat as plain text output event
if (cleanLine) {
events.push(createOutputEvent(cleanLine))
}
Expand Down Expand Up @@ -192,6 +205,13 @@ export class CliOutputParser {

// Not JSON - strip VT characters before treating as plain text
const cleanLine = stripVTControlCharacters(trimmedBuffer)
const extracted = extractJsonObjects(cleanLine)
if (extracted.length > 0) {
const events = extracted
.map((obj) => toStreamEvent(obj))
.filter((extractedEvent): extractedEvent is StreamEvent => extractedEvent !== null)
return { events, remainingBuffer: "" }
}
if (cleanLine) {
return { events: [createOutputEvent(cleanLine)], remainingBuffer: "" }
}
Expand Down Expand Up @@ -223,13 +243,15 @@ function toStreamEvent(parsed: Record<string, unknown>): StreamEvent | null {
}
}

// Detect welcome event from CLI (format: { type: "welcome", metadata: { welcomeOptions: { worktreeBranch: "..." } }, ... })
// Detect welcome event from CLI (format: { type: "welcome", metadata: { welcomeOptions: { worktreeBranch: "...", workspace: "..." } }, ... })
if (parsed.type === "welcome") {
const metadata = parsed.metadata as Record<string, unknown> | undefined
const welcomeOptions = metadata?.welcomeOptions as Record<string, unknown> | undefined
const worktreePath = (welcomeOptions?.workspace || welcomeOptions?.worktreePath) as string | undefined
return {
streamEventType: "welcome",
worktreeBranch: welcomeOptions?.worktreeBranch as string | undefined,
worktreePath,
timestamp: (parsed.timestamp as number) || Date.now(),
}
}
Expand All @@ -249,6 +271,59 @@ function toStreamEvent(parsed: Record<string, unknown>): StreamEvent | null {
}
}

function extractJsonObjects(line: string): Record<string, unknown>[] {
const objects: Record<string, unknown>[] = []
let depth = 0
let startIndex = -1
let inString = false
let isEscaped = false

for (let i = 0; i < line.length; i++) {
const ch = line[i]

if (isEscaped) {
isEscaped = false
continue
}

if (inString) {
if (ch === "\\") {
isEscaped = true
} else if (ch === '"') {
inString = false
}
continue
}

if (ch === '"') {
inString = true
continue
}

if (ch === "{") {
if (depth === 0) {
startIndex = i
}
depth += 1
continue
}

if (ch === "}") {
depth -= 1
if (depth === 0 && startIndex !== -1) {
const candidate = line.slice(startIndex, i + 1)
const parsed = tryParseJson(candidate)
if (parsed) {
objects.push(parsed)
}
startIndex = -1
}
}
}

return objects
}

function createOutputEvent(content: string): OutputStreamEvent {
return {
streamEventType: "output",
Expand Down
Loading