Skip to content
Merged
3 changes: 2 additions & 1 deletion packages/kilo-vscode/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,8 @@
"zoo code"
],
"activationEvents": [
"onStartupFinished"
"onStartupFinished",
"onUri"
],
"main": "./dist/extension.js",
"contributes": {
Expand Down
17 changes: 17 additions & 0 deletions packages/kilo-vscode/src/KiloProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -200,6 +200,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
private configWarningsShown = false
/** Cached notificationsLoaded payload */
private cachedNotificationsMessage: unknown = null
private pendingKiloModelID: string | null = null
private pendingReviewComments: { comments: unknown[]; autoSend: boolean }[] = []
private readyResolvers: (() => void)[] = []
private promptRecoveryQueued = false
Expand Down Expand Up @@ -595,6 +596,11 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
this.postMessage({ type: "openCloudSession", sessionId })
}

public selectKiloModel(modelID: string): void {
this.pendingKiloModelID = modelID
this.flushPendingKiloModel()
}

public setContinueInWorktreeHandler(
handler: (sessionId: string, progress: (status: string, detail?: string, error?: string) => void) => Promise<void>,
): void {
Expand Down Expand Up @@ -668,6 +674,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
this.isWebviewReady = true
this.visibleTaskStreams.clear()
await this.syncWebviewState("webviewReady")
this.flushPendingKiloModel()
this.flushPendingReviewComments()
this.recoverPendingPrompts()
this.readyResolvers.splice(0).forEach((r) => r())
Expand Down Expand Up @@ -1195,6 +1202,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper

// Connect the shared service (no-op if already connected)
await this.connectionService.connect(workspaceDir)
this.flushPendingKiloModel()

// Subscribe to SSE events for this webview (filtered by tracked sessions)
this.unsubscribeEvent = this.connectionService.onEventFiltered(
Expand Down Expand Up @@ -1229,6 +1237,7 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
this.postConnectionState(error)

if (state === "connected") {
this.flushPendingKiloModel()
// Fire config warnings independently so a failure in the
// sequential await chain doesn't prevent warnings from being shown
void this.checkConfigWarnings("state")
Expand Down Expand Up @@ -3189,6 +3198,14 @@ export class KiloProvider implements vscode.WebviewViewProvider, TelemetryProper
})
}

private flushPendingKiloModel(): void {
if (!this.webview || !this.isWebviewReady || !this.client || !this.pendingKiloModelID) return
Comment thread
lambertjosh marked this conversation as resolved.
Resolved

const modelID = this.pendingKiloModelID
this.pendingKiloModelID = null
this.postMessage({ type: "selectKiloModel", modelID })
}

public async appendReviewComments(comments: unknown[], autoSend = false): Promise<void> {
this.pendingReviewComments.push({ comments, autoSend })

Expand Down
29 changes: 19 additions & 10 deletions packages/kilo-vscode/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ let agentManager: AgentManagerProvider | undefined
let shuttingDown = false

const RESTORE_KEY = "kilo.workbench.restore"
const PROMOTED_KILO_MODEL_IDS = new Set(["stealth/claude-opus-4.8"])
Comment thread
lambertjosh marked this conversation as resolved.
Resolved

type RestoreState = {
sidebar?: boolean
Expand All @@ -36,9 +37,9 @@ const panelTitleHandler = (panel: vscode.WebviewPanel) => (title: string) => {
panel.title = title || EXTENSION_DISPLAY_NAME
}

// Activated via "onStartupFinished" (package.json) so that commands, code actions, keybindings,
// autocomplete, commit-message generation, and URI deep links all work immediately — without
// requiring the user to open a Kilo sidebar or panel first. The CLI backend is NOT spawned here;
// Activated via "onStartupFinished" and "onUri" (package.json) so that commands, code actions,
// keybindings, autocomplete, commit-message generation, and URI deep links all work immediately —
// without requiring the user to open a Kilo sidebar or panel first. The CLI backend is NOT spawned here;
// it starts lazily when a webview connects or when ensureBackendForAutocomplete() triggers it.
export function activate(context: vscode.ExtensionContext) {
console.log("Kilo Code extension is now active")
Expand Down Expand Up @@ -471,17 +472,25 @@ export function activate(context: vscode.ExtensionContext) {
),
)

// Register URI handler for session imports (vscode://kilocode.kilo-code/kilocode/s/{sessionId})
// Register URI handler for extension deep links (vscode://kilocode.kilo-code/kilocode/...)
context.subscriptions.push(
vscode.window.registerUriHandler({
async handleUri(uri: vscode.Uri) {
const match = uri.path.match(/^\/kilocode\/s\/([a-zA-Z0-9_-]+)$/)
if (!match) return
const sessionId = match[1]
if (!sessionId) return
console.log("[Kilo New] URI handler: opening cloud session:", sessionId)
const sessionMatch = uri.path.match(/^\/kilocode\/s\/([a-zA-Z0-9_-]+)$/)
const sessionId = sessionMatch?.[1]
if (sessionId) {
console.log("[Kilo New] URI handler: opening cloud session:", sessionId)
await vscode.commands.executeCommand(`${KiloProvider.viewType}.focus`)
provider.openCloudSession(sessionId)
return
}

if (uri.path !== "/kilocode/model") return
const modelID = new URLSearchParams(uri.query).get("model")
if (!modelID || !PROMOTED_KILO_MODEL_IDS.has(modelID)) return
console.log("[Kilo New] URI handler: selecting promoted model:", modelID)
await vscode.commands.executeCommand(`${KiloProvider.viewType}.focus`)
provider.openCloudSession(sessionId)
provider.selectKiloModel(modelID)
},
}),
)
Expand Down
32 changes: 19 additions & 13 deletions packages/kilo-vscode/src/kilo-provider/model-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,18 +41,22 @@ async function read(client: KiloClient | null): Promise<Record<string, unknown>>
}
}

function write(client: KiloClient | null, key: string, value: unknown): Promise<void> {
function update(client: KiloClient | null, key: string, updater: (value: unknown) => unknown): Promise<void> {
const op = queue.then(async () => {
const p = await resolve(client)
if (!p) return
const existing = await read(client)
existing[key] = value
existing[key] = updater(existing[key])
await fs.promises.writeFile(p, JSON.stringify(existing, null, 2))
})
queue = op.catch(() => {})
return op
}

function write(client: KiloClient | null, key: string, value: unknown): Promise<void> {
return update(client, key, () => value)
}

/**
* Handle a model-state webview message. Returns true if handled.
*/
Expand All @@ -63,20 +67,22 @@ export async function handleMessage(
post: PostMessage,
): Promise<boolean> {
if (type === "persistModelSelection") {
const data = await read(client)
const model = validateModelSelections(data.model)
model[message.agent as string] = {
providerID: message.providerID as string,
modelID: message.modelID as string,
}
await write(client, "model", model)
await update(client, "model", (value) => {
const model = validateModelSelections(value)
model[message.agent as string] = {
providerID: message.providerID as string,
modelID: message.modelID as string,
}
return model
})
return true
}
if (type === "clearModelSelection") {
const data = await read(client)
const model = validateModelSelections(data.model)
delete model[message.agent as string]
await write(client, "model", model)
await update(client, "model", (value) => {
const model = validateModelSelections(value)
delete model[message.agent as string]
return model
})
return true
}
if (type === "requestModelSelections") {
Expand Down
16 changes: 16 additions & 0 deletions packages/kilo-vscode/webview-ui/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { Diff } from "@kilocode/kilo-ui/diff"
import { File } from "@kilocode/kilo-ui/file"
import { DataProvider } from "@kilocode/kilo-ui/context/data"
import { Toast } from "@kilocode/kilo-ui/toast"
import { KILO_PROVIDER_ID } from "../../src/shared/provider-model"
import Settings from "./components/settings/Settings"
import ProfileView from "./components/profile/ProfileView"
import { VSCodeProvider, useVSCode } from "./context/vscode"
Expand All @@ -36,11 +37,18 @@ import { NotificationsProvider } from "./context/notifications"
import { FeedbackProvider } from "./context/feedback"
import { KiloEmbeddingModelsProvider } from "./context/kilo-embedding-models"
import type { Message as SDKMessage, Part as SDKPart } from "@kilocode/sdk/v2"
import type { SelectKiloModelMessage } from "./types/messages"
import "./styles/chat.css"

type ViewType = "newTask" | "marketplace" | "history" | "profile" | "settings" | "subAgentViewer"
const VALID_VIEWS = new Set<string>(["newTask", "marketplace", "history", "profile", "settings", "subAgentViewer"])

function isSelectKiloModelMessage(message: unknown): message is SelectKiloModelMessage {
if (!message || typeof message !== "object") return false
if (!("type" in message) || !("modelID" in message)) return false
return message.type === "selectKiloModel" && typeof message.modelID === "string"
}

/**
* Bridge our session store to the DataProvider's expected Data shape.
*
Expand Down Expand Up @@ -261,6 +269,13 @@ const AppContent: Component = () => {
setCurrentView("newTask")
}

const handleSelectKiloModel = (message: unknown) => {
if (!isSelectKiloModelMessage(message)) return
console.log("[Kilo New] App: selecting promoted Kilo model:", message.modelID)
session.selectPersistedModel(KILO_PROVIDER_ID, message.modelID)
setCurrentView("newTask")
}

onMount(() => {
const handler = (event: MessageEvent) => {
const message = event.data
Expand All @@ -279,6 +294,7 @@ const AppContent: Component = () => {
session.selectCloudSession(message.sessionId)
setCurrentView("newTask")
}
handleSelectKiloModel(message)
handleForked(message)
if (message?.type === "viewSubAgentSession" && message.sessionID) {
console.log("[Kilo New] App: 🔍 viewSubAgentSession:", message.sessionID)
Expand Down
54 changes: 45 additions & 9 deletions packages/kilo-vscode/webview-ui/src/context/session.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,7 @@ interface SessionContextValue {
// Model selection (global, extension-lifetime)
selected: (sessionID?: string) => ModelSelection | null
selectModel: (providerID: string, modelID: string, sessionID?: string) => void
selectPersistedModel: (providerID: string, modelID: string) => void
hasModelOverride: (sessionID?: string) => boolean
clearModelOverride: (sessionID?: string) => void

Expand Down Expand Up @@ -345,6 +346,7 @@ export const SessionProvider: ParentComponent = (props) => {
const [agents, setAgents] = createSignal<AgentInfo[]>([])
const [allAgents, setAllAgents] = createSignal<AgentInfo[]>([])
const [defaultAgent, setDefaultAgent] = createSignal("code")
const [pendingPersistedModel, setPendingPersistedModel] = createSignal<ModelSelection | null>(null)

// Skills loaded from the CLI backend
const [skills, setSkills] = createSignal<SkillInfo[]>([])
Expand Down Expand Up @@ -506,17 +508,9 @@ export const SessionProvider: ParentComponent = (props) => {
vscode.postMessage({ type: "persistRecents", recents: updated })
}

function applyModel(agentName: string, selection: ModelSelection, sessionID?: string) {
pushRecent(selection)
if (sessionID) {
setStore("sessionOverrides", sessionID, selection)
return
}
// Always remember the per-mode model choice so switching modes restores
// the last-used model (mirrors CLI TUI's model.json behavior).
function persistModelSelection(agentName: string, selection: ModelSelection) {
setUserSetAgents((prev) => ({ ...prev, [agentName]: true }))
setStore("modelSelections", agentName, selection)
// Persist to model.json via the extension host
vscode.postMessage({
type: "persistModelSelection",
agent: agentName,
Expand All @@ -525,6 +519,17 @@ export const SessionProvider: ParentComponent = (props) => {
})
}

function applyModel(agentName: string, selection: ModelSelection, sessionID?: string) {
pushRecent(selection)
if (sessionID) {
setStore("sessionOverrides", sessionID, selection)
return
}
// Always remember the per-mode model choice so switching modes restores
// the last-used model (mirrors CLI TUI's model.json behavior).
persistModelSelection(agentName, selection)
}

function selectModel(providerID: string, modelID: string, sessionID?: string) {
const sid = sessionID ?? currentSessionID()
applyModel(agentForScope(sid), { providerID, modelID }, sid)
Expand All @@ -533,6 +538,30 @@ export const SessionProvider: ParentComponent = (props) => {
}
}

function applyPersistedModel(selection: ModelSelection) {
const sid = currentSessionID()
const defaultAgentName = defaultAgent()
const activeAgentName = agentForScope()
pushRecent(selection)
persistModelSelection(defaultAgentName, selection)
if (activeAgentName !== defaultAgentName) {
persistModelSelection(activeAgentName, selection)
}
if (sid) {
setStore("sessionOverrides", sid, selection)
hideErrors(sid)
}
}

function selectPersistedModel(providerID: string, modelID: string) {
const selection = { providerID, modelID }
if (agents().length === 0) {
setPendingPersistedModel(selection)
return
}
applyPersistedModel(selection)
}

function promptAgent(sessionID?: string) {
const name = agentForScope(sessionID)
return name !== defaultAgent() ? name : undefined
Expand Down Expand Up @@ -637,6 +666,12 @@ export const SessionProvider: ParentComponent = (props) => {
}),
)

const pendingModel = pendingPersistedModel()
if (pendingModel) {
setPendingPersistedModel(null)
applyPersistedModel(pendingModel)
}

// Rescan already-loaded message history so sessions whose messagesLoaded
// arrived before agentsLoaded (and therefore got no agent selection) are
// backfilled now that we know the valid agent names.
Expand Down Expand Up @@ -2478,6 +2513,7 @@ export const SessionProvider: ParentComponent = (props) => {
scopedSuggestions,
selected,
selectModel,
selectPersistedModel,
hasModelOverride,
clearModelOverride,
costBreakdown,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,11 @@ export interface OpenCloudSessionMessage {
sessionId: string
}

export interface SelectKiloModelMessage {
type: "selectKiloModel"
modelID: string
}

export interface ActionMessage {
type: "action"
action: string
Expand Down Expand Up @@ -1011,6 +1016,7 @@ export type ExtensionMessage =
| CloudSessionImportedMessage
| CloudSessionImportFailedMessage
| OpenCloudSessionMessage
| SelectKiloModelMessage
| AgentManagerBranchesMessage
| AgentManagerExternalWorktreesMessage
| AgentManagerImportResultMessage
Expand Down
Loading