From be7dc4d0ac3a934bd0b8225d9a1910341b1c1a3c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Igor=20=C5=A0=C4=87eki=C4=87?= Date: Sat, 25 Jul 2026 13:15:02 +0200 Subject: [PATCH 1/3] fix(cli): advertise the instance from enableRemote so /remote registers as a spawn target Enabling the remote relay from the TUI `/remote` slash command connected the socket and mirrored sessions, but never advertised the instance, so the CLI never appeared as a spawn target in the mobile "Run on" picker. Only the explicit `kilo remote` command called setInstanceAdvertisement. The advertisement now runs on every successful enableRemote() entry, before the already-connected and coalescing early returns. That ordering matters: bootstrap auto-enable frequently connects first, so `/remote` usually hits `if (remote) return` and an advertisement placed in the connection-setup body would leave the defect unfixed in the common case. `ingestDisabled` returns before the advertisement and stays unadvertised. The ensure helper is a no-op when an advertisement is already set, so it fires no extra heartbeat, while explicit setInstanceAdvertisement keeps its existing replace semantics. buildInstanceAdvertisement moves to a shared module so the command path and the enable path derive it identically. --- packages/opencode/src/cli/cmd/remote.ts | 28 +----- .../kilo-sessions/instance-advertisement.ts | 21 +++++ .../src/kilo-sessions/kilo-sessions.ts | 16 +++- .../test/kilocode/cli/cmd/remote.test.ts | 3 +- .../test/kilocode/kilo-sessions.test.ts | 94 +++++++++++++++---- 5 files changed, 117 insertions(+), 45 deletions(-) create mode 100644 packages/opencode/src/kilo-sessions/instance-advertisement.ts diff --git a/packages/opencode/src/cli/cmd/remote.ts b/packages/opencode/src/cli/cmd/remote.ts index 3e33f002dd3f..1cc7ed520b8d 100644 --- a/packages/opencode/src/cli/cmd/remote.ts +++ b/packages/opencode/src/cli/cmd/remote.ts @@ -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", @@ -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() diff --git a/packages/opencode/src/kilo-sessions/instance-advertisement.ts b/packages/opencode/src/kilo-sessions/instance-advertisement.ts new file mode 100644 index 000000000000..97c5ffb6e890 --- /dev/null +++ b/packages/opencode/src/kilo-sessions/instance-advertisement.ts @@ -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), + } +} diff --git a/packages/opencode/src/kilo-sessions/kilo-sessions.ts b/packages/opencode/src/kilo-sessions/kilo-sessions.ts index e9deaeb575c0..4b1dce893761 100644 --- a/packages/opencode/src/kilo-sessions/kilo-sessions.ts +++ b/packages/opencode/src/kilo-sessions/kilo-sessions.ts @@ -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" @@ -456,9 +457,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 }) diff --git a/packages/opencode/test/kilocode/cli/cmd/remote.test.ts b/packages/opencode/test/kilocode/cli/cmd/remote.test.ts index abeb24b02cf1..e571148694a0 100644 --- a/packages/opencode/test/kilocode/cli/cmd/remote.test.ts +++ b/packages/opencode/test/kilocode/cli/cmd/remote.test.ts @@ -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", () => { diff --git a/packages/opencode/test/kilocode/kilo-sessions.test.ts b/packages/opencode/test/kilocode/kilo-sessions.test.ts index 78f26bf75d52..f3916504785e 100644 --- a/packages/opencode/test/kilocode/kilo-sessions.test.ts +++ b/packages/opencode/test/kilocode/kilo-sessions.test.ts @@ -276,18 +276,17 @@ multi.live("isolates the process-wide listener by instance directory", () => { ) }) -// kilocode_change start - K1 W1: instance advertisement + per-session platform. +// kilocode_change start - K1 W1 / DEF-1: instance advertisement + per-session platform. // -// The race is the heart of this slice: `enableRemote` is idempotent/coalescing -// and can be called from either the explicit `kilo remote` command OR from -// bootstrap auto-enable (`KILO_REMOTE=1` / `remote_control` config). The -// module-level `instanceAdvertisement` flag must make the next heartbeat -// carry `instance` regardless of which caller won the race, and the setter -// must trigger an out-of-band heartbeat when called against an existing -// connection (so the cloud learns about the instance without waiting for -// the next 10s timer tick). - -describe("KiloSessions.setInstanceAdvertisement (K1 W1)", () => { +// `enableRemote` is idempotent/coalescing and is called from `/remote`, the +// explicit `kilo remote` command, and bootstrap auto-enable (`KILO_REMOTE=1` / +// `remote_control`). Every successful entry must ensure a default instance +// advertisement (including the already-connected early return — the common +// `/remote`-after-auto-enable path). Explicit `setInstanceAdvertisement` +// keeps replace semantics and fires one out-of-band heartbeat per set when +// connected; `enableRemote` with an ad already set is a no-op (no extra HB). + +describe("KiloSessions.setInstanceAdvertisement (K1 W1 / DEF-1)", () => { let heartbeatCalls = 0 let outOfBand: Promise | undefined @@ -375,27 +374,51 @@ describe("KiloSessions.setInstanceAdvertisement (K1 W1)", () => { return getSessions as () => Promise } - test("flag is unset by default — heartbeats omit `instance`", async () => { + test("enableRemote alone advertises the instance (covers /remote and auto-enable)", async () => { await using tmp = await tmpdir({ git: true }) await provide({ directory: tmp.path, fn: async () => { + // Contract: enableRemote entry with none set → derive and set. + // No prior setInstanceAdvertisement (simulates /remote or auto-enable). await KiloSessions.enableRemote() const payload = await capturedGetSessions()() expect(payload.type).toBe("heartbeat") - expect(payload.instance).toBeUndefined() + expect(payload.instance).toBeDefined() + expect(payload.instance!.projectName.length).toBeGreaterThan(0) + expect(payload.instance!.name.length).toBeGreaterThan(0) }, }) }) - test("setting the flag makes the next getSessions include `instance` (race: setter after enable)", async () => { + test("enableRemote after already connected is a no-op for advertisement (no extra heartbeat)", async () => { await using tmp = await tmpdir({ git: true }) await provide({ directory: tmp.path, fn: async () => { + // Auto-enable connects first and advertises. await KiloSessions.enableRemote() - // Race: the explicit `kilo remote` command now sets the flag, after - // `enableRemote` already coalesced with bootstrap auto-enable. + const first = await capturedGetSessions()() + expect(first.instance).toBeDefined() + const before = heartbeatCalls + // /remote calls enableRemote again; already-connected early return must + // not re-set or fire an extra out-of-band heartbeat. + await KiloSessions.enableRemote() + expect(heartbeatCalls).toBe(before) + const second = await capturedGetSessions()() + expect(second.instance).toEqual(first.instance) + }, + }) + }) + + test("explicit set after enable replaces the payload (kilo remote race)", async () => { + await using tmp = await tmpdir({ git: true }) + await provide({ + directory: tmp.path, + fn: async () => { + await KiloSessions.enableRemote() + // Explicit set keeps replace semantics even when enableRemote already + // derived a default advertisement. KiloSessions.setInstanceAdvertisement({ name: "mbp-igor", projectName: "cloud", @@ -414,11 +437,10 @@ describe("KiloSessions.setInstanceAdvertisement (K1 W1)", () => { directory: tmp.path, fn: async () => { await KiloSessions.enableRemote() - const beforePayload = await capturedGetSessions()() - expect(beforePayload.instance).toBeUndefined() + // enableRemote already set a default ad; explicit set replaces and fires + // exactly one out-of-band heartbeat. const beforeHeartbeatCalls = heartbeatCalls KiloSessions.setInstanceAdvertisement({ name: "h", projectName: "p" }) - // The setter fires one out-of-band heartbeat — wait for it. await outOfBand expect(heartbeatCalls).toBe(beforeHeartbeatCalls + 1) const afterPayload = await capturedGetSessions()() @@ -427,7 +449,7 @@ describe("KiloSessions.setInstanceAdvertisement (K1 W1)", () => { }) }) - test("setter is idempotent — second call replaces the payload and still fires one out-of-band heartbeat", async () => { + test("setter replaces payload and fires one out-of-band heartbeat per call", async () => { await using tmp = await tmpdir({ git: true }) await provide({ directory: tmp.path, @@ -445,6 +467,38 @@ describe("KiloSessions.setInstanceAdvertisement (K1 W1)", () => { }) }) + test("explicit set before enableRemote is preserved (no re-set on enable)", async () => { + await using tmp = await tmpdir({ git: true }) + await provide({ + directory: tmp.path, + fn: async () => { + // Contract: set before connect → flag stored; enable must not replace. + KiloSessions.setInstanceAdvertisement({ name: "pre-set", projectName: "proj", version: "9.9.9" }) + await KiloSessions.enableRemote() + const payload = await capturedGetSessions()() + expect(payload.instance).toEqual({ name: "pre-set", projectName: "proj", version: "9.9.9" }) + }, + }) + }) + + test("disableRemote does not clear the advertisement flag", async () => { + await using tmp = await tmpdir({ git: true }) + await provide({ + directory: tmp.path, + fn: async () => { + await KiloSessions.enableRemote() + const before = await capturedGetSessions()() + expect(before.instance).toBeDefined() + KiloSessions.disableRemote() + // Re-enable: ensureDefault must no-op (flag still set), and the new + // connection's getSessions must still carry the same advertisement. + await KiloSessions.enableRemote() + const after = await capturedGetSessions()() + expect(after.instance).toEqual(before.instance) + }, + }) + }) + test("per-session platform resolution matches meta() order — env var fallback", async () => { // The getSessions closure's platform field is computed as: // KiloSession.resolvePlatform(id) || process.env["KILO_PLATFORM"] || "cli" From 3159b2456c4bcfc57cf73b0d4128cda29298bdc3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Igor=20=C5=A0=C4=87eki=C4=87?= Date: Sat, 25 Jul 2026 13:30:56 +0200 Subject: [PATCH 2/3] fix(cli): report pending question and permission on the session heartbeat MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The heartbeat built each session's status from SessionStatus.Service, whose union is idle/retry/busy/offline and which never consults Question.Service or Permission.Service. deriveStatus() already did consult both, but only fed the ingest session_status sync. So a session genuinely blocked on a question was advertised as busy on the heartbeat, and the mobile app — which takes live row status from the heartbeat — showed no needs-input badge. Extract the precedence (permission, then question, then SessionStatus) into a shared helper used by both deriveStatus and the heartbeat, so the two channels cannot drift. The heartbeat runs on a ~10s timer across every session, and deriveStatus makes service calls per session, so the permission and question lists are fetched once per tick and indexed by session id rather than queried per session. A test pins the call count. Behaviour note beyond the strict fix: sharing the derivation also means a SessionStatus of offline now reports as retry on the wire, matching what deriveStatus has always sent to ingest. Nothing consumes offline from the heartbeat — the transport forwards only idle and busy, and the mobile row treats both as non-attention — so the effect is that the two channels now agree. The detach fence test is parameterised accordingly; its assertion that the status clears on detach is unchanged. --- .../src/kilo-sessions/kilo-sessions.ts | 43 ++- .../test/kilocode/kilo-sessions.test.ts | 314 +++++++++++++++++- 2 files changed, 349 insertions(+), 8 deletions(-) diff --git a/packages/opencode/src/kilo-sessions/kilo-sessions.ts b/packages/opencode/src/kilo-sessions/kilo-sessions.ts index 4b1dce893761..debcc69b0a34 100644 --- a/packages/opencode/src/kilo-sessions/kilo-sessions.ts +++ b/packages/opencode/src/kilo-sessions/kilo-sessions.ts @@ -247,7 +247,25 @@ export namespace KiloSessions { const statusSyncs = new Map() 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 { const { AppRuntime } = await import("@/effect/app-runtime") const permissions = (await AppRuntime.runPromise(Permission.Service.use((svc) => svc.list()))).filter( (p) => p.sessionID === sessionID, @@ -260,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) { @@ -510,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 = 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)) @@ -523,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, diff --git a/packages/opencode/test/kilocode/kilo-sessions.test.ts b/packages/opencode/test/kilocode/kilo-sessions.test.ts index f3916504785e..b18c95f2a9b1 100644 --- a/packages/opencode/test/kilocode/kilo-sessions.test.ts +++ b/packages/opencode/test/kilocode/kilo-sessions.test.ts @@ -631,19 +631,22 @@ describe("KiloSessions.detachRemoteSession heartbeat fence (K1 W1)", () => { return chat.id } - for (const { label, status } of [ - { label: "busy", status: { type: "busy" as const } }, + for (const { label, status, heartbeatStatus } of [ + { label: "busy", status: { type: "busy" as const }, heartbeatStatus: "busy" }, { label: "retry", status: { type: "retry" as const, attempt: 1, message: "retrying", next: 100 }, + heartbeatStatus: "retry", }, { + // SessionStatus.offline maps to heartbeat "retry" (same as deriveStatus). label: "offline", status: { type: "offline" as const, requestID: QuestionID.ascending(), message: "waiting for user", }, + heartbeatStatus: "retry", }, ]) { test(`clears ${label} SessionStatus so the detach heartbeat fence resolves`, async () => { @@ -661,7 +664,7 @@ describe("KiloSessions.detachRemoteSession heartbeat fence (K1 W1)", () => { const getSessions = capturedGetSessions() const before = await getSessions() - expect(before.sessions.some((s) => s.id === id && s.status === label)).toBe(true) + expect(before.sessions.some((s) => s.id === id && s.status === heartbeatStatus)).toBe(true) await KiloSessions.detachRemoteSession(id) @@ -675,3 +678,308 @@ describe("KiloSessions.detachRemoteSession heartbeat fence (K1 W1)", () => { }, 30000) } }) + +// DEF-3 part 1: heartbeat per-session status must reflect pending +// question/permission (same precedence as deriveStatus), with Permission and +// Question list() called once per heartbeat — not once per session. +describe("KiloSessions heartbeat attention status (DEF-3)", () => { + beforeEach(() => { + process.env["KILO_DISABLE_SESSION_INGEST"] = "0" + delete process.env["KILO_SESSION_INGEST_URL"] + process.env["KILO_API_KEY"] = "tok" + reset("tok") + KiloSessions.resetInstanceAdvertisementForTests() + + spyOn(RemoteSender, "create").mockImplementation( + () => + ({ + handle() {}, + dispose() {}, + }) as RemoteSender.Sender, + ) + spyOn(RemoteWS, "connect").mockImplementation( + (options) => + ({ + connectionId: "test-conn", + send() {}, + heartbeat: () => options.getSessions().then(() => undefined), + close() {}, + get connected() { + return true + }, + }) as RemoteWS.Connection, + ) + + clearInFlightCache("kilo-sessions:token") + clearInFlightCache("kilo-sessions:token-valid:tok") + + globalThis.fetch = mock(async (input) => { + const url = String(input) + if (url.endsWith("/api/user")) { + return new Response(null, { status: 200 }) + } + if (url.endsWith("/api/session")) { + return Response.json({ id: "remote-test", ingestPath: "/api/ingest/test" }) + } + throw new Error(`unexpected fetch in test: ${url}`) + }) as unknown as typeof fetch + }) + + afterEach(async () => { + const pub = spyOn(Bus, "publish").mockResolvedValue(undefined as never) + await using tmp = await tmpdir({ git: true }) + await provide({ + directory: tmp.path, + fn: async () => { + KiloSessions.disableRemote() + }, + }) + pub.mockRestore() + mock.restore() + delete process.env["KILO_DISABLE_SESSION_INGEST"] + delete process.env["KILO_SESSION_INGEST_URL"] + delete process.env["KILO_PLATFORM"] + delete process.env["KILO_API_KEY"] + reset("tok") + }) + + function capturedGetSessions(): () => Promise { + const calls = (RemoteWS.connect as unknown as { mock: { calls: { 0: RemoteWS.Options }[] } }).mock.calls + const getSessions = calls[0]?.[0].getSessions + if (!getSessions) throw new Error("RemoteWS.connect was not called") + return getSessions as () => Promise + } + + async function setupSession() { + const { AppRuntime } = await import("@/effect/app-runtime") + const { Session } = await import("@/session/session") + const chat = await AppRuntime.runPromise(Session.Service.use((svc) => svc.create({}))) + return chat.id + } + + const questionPrompt = [ + { + header: "Continue?", + question: "Should I continue?", + options: [ + { label: "Yes", description: "Go" }, + { label: "No", description: "Stop" }, + ], + }, + ] + + async function waitForPermission(sessionID: string) { + const { AppRuntime } = await import("@/effect/app-runtime") + const { Permission } = await import("@/permission") + for (let i = 0; i < 50; i++) { + const pending = await AppRuntime.runPromise(Permission.Service.use((svc) => svc.list())) + if (pending.some((p) => p.sessionID === sessionID)) return + await new Promise((r) => setTimeout(r, 10)) + } + throw new Error(`timed out waiting for permission on ${sessionID}`) + } + + async function waitForQuestion(sessionID: string) { + const { AppRuntime } = await import("@/effect/app-runtime") + const { Question } = await import("@/question") + for (let i = 0; i < 50; i++) { + const pending = await AppRuntime.runPromise(Question.Service.use((svc) => svc.list())) + if (pending.some((q) => q.sessionID === sessionID)) return + await new Promise((r) => setTimeout(r, 10)) + } + throw new Error(`timed out waiting for question on ${sessionID}`) + } + + test("reports permission when a permission request is pending", async () => { + await using tmp = await tmpdir({ git: true }) + await provide({ + directory: tmp.path, + fn: async () => { + await KiloSessions.enableRemote() + const id = await setupSession() + await KiloSessions.attachRemoteSession(id) + + const { AppRuntime } = await import("@/effect/app-runtime") + const { Permission } = await import("@/permission") + const { PermissionV1 } = await import("@opencode-ai/core/v1/permission") + const requestID = PermissionV1.ID.make("permission_hb_perm") + + AppRuntime.runFork( + Permission.Service.use((svc) => + svc.ask({ + id: requestID, + sessionID: id, + permission: "bash", + patterns: ["ls"], + metadata: {}, + always: [], + ruleset: [], + }), + ), + ) + await waitForPermission(id) + + const payload = await capturedGetSessions()() + expect(payload.sessions.some((s) => s.id === id && s.status === "permission")).toBe(true) + + await AppRuntime.runPromise(Permission.Service.use((svc) => svc.reply({ requestID, reply: "once" }))) + }, + }) + }, 30000) + + test("reports question when a structured question is pending", async () => { + await using tmp = await tmpdir({ git: true }) + await provide({ + directory: tmp.path, + fn: async () => { + await KiloSessions.enableRemote() + const id = await setupSession() + await KiloSessions.attachRemoteSession(id) + + const { AppRuntime } = await import("@/effect/app-runtime") + const { Question } = await import("@/question") + + AppRuntime.runFork(Question.Service.use((svc) => svc.ask({ sessionID: id, questions: questionPrompt }))) + await waitForQuestion(id) + + const payload = await capturedGetSessions()() + expect(payload.sessions.some((s) => s.id === id && s.status === "question")).toBe(true) + + const pending = await AppRuntime.runPromise(Question.Service.use((svc) => svc.list())) + const req = pending.find((q) => q.sessionID === id) + expect(req).toBeDefined() + await AppRuntime.runPromise(Question.Service.use((svc) => svc.reject(req!.id))) + }, + }) + }, 30000) + + test("permission takes precedence over question", async () => { + await using tmp = await tmpdir({ git: true }) + await provide({ + directory: tmp.path, + fn: async () => { + await KiloSessions.enableRemote() + const id = await setupSession() + await KiloSessions.attachRemoteSession(id) + + const { AppRuntime } = await import("@/effect/app-runtime") + const { Permission } = await import("@/permission") + const { Question } = await import("@/question") + const { PermissionV1 } = await import("@opencode-ai/core/v1/permission") + const requestID = PermissionV1.ID.make("permission_hb_both") + + AppRuntime.runFork(Question.Service.use((svc) => svc.ask({ sessionID: id, questions: questionPrompt }))) + AppRuntime.runFork( + Permission.Service.use((svc) => + svc.ask({ + id: requestID, + sessionID: id, + permission: "bash", + patterns: ["ls"], + metadata: {}, + always: [], + ruleset: [], + }), + ), + ) + await waitForPermission(id) + await waitForQuestion(id) + + const payload = await capturedGetSessions()() + expect(payload.sessions.some((s) => s.id === id && s.status === "permission")).toBe(true) + + await AppRuntime.runPromise(Permission.Service.use((svc) => svc.reply({ requestID, reply: "once" }))) + const pending = await AppRuntime.runPromise(Question.Service.use((svc) => svc.list())) + const req = pending.find((q) => q.sessionID === id) + if (req) await AppRuntime.runPromise(Question.Service.use((svc) => svc.reject(req.id))) + }, + }) + }, 30000) + + test("idle/busy/retry unchanged when no attention is pending", async () => { + await using tmp = await tmpdir({ git: true }) + await provide({ + directory: tmp.path, + fn: async () => { + await KiloSessions.enableRemote() + const idleId = await setupSession() + const busyId = await setupSession() + const retryId = await setupSession() + + const { AppRuntime } = await import("@/effect/app-runtime") + await AppRuntime.runPromise(SessionStatus.Service.use((svc) => svc.set(busyId, { type: "busy" }))) + await AppRuntime.runPromise( + SessionStatus.Service.use((svc) => + svc.set(retryId, { type: "retry", attempt: 1, message: "retrying", next: 100 }), + ), + ) + + await KiloSessions.attachRemoteSession(idleId) + await KiloSessions.attachRemoteSession(busyId) + await KiloSessions.attachRemoteSession(retryId) + + const payload = await capturedGetSessions()() + const byId = Object.fromEntries(payload.sessions.map((s) => [s.id, s.status])) + expect(byId[idleId]).toBe("idle") + expect(byId[busyId]).toBe("busy") + expect(byId[retryId]).toBe("retry") + }, + }) + }, 30000) + + test("Permission and Question list() are called once per heartbeat across many sessions", async () => { + await using tmp = await tmpdir({ git: true }) + await provide({ + directory: tmp.path, + fn: async () => { + await KiloSessions.enableRemote() + for (let i = 0; i < 4; i++) { + const id = await setupSession() + await KiloSessions.attachRemoteSession(id) + } + + const { AppRuntime } = await import("@/effect/app-runtime") + const { Permission } = await import("@/permission") + const { Question } = await import("@/question") + + // list is readonly on the interface; cast to count calls in place. + type ListBag = { list: () => unknown } + const permSvc = (await AppRuntime.runPromise( + Permission.Service.use((svc) => Effect.succeed(svc)), + )) as unknown as ListBag + const qSvc = (await AppRuntime.runPromise( + Question.Service.use((svc) => Effect.succeed(svc)), + )) as unknown as ListBag + + let permissionListCalls = 0 + let questionListCalls = 0 + const origPermList = permSvc.list.bind(permSvc) + const origQList = qSvc.list.bind(qSvc) + permSvc.list = () => { + permissionListCalls += 1 + return origPermList() + } + qSvc.list = () => { + questionListCalls += 1 + return origQList() + } + + try { + await capturedGetSessions()() + // Once per heartbeat, not once per session (4 sessions attached). + expect(permissionListCalls).toBe(1) + expect(questionListCalls).toBe(1) + + permissionListCalls = 0 + questionListCalls = 0 + await capturedGetSessions()() + expect(permissionListCalls).toBe(1) + expect(questionListCalls).toBe(1) + } finally { + permSvc.list = origPermList + qSvc.list = origQList + } + }, + }) + }, 30000) +}) From e76b35268918488f5aacb141ed4248b13be117b9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Igor=20=C5=A0=C4=87eki=C4=87?= Date: Sat, 25 Jul 2026 14:13:04 +0200 Subject: [PATCH 3/3] chore(cli): widen the promise-facade allowlist for the heartbeat attention tests MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The DEF-3 heartbeat tests raise and reply to real Question and Permission requests through the global AppRuntime, which took kilo-sessions.test.ts from 4 classified references to 29 and failed the allowlist check. Bumping the count rather than restructuring the tests is deliberate: the heartbeat resolves attention status from the global Question.Service and Permission.Service, so asserting it requires driving those same services. Scoped layers cannot express that — the global-runtime coupling is the thing under test — and it is the same integration pattern this entry already sanctioned for the detach fence. The reason string records that. --- script/check-opencode-promise-facades.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/script/check-opencode-promise-facades.ts b/script/check-opencode-promise-facades.ts index dface6a997b8..44f24fb98073 100644 --- a/script/check-opencode-promise-facades.ts +++ b/script/check-opencode-promise-facades.ts @@ -43,11 +43,16 @@ const testAllow: Record = { reason: "disk-backed instance integration test cleanup", }, "kilocode/kilo-sessions.test.ts": { - count: 4, + count: 29, reason: "K1 W1: real integration test for SessionStatus→detach→heartbeat-fence; " + "the test creates a session and sets its status via the global AppRuntime, " + - "then drives the module-level KiloSessions seams and verifies the fence.", + "then drives the module-level KiloSessions seams and verifies the fence. " + + "DEF-3 extends this with heartbeat attention-status coverage: the heartbeat " + + "resolves pending question/permission from the global Question.Service and " + + "Permission.Service, so a test can only assert it by raising and replying to " + + "real requests through that same runtime. Scoped layers cannot express this — " + + "the global-runtime coupling is exactly what is under test.", }, "kilocode/session/platform-attribution.test.ts": { count: 2, reason: "existing runtime integration test" }, "kilocode/session-prompt-queue.test.ts": { count: 6, reason: "prompt queue legacy instance bridge regression" },