Skip to content
Merged
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
28 changes: 5 additions & 23 deletions packages/opencode/src/cli/cmd/remote.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,33 +2,13 @@
import { cmd } from "./cmd"
import { bootstrap } from "../bootstrap"
import { KiloSessions } from "@/kilo-sessions/kilo-sessions"
import { buildInstanceAdvertisement } from "@/kilo-sessions/instance-advertisement"
import { context } from "@/project/instance-context"
import { InstanceRuntime } from "@/project/instance-runtime"
import { Instance } from "@/kilocode/instance"
import { InstallationVersion } from "@opencode-ai/core/installation/version"
import os from "node:os"
import path from "node:path"

function truncate(value: string, max: number) {
return value.length > max ? value.slice(0, max) : value
}

// kilocode_change start - K1 W1: extracted so the advertisement payload shape
// is unit-testable as real behavior, rather than only through a source-text/
// regex assertion on this file (the handler itself can't be driven end-to-end
// — see the doc comment on `handler` below).
export function buildInstanceAdvertisement(directory: string): {
name: string
projectName: string
version: string
} {
return {
name: truncate(os.hostname(), 64),
projectName: truncate(path.basename(directory) || directory, 64),
version: truncate(InstallationVersion, 32),
}
}
// kilocode_change end
// Re-export so existing unit tests that import from this module keep working.
export { buildInstanceAdvertisement }

export const RemoteCommand = cmd({
command: "remote",
Expand All @@ -41,6 +21,8 @@ export const RemoteCommand = cmd({
// The process-wide `KILO_REMOTE_ATTACH_SESSION` guard was removed in K1
// (in-process sessions only; no spawned children), so this is always
// advertised for the explicit `kilo remote` command path.
// enableRemote() also ensures a default advertisement; this explicit call
// remains a legitimate replace (or no-op when identical) per the contract.
KiloSessions.setInstanceAdvertisement(buildInstanceAdvertisement(Instance.directory))

await KiloSessions.enableRemote()
Expand Down
21 changes: 21 additions & 0 deletions packages/opencode/src/kilo-sessions/instance-advertisement.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// kilocode_change - new file
// Shared derivation for the spawn-capable instance advertisement payload.
// Used by both `kilo remote` (explicit CLI) and `enableRemote()` (covers `/remote`
// and KILO_REMOTE / remote_control auto-enable) so all enable paths advertise
// identically.
import { InstallationVersion } from "@opencode-ai/core/installation/version"
import os from "node:os"
import path from "node:path"
import type { RemoteProtocol } from "@/kilo-sessions/remote-protocol"

function truncate(value: string, max: number) {
return value.length > max ? value.slice(0, max) : value
}

export function buildInstanceAdvertisement(directory: string): RemoteProtocol.InstanceAdvertisement {
return {
name: truncate(os.hostname(), 64),
projectName: truncate(path.basename(directory) || directory, 64),
version: truncate(InstallationVersion, 32),
}
}
59 changes: 53 additions & 6 deletions packages/opencode/src/kilo-sessions/kilo-sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import simpleGit from "simple-git"
import { RemoteWS } from "@/kilo-sessions/remote-ws"
import { RemoteSender } from "@/kilo-sessions/remote-sender"
import { RemoteProtocol } from "@/kilo-sessions/remote-protocol"
import { buildInstanceAdvertisement } from "@/kilo-sessions/instance-advertisement"
import { AttachedState } from "@/kilo-sessions/attached-state"
import { SessionStatus } from "@/session/status"
import { Telemetry } from "@kilocode/kilo-telemetry"
Expand Down Expand Up @@ -246,7 +247,25 @@ export namespace KiloSessions {
const statusSyncs = new Map<string, { running: boolean; dirty: boolean }>()
const STATUS_TIMEOUT_MS = 3_000

async function deriveStatus(sessionID: string): Promise<"idle" | "busy" | "question" | "permission" | "retry"> {
// Shared attention/status resolution for ingest sync and the remote heartbeat.
// Precedence: permission > question > SessionStatus (offline maps to retry).
type DerivedSessionStatus = "idle" | "busy" | "question" | "permission" | "retry"

function resolveDerivedSessionStatus(input: {
hasPermission: boolean
hasQuestion: boolean
statusType: SessionStatus.Info["type"] | undefined
}): DerivedSessionStatus {
if (input.hasPermission) return "permission"
if (input.hasQuestion) return "question"
if (input.statusType === "offline") return "retry"
if (input.statusType === "busy" || input.statusType === "retry" || input.statusType === "idle") {
return input.statusType
}
return "idle"
}

async function deriveStatus(sessionID: string): Promise<DerivedSessionStatus> {
const { AppRuntime } = await import("@/effect/app-runtime")
const permissions = (await AppRuntime.runPromise(Permission.Service.use((svc) => svc.list()))).filter(
(p) => p.sessionID === sessionID,
Expand All @@ -259,8 +278,11 @@ export namespace KiloSessions {
if (questions.length > 0) return "question"

const status = await AppRuntime.runPromise(SessionStatus.Service.use((svc) => svc.get(SessionID.make(sessionID))))
if (status.type === "offline") return "retry"
return status.type
return resolveDerivedSessionStatus({
hasPermission: false,
hasQuestion: false,
statusType: status.type,
})
}

async function deriveAndSyncStatus(sessionID: string) {
Expand Down Expand Up @@ -456,9 +478,22 @@ export namespace KiloSessions {

export const node = LayerNode.suspend(() => LayerNode.make(layer, [Bus.node, Config.node, Session.node]))

// kilocode_change - DEF-1: default advertisement for every successful
// enableRemote() entry (covers `/remote` after auto-enable already connected).
// No-op when an advertisement is already set — must not re-set or fire an
// extra heartbeat. Explicit setInstanceAdvertisement keeps replace semantics.
function ensureDefaultInstanceAdvertisement() {
if (instanceAdvertisement) return
setInstanceAdvertisement(buildInstanceAdvertisement(Instance.directory))
}

export async function enableRemote() {
if (remote) return
// ingestDisabled must not advertise. Every other successful entry — including
// already-connected and coalescing early returns — must ensure advertisement
// before returning, otherwise `/remote` after auto-enable never registers.
if (ingestDisabled) return
ensureDefaultInstanceAdvertisement()
if (remote) return
if (enabling) return enabling
const seq = ++remoteSeq
void Bus.publish(Instance.current, Event.RemoteStatusChanged, { enabled: true, connected: false })
Expand Down Expand Up @@ -496,8 +531,16 @@ export namespace KiloSessions {
branch().catch(() => undefined),
])
const { AppRuntime } = await import("@/effect/app-runtime")
const statusMap = await AppRuntime.runPromise(SessionStatus.Service.use((svc) => svc.list()))
// Batch SessionStatus + attention lists once per heartbeat (not per session).
// Permission/Question list() feeds the same precedence as deriveStatus().
const [statusMap, permissions, questions] = await Promise.all([
AppRuntime.runPromise(SessionStatus.Service.use((svc) => svc.list())),
AppRuntime.runPromise(Permission.Service.use((svc) => svc.list())),
AppRuntime.runPromise(Question.Service.use((svc) => svc.list())),
])
const statuses: Record<string, SessionStatus.Info> = Object.fromEntries(statusMap)
const permissionSessions = new Set(permissions.map((p) => p.sessionID as string))
const questionSessions = new Set(questions.map((q) => q.sessionID as string))
// Advertise both presence-owned and pending-created ids so the relay learns about new
// sessions before the next periodic heartbeat and the create_session response can be sent.
const ids = new Set(Object.keys(statuses))
Expand All @@ -509,7 +552,11 @@ export namespace KiloSessions {
svc.get(SessionID.make(id)).pipe(
Effect.map((session) => ({
id,
status: statuses[id]?.type ?? ("idle" as const),
status: resolveDerivedSessionStatus({
hasPermission: permissionSessions.has(id),
hasQuestion: questionSessions.has(id),
statusType: statuses[id]?.type,
}),
title: session.title,
parentSessionId: session.parentID,
gitUrl,
Expand Down
3 changes: 2 additions & 1 deletion packages/opencode/test/kilocode/cli/cmd/remote.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@
// a source-text/regex assertion on the handler's structure.

import { describe, expect, test } from "bun:test"
import { buildInstanceAdvertisement } from "../../../../src/cli/cmd/remote"
// Shared helper lives in kilo-sessions; remote.ts re-exports for the CLI path.
import { buildInstanceAdvertisement } from "../../../../src/kilo-sessions/instance-advertisement"

describe("RemoteCommand instance advertisement (K1 W1)", () => {
test("buildInstanceAdvertisement resolves name/projectName/version from the directory and installation version", () => {
Expand Down
Loading
Loading