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
5 changes: 5 additions & 0 deletions .changeset/meta-launch-directory-no-context-fallback.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"kilo-code": patch
---

Fix a crash when session repository metadata is resolved without an instance context (e.g. the API fallback path): it now degrades to no git metadata instead of throwing.
5 changes: 5 additions & 0 deletions .changeset/remote-session-metadata-from-session-directory.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"kilo-code": patch
---

Remote sessions started outside the selected repository now show the correct repository name and branch in the sessions list.
91 changes: 75 additions & 16 deletions packages/opencode/src/kilo-sessions/kilo-sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import { Config } from "@/config/config"
import { InstanceState } from "@/effect/instance-state"
import { Instance } from "@/kilocode/instance"
import { Vcs } from "@/project/vcs"
import { Git } from "@/git"
import simpleGit from "simple-git"
import { RemoteWS } from "@/kilo-sessions/remote-ws"
import { RemoteSender } from "@/kilo-sessions/remote-sender"
Expand Down Expand Up @@ -94,6 +95,7 @@ export namespace KiloSessions {
const orgKey = "kilo-sessions:org"
const clientKey = "kilo-sessions:client"
const gitUrlKeyPrefix = "kilo-sessions:git-url:"
const gitBranchKeyPrefix = "kilo-sessions:git-branch:"

const ttlMs = 10_000

Expand Down Expand Up @@ -128,7 +130,12 @@ export namespace KiloSessions {
clearInFlightCache(tokenValidKey)
clearInFlightCache(clientKey)
clearInFlightCache(orgKey)
// The git-url and per-directory branch caches are keyed per directory
// (`<prefix><directory>`); only the launch-directory entry is cleared here.
// Entries for other session directories expire via ttlMs (10 s) — there is
// intentionally no prefix-clear API.
clearInFlightCache(gitUrlKeyPrefix + Instance.worktree)
clearInFlightCache(gitBranchKeyPrefix + Instance.worktree)
}

async function authValid(token: string) {
Expand Down Expand Up @@ -795,10 +802,10 @@ export namespace KiloSessions {
// moment of sending. The flag may be set after this closure is created
// (race-proof) — `getSessions` reads the current value each tick.
const getSessions = async (): Promise<RemoteProtocol.Heartbeat> => {
const [gitUrl, gitBranch] = await Promise.all([
getGitUrl().catch(() => undefined),
branch().catch(() => undefined),
])
// The instance advertisement describes the host process's own project,
// so it keeps the launch-directory (Vcs) branch. Session rows derive
// their repository metadata from each session's own directory below.
const gitBranch = await branch().catch(() => undefined)
const { AppRuntime } = await import("@/effect/app-runtime")
// Batch SessionStatus + attention lists once per heartbeat (not per session).
// Permission/Question list() feeds the same precedence as deriveStatus().
Expand All @@ -819,17 +826,16 @@ export namespace KiloSessions {
Effect.all(
[...ids].map((id) =>
svc.get(SessionID.make(id)).pipe(
Effect.map((session) => ({
id,
status: resolveDerivedSessionStatus({
Effect.map((session) => ({
id,
directory: session.directory,
status: resolveDerivedSessionStatus({
hasPermission: permissionSessions.has(id),
hasQuestion: questionSessions.has(id),
statusType: statuses[id]?.type,
}),
title: session.title,
parentSessionId: session.parentID,
gitUrl,
gitBranch,
// kilocode_change - K1 W1: per-session platform, mirrors
// meta()'s resolution order so the live value always agrees
// with the session's stored created_on_platform.
Expand All @@ -841,7 +847,29 @@ export namespace KiloSessions {
),
),
)
const sessions = results.filter((r): r is NonNullable<typeof r> => !!r)
// Resolve repository metadata per distinct session directory: a host
// launched outside the selected repository must still publish each
// session's own repo. Directory-less sessions fall back to the launch
// worktree, and the in-flight cache collapses same-directory sessions
// into one git call per ttlMs.
const gitPairs = new Map<string, { gitUrl?: string; gitBranch?: string }>()
await Promise.all(
[...new Set(results.map((r) => r?.directory ?? Instance.worktree))].map(async (directory) => {
const [gitUrl, sessionGitBranch] = await Promise.all([
getGitUrl(directory).catch(() => undefined),
branchFor(directory).catch(() => undefined),
])
gitPairs.set(directory, { gitUrl, gitBranch: sessionGitBranch })
}),
)
const sessions = results.filter((r): r is NonNullable<typeof r> => !!r).map((r) => ({
id: r.id,
status: r.status,
title: r.title,
parentSessionId: r.parentSessionId,
...gitPairs.get(r.directory ?? Instance.worktree),
platform: r.platform,
}))
// kilocode_change - PR link advertise (plan 8.2): resolve once
// (worktree-scoped) and attach to every advertised row, then ingest the
// triple per session (deduped by last-sent triple).
Expand All @@ -852,7 +880,7 @@ export namespace KiloSessions {
const advertised = pr.prLink ? sessions.map((row) => ({ ...row, prLink: pr.prLink })) : sessions
const instance = instanceAdvertisement && {
...instanceAdvertisement,
// Reuse the current session branch without splitting a surrogate pair.
// Truncate the launch-directory branch without splitting a surrogate pair.
gitBranch: gitBranch?.slice(0, 24).replace(/[\uD800-\uDBFF]$/, ""),
}
return { type: "heartbeat", sessions: advertised, ...(instance ? { instance } : {}) }
Expand Down Expand Up @@ -1466,9 +1494,9 @@ export namespace KiloSessions {
}
}

async function getGitUrl(): Promise<string | undefined> {
return withInFlightCache(gitUrlKeyPrefix + Instance.worktree, ttlMs, async () => {
const repo = simpleGit(Instance.worktree)
async function getGitUrl(directory: string): Promise<string | undefined> {
return withInFlightCache(gitUrlKeyPrefix + directory, ttlMs, async () => {
const repo = simpleGit(directory)
const remotes = await repo.getRemotes(true).catch(() => [])
if (remotes.length === 0) return undefined

Expand All @@ -1488,17 +1516,48 @@ export namespace KiloSessions {
})
}

// Context-scoped branch for the instance advertisement: the ad describes the
// host process's own project, so it keeps the launch-directory Vcs branch.
async function branch() {
const { AppRuntime } = await import("@/effect/app-runtime")
return AppRuntime.runPromise(Vcs.Service.use((svc) => svc.branch()))
}

// Per-directory branch for session rows and persisted kilo_meta: a session
// created in a nested repository must report that repository's branch, not
// the host's launch directory. `Git.branch` returns undefined for
// non-repositories, which collapses to "no branch metadata".
async function branchFor(directory: string) {
const { AppRuntime } = await import("@/effect/app-runtime")
return withInFlightCache(gitBranchKeyPrefix + directory, ttlMs, () =>
AppRuntime.runPromise(Git.Service.use((svc) => svc.branch(directory))),
)
}

// Non-throwing launch-directory read for `meta()`: when called outside any
// instance context (e.g. the API-robustness path where Session.get already
// failed), `Instance.worktree` throws synchronously — before, the only access
// sat inside an async closure so it degraded to "git metadata absent".
// Degrade the same way instead of throwing.
function launchDirectory(): string | undefined {
try {
return Instance.worktree
} catch {
return undefined
}
}

async function meta(sessionId?: string, info?: Session.Info | null) {
const override = sessionId ? KiloSession.resolvePlatform(sessionId) : undefined
const platform = override || process.env["KILO_PLATFORM"] || "cli"
const orgId = await getOrgId(sessionId, info)
const gitBranch = await branch().catch(() => undefined)
const gitUrl = await getGitUrl().catch(() => undefined)
// Repository metadata follows the session's own directory (a `kilo remote`
// host launched outside the selected repository must still publish the
// session's repo); directory-less sessions fall back to the launch worktree
// when an instance context exists, else to "no git metadata".
const directory = info?.directory ?? launchDirectory()
const gitBranch = directory ? await branchFor(directory).catch(() => undefined) : undefined
const gitUrl = directory ? await getGitUrl(directory).catch(() => undefined) : undefined

return {
platform,
Expand Down
38 changes: 38 additions & 0 deletions packages/opencode/test/kilocode/chmod-injection-contract.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// kilocode_change - new file
/**
* Contract test for chmod(0o000) failure injections in kilo-sessions.test.ts.
*
* The heartbeat self-heal test breaks git with `chmod 0o000 .git` and asserts
* the repository metadata disappears. On Windows chmod(0o000) is a no-op for
* reads, and root ignores permission bits, so the injection cannot break git
* there and the assertions spuriously fail. The file runs on Windows because
* .github/workflows/test.yml schedules six windows shards that run the
* packages/opencode unit tests with no exclusion. Every injection must skip
* win32 and root first — the pattern in test/util/filesystem.test.ts
* ("throws EACCES on permission-denied symlink target"). This test catches a
* guard that was removed or copied without.
*/

import { describe, expect, test } from "bun:test"
import { readFileSync } from "node:fs"
import path from "node:path"

const TARGET = path.resolve(import.meta.dir, "kilo-sessions.test.ts")

describe("chmod(0o000) failure injections in kilo-sessions.test.ts", () => {
test("the self-heal injection exists and is guarded against win32 and root", () => {
const content = readFileSync(TARGET, "utf-8")
const injections = [...content.matchAll(/\.chmod\([^)]*0o000\)/g)]
// The e5 self-heal scenario must stay covered; dropping it is a contract
// break too, so fail loudly instead of passing vacuously.
expect(injections.length).toBeGreaterThan(0)
for (const injection of injections) {
// The enclosing test callback starts at the nearest preceding `test(`.
const testStart = content.lastIndexOf("\n test(", injection.index)
expect(testStart).toBeGreaterThan(-1)
const header = content.slice(testStart, injection.index)
expect(header).toContain('if (process.platform === "win32") return')
expect(header).toContain("if (process.getuid?.() === 0) return")
}
})
})
Loading
Loading