Skip to content

Commit 124e69a

Browse files
authored
Merge pull request #19 from shanebishop1/fix/focus-state-startup
fix: retain terminal focus across startup and reload
2 parents 345f3f7 + f0f06be commit 124e69a

8 files changed

Lines changed: 210 additions & 24 deletions

File tree

‎package.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "opencode-nap",
3-
"version": "0.1.5",
3+
"version": "0.1.6",
44
"description": "OpenCode TUI plugin that naps idle windows to free memory and wakes them into the same session",
55
"type": "module",
66
"exports": {

‎src/focus.ts‎

Lines changed: 17 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { Focus } from "./policy.js"
22
import type { Emitter } from "./probe.js"
3+
import { read } from "./read.js"
34

45
export interface FocusState {
56
focus: Focus
@@ -11,12 +12,23 @@ export interface FocusSource {
1112
dispose(): void
1213
}
1314

14-
/**
15-
* Terminal focus from the renderer's "focus" and "blur" events; unknown until
16-
* the first one. `onChange` runs after each change, not for a repeated event.
17-
*/
15+
// The renderer may already have received focus before a plugin starts or
16+
// reloads. This private snapshot is optional: an older or changed renderer
17+
// still works from future events, without guessing that the window is away.
18+
function rendererFocus(renderer: Emitter): Focus {
19+
try {
20+
const focused = read(renderer, "_terminalFocusState")
21+
return focused === true ? "focused" : focused === false ? "unfocused" : "unknown"
22+
} catch {
23+
return "unknown"
24+
}
25+
}
26+
27+
/** Terminal focus, including reports received before setup. `onChange` runs only after later changes. */
1828
export function createFocusSource(input: { renderer: Emitter; now: () => number; onChange?: () => void }): FocusSource {
19-
let current: FocusState = { focus: "unknown", unfocusedSince: undefined }
29+
const initial = rendererFocus(input.renderer)
30+
// The earlier blur's time is not known; allow the full debounce from now.
31+
let current: FocusState = { focus: initial, unfocusedSince: initial === "unfocused" ? input.now() : undefined }
2032

2133
const onFocus = () => {
2234
if (current.focus === "focused") return

‎src/tui.ts‎

Lines changed: 19 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,17 @@ export function startNap(context: unknown, rawOptions: unknown, log: Log, proc:
194194
schedule(decision.checkAfterMs)
195195
}
196196

197+
// Subscribe before awaiting server info, so focus changes during startup
198+
// are not lost even if the renderer has no readable focus snapshot.
199+
try {
200+
focus = createFocusSource({ renderer: host.renderer, now: proc.now, onChange: recheck })
201+
const source = focus
202+
disposers.push(() => source.dispose())
203+
} catch (error) {
204+
off("off: runtime error", { error: describe(error) })
205+
return cleanup
206+
}
207+
197208
void (async () => {
198209
let serverPid: number | undefined
199210
try {
@@ -218,18 +229,14 @@ export function startNap(context: unknown, rawOptions: unknown, log: Log, proc:
218229
}
219230

220231
try {
221-
const sources = {
222-
idle: createIdleSource({
223-
now: proc.now,
224-
readAtime: proc.readAtime,
225-
keyInput: host.renderer.keyInput,
226-
stdin,
227-
}),
228-
focus: createFocusSource({ renderer: host.renderer, now: proc.now, onChange: recheck }),
229-
}
230-
idle = sources.idle
231-
focus = sources.focus
232-
disposers.push(() => sources.idle.dispose(), () => sources.focus.dispose())
232+
const source = createIdleSource({
233+
now: proc.now,
234+
readAtime: proc.readAtime,
235+
keyInput: host.renderer.keyInput,
236+
stdin,
237+
})
238+
idle = source
239+
disposers.push(() => source.dispose())
233240
} catch (error) {
234241
off("off: runtime error", { error: describe(error) })
235242
return

‎tests/e2e.card.test.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ describe.skipIf(!e2eEnabled)(`OpenCode ${cliVersion}: the nap card`, () => {
5252
expect(drawn).toContain("Sessions keep running in the background.")
5353
// Long scratch paths are cut to their last segments, so only the end is certain.
5454
expect(drawn).toContain("/project")
55-
expect(drawn).toContain("2.2.4")
55+
expect(drawn).toContain(cliVersion)
5656
// The stub prints once and waits: one shell and its reader, nothing else,
5757
// and the shell that waits no longer carries the card.
5858
expect(napped.count).toBe(2)
@@ -67,7 +67,7 @@ describe.skipIf(!e2eEnabled)(`OpenCode ${cliVersion}: the nap card`, () => {
6767
title: "Fix the flaky test",
6868
directory: scratch.project,
6969
home: scratch.env.HOME,
70-
version: "2.2.4",
70+
version: cliVersion,
7171
})
7272
const [withCard, plain] = [await stubRss("card-stub", rich), await stubRss("plain-stub", plainCard(""))]
7373
console.log(`napped sh RSS: ${withCard} KiB with the card, ${plain} KiB with plain text (${withCard - plain} KiB more)`)

‎tests/e2e.focus-startup.test.ts‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
import { afterAll, afterEach, beforeAll, describe, expect, it } from "bun:test"
2+
import { mkdir, writeFile } from "fs/promises"
3+
import { join } from "path"
4+
import {
5+
cleanup, cliVersion, createScratch, createSession, e2eEnabled, installedPackage,
6+
installObserver, startServer, startTuiWith, stopTuis, writeCliConfig, type Scratch,
7+
} from "./e2e/harness.js"
8+
import { NapRun, SPACE, waitUntil, Watch } from "./e2e/nap-run.js"
9+
import { napOptions, NAP_TIMEOUT_MS } from "./e2e/timing.js"
10+
11+
const FOCUS_IN = "\x1b[I"
12+
const FOCUS_OUT = "\x1b[O"
13+
14+
function focusReporting(raw: string): boolean {
15+
let on = false
16+
// eslint-disable-next-line no-control-regex
17+
for (const match of raw.matchAll(/\x1b\[\?([\d;]+)([hl])/g)) {
18+
if (match[1].split(";").includes("1004")) on = match[2] === "h"
19+
}
20+
return on
21+
}
22+
23+
let scratch: Scratch
24+
let server: Awaited<ReturnType<typeof startServer>>
25+
26+
/** Start the packed plugin only after the real renderer has received focus. */
27+
async function openAfterFocus(name: string, report: string) {
28+
const watch = await Watch.configure(scratch, name, napOptions)
29+
const gate = join(scratch.root, `${name}-gate`)
30+
await mkdir(gate)
31+
await writeFile(join(gate, "package.json"), JSON.stringify({ name: "nap-e2e-focus-gate", private: true, type: "module", exports: { "./tui": "./tui.js" } }))
32+
await writeFile(join(gate, "tui.js"), `
33+
import nap from ${JSON.stringify(join(installedPackage(scratch), "dist/tui.js"))}
34+
import { appendFileSync } from "node:fs"
35+
export default { id: "nap-e2e-focus-gate", async setup(api) {
36+
if (!process.env.NAP_E2E_FOCUS_GATE_PASSED) {
37+
await new Promise(resolve => {
38+
const ready = () => { api.renderer.off(${JSON.stringify(report === FOCUS_OUT ? "blur" : "focus")}, ready); resolve() }
39+
api.renderer.on(${JSON.stringify(report === FOCUS_OUT ? "blur" : "focus")}, ready)
40+
appendFileSync(${JSON.stringify(watch.observerLog)}, JSON.stringify({event:"waiting-for-focus"}) + "\\n")
41+
})
42+
process.env.NAP_E2E_FOCUS_GATE_PASSED = "1"
43+
}
44+
return nap.setup(api)
45+
} }
46+
`)
47+
await writeCliConfig(scratch, [
48+
{ package: gate, options: { ...napOptions, debugLogFile: watch.napLog } },
49+
{ package: await installObserver(scratch), options: { logFile: watch.observerLog, controlDir: watch.controlDir } },
50+
])
51+
const sessionID = await createSession(scratch, server.url)
52+
const tui = await startTuiWith(scratch, name, ["--server", server.url, "-s", sessionID, scratch.project])
53+
const run = new NapRun(tui, watch)
54+
await waitUntil(() => tui.output().includes("\x1b[?1004$p") || undefined, 60_000, "the focus mode query")
55+
tui.write("\x1b[?1004;2$y")
56+
await waitUntil(() => focusReporting(tui.output()) || undefined, 30_000, "focus reporting on")
57+
await waitUntil(async () => (await watch.observerEntries()).some(entry => entry.event === "waiting-for-focus") || undefined, 30_000, "delayed plugin setup")
58+
tui.write(report)
59+
await run.waitForWatching(1)
60+
await run.waitForInteractive(0)
61+
return { tui, run }
62+
}
63+
64+
describe.skipIf(!e2eEnabled)(`OpenCode ${cliVersion}: focus received before plugin setup`, () => {
65+
beforeAll(async () => {
66+
scratch = await createScratch()
67+
server = await startServer(scratch)
68+
}, 300_000)
69+
afterEach(stopTuis, 60_000)
70+
afterAll(cleanup, 60_000)
71+
72+
it("ac-focus-startup: an already-unfocused window naps and wakes on refocus", async () => {
73+
const { tui, run } = await openAfterFocus("early-blur", FOCUS_OUT)
74+
await run.waitForNap(NAP_TIMEOUT_MS)
75+
expect(focusReporting(tui.output()), await run.context()).toBe(true)
76+
const focusAt = Date.now()
77+
tui.write(FOCUS_IN)
78+
await run.waitForWatching(2)
79+
await run.waitForInteractive(focusAt)
80+
}, 120_000)
81+
82+
it("ac-focus-startup: an already-focused window still waits for a key or click", async () => {
83+
const { tui, run } = await openAfterFocus("early-focus", FOCUS_IN)
84+
await run.waitForNap(NAP_TIMEOUT_MS)
85+
// A real terminal sends no focus reports while this mode is disabled.
86+
expect(focusReporting(tui.output()), await run.context()).toBe(false)
87+
await run.assertNapping()
88+
const spaceAt = await run.wake(SPACE)
89+
await run.waitForWatching(2)
90+
await run.waitForInteractive(spaceAt)
91+
}, 120_000)
92+
})

‎tests/e2e.focus.test.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -126,8 +126,10 @@ describe.skipIf(!e2eEnabled)(`OpenCode ${cliVersion}: focus rules in a real TUI`
126126
const focusAt = Date.now()
127127
expect(focus(FOCUS_IN), await run.context()).toBe(true)
128128
const wokeAt = await run.waitForWatching(2)
129-
expect(await leader(tui.pid), await run.context()).toContain("opencode")
130-
expect(await messages(), await run.context()).toEqual(["loaded", "watching", "napping", "loaded", "watching"])
129+
await run.waitForInteractive(focusAt)
130+
// Under load the short test timer may legitimately expire again before
131+
// assertions finish. Check the first wake, not the window's later state.
132+
expect((await messages()).slice(0, 5), await run.context()).toEqual(["loaded", "watching", "napping", "loaded", "watching"])
131133
console.log(`focus-wake: focus in to plugin running ${wokeAt - focusAt} ms`)
132134
}, 120_000)
133135

@@ -146,8 +148,8 @@ describe.skipIf(!e2eEnabled)(`OpenCode ${cliVersion}: focus rules in a real TUI`
146148

147149
const spaceAt = await run.wake(SPACE)
148150
const wokeAt = await run.waitForWatching(2)
149-
expect(await leader(tui.pid), await run.context()).toContain("opencode")
150-
expect(await messages(), await run.context()).toEqual(["loaded", "watching", "napping", "loaded", "watching"])
151+
await run.waitForInteractive(spaceAt)
152+
expect((await messages()).slice(0, 5), await run.context()).toEqual(["loaded", "watching", "napping", "loaded", "watching"])
151153
console.log(`no-wake: Space to plugin running ${wokeAt - spaceAt} ms`)
152154
}, 120_000)
153155

‎tests/focus.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,39 @@ import { createFocusSource } from "../src/focus.js"
33
import { FakeEmitter } from "./fakes.js"
44

55
describe("createFocusSource", () => {
6+
it("recovers focus reports received before setup and keeps the blur debounce", () => {
7+
for (const focused of [false, true]) {
8+
let now = 1_000
9+
const renderer = Object.assign(new FakeEmitter(), { _terminalFocusState: focused })
10+
const seen: string[] = []
11+
const focus = createFocusSource({ renderer, now: () => now, onChange: () => seen.push("change") })
12+
expect(focus.state()).toEqual({ focus: focused ? "focused" : "unfocused", unfocusedSince: focused ? undefined : now })
13+
expect(seen).toEqual([])
14+
15+
now = 2_000
16+
renderer.emit(focused ? "focus" : "blur")
17+
expect(focus.state().unfocusedSince).toBe(focused ? undefined : 1_000)
18+
expect(seen).toEqual([])
19+
renderer.emit(focused ? "blur" : "focus")
20+
expect(focus.state().focus).toBe(focused ? "unfocused" : "focused")
21+
expect(seen).toEqual(["change"])
22+
focus.dispose()
23+
expect(renderer.count()).toBe(0)
24+
}
25+
})
26+
27+
it("keeps unknown focus when the optional snapshot is absent, invalid or unreadable", () => {
28+
const renderers = [undefined, null, "false", 0, {}].map(value => Object.assign(new FakeEmitter(), { _terminalFocusState: value }))
29+
renderers.push(Object.defineProperty(new FakeEmitter(), "_terminalFocusState", { get() { throw new Error("changed internal") } }))
30+
for (const renderer of renderers) {
31+
const focus = createFocusSource({ renderer, now: () => 1_000 })
32+
expect(focus.state()).toEqual({ focus: "unknown", unfocusedSince: undefined })
33+
renderer.emit("blur")
34+
expect(focus.state()).toEqual({ focus: "unfocused", unfocusedSince: 1_000 })
35+
focus.dispose()
36+
}
37+
})
38+
639
it("reports unknown until the first event, then tracks focus and when it was lost", () => {
740
let now = 1_000
841
const renderer = new FakeEmitter()

‎tests/tui.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,46 @@ describe("startNap", () => {
107107
expect(here.fake.execs[0].argv[5]).toBe("keys")
108108
})
109109

110+
it("ac-focus-startup: a focus report received before setup still selects the correct wake mode", async () => {
111+
for (const focused of [false, true]) {
112+
const { fake, cleanup } = await start({ edit: context => { Object.assign(context.renderer, { _terminalFocusState: focused }) } })
113+
await fake.advance(IDLE_MS + 5_000)
114+
expect(fake.execs[0].argv[5]).toBe(focused ? "keys" : "focus")
115+
cleanup()
116+
}
117+
})
118+
119+
it("ac-focus-reload: reloading while unfocused keeps focus-wake without another blur report", async () => {
120+
const { fake, context, cleanup } = await start()
121+
Object.assign(context.renderer, { _terminalFocusState: false })
122+
context.renderer.emit("blur")
123+
cleanup()
124+
const stop = startNap(context, options, fakeLog(), fake.proc)
125+
await fake.advance(IDLE_MS + 5_000)
126+
expect(fake.execs[0].argv[5]).toBe("focus")
127+
stop()
128+
expect(context.renderer.count() + context.renderer.keyInput.count() + fake.stdin.count()).toBe(0)
129+
})
130+
131+
it("ac-focus-startup: follows focus changes while the server info request is pending", async () => {
132+
for (const refocus of [false, true]) {
133+
const fake = fakeProcess()
134+
const context = fakeContext(fake.stdin)
135+
let answer!: (value: { pid: unknown; version: string }) => void
136+
context.client.server.info = () => new Promise(resolve => { answer = resolve })
137+
const cleanup = startNap(context, options, fakeLog(), fake.proc)
138+
// No snapshot: even older renderers must not lose reports during setup.
139+
context.renderer.emit("blur")
140+
await fake.advance(5_000)
141+
if (refocus) context.renderer.emit("focus")
142+
expect(fake.execs).toHaveLength(0)
143+
answer({ pid: 200, version: "2.2.4" })
144+
await fake.advance(IDLE_MS + 5_000)
145+
expect(fake.execs[0].argv[5]).toBe(refocus ? "keys" : "focus")
146+
cleanup()
147+
}
148+
})
149+
110150
it("makes a relative directory argument absolute", async () => {
111151
const { fake } = await start({ args: ["--server", SERVER_URL, "project"] })
112152
await fake.advance(IDLE_MS + 5_000)

0 commit comments

Comments
 (0)