Skip to content

Commit c830051

Browse files
authored
Merge pull request #16 from shanebishop1/feat/wake-on-focus
feat: wake a window that napped on focus loss when it regains focus
2 parents e8a4c04 + d6a54ad commit c830051

10 files changed

Lines changed: 81 additions & 21 deletions

File tree

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ Use the object form in the same file to set options:
4747
| `enabled` | `true` | Set to `false` to turn the plugin off without removing it. |
4848
| `debugLogFile` | unset | Absolute path of a diagnostic log. It never contains prompt text. |
4949

50-
Input means a key press, a paste or mouse input. The focus options need a terminal that reports focus changes; without them, only `idleMinutes` applies. An unknown or invalid option turns the plugin off.
50+
Input means a key press, a paste or mouse input. The focus options need a terminal that reports focus changes; without them, only `idleMinutes` applies. A window that napped because it lost focus also wakes when you switch back to it; one that napped on `idleMinutes` waits for a key or click. An unknown or invalid option turns the plugin off.
5151

5252
## How it works
5353

‎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.3",
3+
"version": "0.1.4",
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/park.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ export interface ParkInput {
3434
session: (sessionID: string) => SessionFacts
3535
/** Builds the nap screen the stub prints. */
3636
card: (session: SessionFacts) => string
37+
/** Whether regaining focus wakes the nap, as well as a key or click. */
38+
wakeOnFocus: boolean
3739
/** Synchronously saves the draft; returns extra environment for the woken TUI, or a deferral. */
3840
beforeNap?: () => Record<string, string> | NapDeferral | undefined
3941
/** Checked after draft capture, in case input arrived since the nap was decided. */
@@ -60,6 +62,7 @@ export function park(input: ParkInput): ParkResult {
6062

6163
const stub = buildStubExec({
6264
card: input.card(session),
65+
wakeOnFocus: input.wakeOnFocus,
6366
opencodePath: input.opencodePath,
6467
args: wake.args,
6568
})

‎src/stub.ts‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
export interface StubInput {
22
/** The nap screen, printed verbatim; see card.ts. */
33
card: string
4+
/** Whether regaining focus wakes it, for a nap that losing focus started. */
5+
wakeOnFocus: boolean
46
opencodePath: string
57
args: string[]
68
}
@@ -11,7 +13,7 @@ export interface StubExec {
1113
}
1214

1315
// The stub is POSIX sh in two stages, run as
14-
// `sh -c STUB_SCRIPT sh <card> <opencode> <args...>`. Values only ever arrive
16+
// `sh -c STUB_SCRIPT sh <card> <wake> <opencode> <args...>`. Values only ever arrive
1517
// as positional parameters. In these template literals every backslash is
1618
// doubled and every `${` is escaped.
1719
//
@@ -24,14 +26,25 @@ export interface StubExec {
2426
// `read -n 1` switches the terminal back to signal mode, so Ctrl-C would kill
2527
// the stub instead of waking it. The rest of an escape or mouse sequence is
2628
// drained by the `read` builtin until 0.1 s passes with no input.
29+
//
30+
// With <wake> set to `focus`, the terminal also reports focus. Focus in wakes
31+
// the window like a key; focus out (`ESC [ O`, whose first byte `dd` took)
32+
// goes back to waiting.
2733
const WAIT_SCRIPT = `
28-
opencode=$1
29-
shift
30-
stty min 1 time 0 2>/dev/null
34+
wake=$1 opencode=$2
35+
shift 2
36+
if [ "$wake" = focus ]; then printf '\\033[?1004h'; fi
3137
printf '\\033[?1000h\\033[?1006h'
32-
dd bs=1 count=1 of=/dev/null 2>/dev/null
38+
while :; do
39+
stty min 1 time 0 2>/dev/null
40+
dd bs=1 count=1 of=/dev/null 2>/dev/null
41+
stty min 0 time 1 2>/dev/null
42+
rest=
43+
while IFS= read -r drained; do rest=$rest$drained; done
44+
[ "$rest$drained" = "[O" ] || break
45+
done
3346
# Clicks off before draining, so a late button release is never reported.
34-
printf '\\033[?1000l\\033[?1006l'
47+
printf '\\033[?1000l\\033[?1006l\\033[?1004l'
3548
stty min 0 time 1 2>/dev/null
3649
while IFS= read -r drained; do :; done
3750
# The card's colours and hidden cursor must not outlive it.
@@ -63,7 +76,7 @@ exit 1
6376
const singleQuoted = (text: string): string => `'${text.replace(/'/g, "'\\''")}'`
6477

6578
export const STUB_SCRIPT = `
66-
opencode=$2
79+
wake=$2 opencode=$3
6780
stty sane 2>/dev/null
6881
# Synchronized output off first so the rest shows. Kitty keyboard stacks are
6982
# per screen: pop all on the alternate screen, leave it, pop all on the main one.
@@ -76,8 +89,8 @@ printf '\\033[?25h\\033[0m\\033[2J\\033[H'
7689
stty raw -echo min 0 time 1 2>/dev/null
7790
while IFS= read -r drained; do :; done
7891
printf '%s' "$1"
79-
shift 2
80-
exec /bin/sh -c ${singleQuoted(WAIT_SCRIPT)} sh "$opencode" "$@"
92+
shift 3
93+
exec /bin/sh -c ${singleQuoted(WAIT_SCRIPT)} sh "$wake" "$opencode" "$@"
8194
`
8295

8396
export function buildStubExec(input: StubInput): StubExec {
@@ -89,6 +102,7 @@ export function buildStubExec(input: StubInput): StubExec {
89102
STUB_SCRIPT,
90103
"sh",
91104
input.card,
105+
input.wakeOnFocus ? "focus" : "keys",
92106
input.opencodePath,
93107
...input.args,
94108
],

‎src/tui.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,9 @@ export function startNap(context: unknown, rawOptions: unknown, log: Log, proc:
141141
return { title: session?.title, directory: session?.location?.directory }
142142
},
143143
card: session => hostCard(context, proc, session),
144+
// Coming back wakes a window that napped because you left it; the
145+
// idle timer's nap still waits for a key or click.
146+
wakeOnFocus: rule !== "idle",
144147
beforeNap: () => carry?.capture(),
145148
stillDue: () => state === "napping" && decideNow().action === "nap",
146149
onExec: route => log.write("napping", { rule, route }),

‎tests/e2e.card.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ let server: { process: PtyProcess; url: string }
2020

2121
/** The shell's resident memory once a stub with this card is napping, started like the others in this run. */
2222
async function stubRss(name: string, card: string): Promise<number> {
23-
const stub = buildStubExec({ card, opencodePath: "/bin/true", args: [] })
23+
const stub = buildStubExec({ card, wakeOnFocus: false, opencodePath: "/bin/true", args: [] })
2424
const pty = await startCommand(scratch, name, [stub.file, ...stub.argv.slice(1)])
2525
await waitUntil(() => (pty.output().includes("\x1b[?1000h") ? true : undefined), 10_000, `the ${name} stub to wait for a key`)
2626
await waitUntil(async () => ((await processTree(pty.pid)).count >= 2 ? true : undefined), 5_000, `the ${name} stub's reader`)

‎tests/e2e.focus.test.ts‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -113,16 +113,33 @@ describe.skipIf(!e2eEnabled)(`OpenCode ${cliVersion}: focus rules in a real TUI`
113113
console.log(`blurIdle: plugin start to card ${napped.at - watchingAt} ms`)
114114
}, 120_000)
115115

116-
it("ac-focus-no-wake: focus changes leave a napping window napping; Space wakes it", async () => {
117-
const { tui, run, messages, focus } = await open("no-wake", { idleMinutes: 5, napOnBlur: true })
116+
it("ac-focus-wake: a window that napped on focus out ignores focus out and wakes on focus in", async () => {
117+
const { tui, run, messages, focus } = await open("focus-wake", { idleMinutes: 5, napOnBlur: true })
118118
expect(focus(FOCUS_OUT), await run.context()).toBe(true)
119119
await run.waitForNap(15_000)
120120
const napped = await leader(tui.pid)
121+
// The stub reports focus for a nap that losing focus started.
122+
expect(focus(FOCUS_OUT), await run.context()).toBe(true)
123+
await sleep(1_000)
124+
expect(await leader(tui.pid), await run.context()).toBe(napped)
125+
126+
const focusAt = Date.now()
127+
expect(focus(FOCUS_IN), await run.context()).toBe(true)
128+
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"])
131+
console.log(`focus-wake: focus in to plugin running ${wokeAt - focusAt} ms`)
132+
}, 120_000)
133+
134+
it("ac-focus-no-wake: focus changes leave an idle-timer nap napping; Space wakes it", async () => {
135+
const { tui, run, messages, focus } = await open("no-wake", napOptions)
136+
await run.waitForNap(NAP_TIMEOUT_MS)
137+
const napped = await leader(tui.pid)
121138
const offset = tui.output().length
122-
// The stub turned focus reporting off, so a terminal sends nothing on a focus change.
139+
// The idle timer's nap leaves focus reporting off, so a terminal sends nothing on a focus change.
123140
const sent = [FOCUS_IN, FOCUS_OUT, FOCUS_IN, FOCUS_OUT].map(report => focus(report))
124141
expect(sent, await run.context()).toEqual([false, false, false, false])
125-
await sleep(3_000)
142+
await sleep(1_000)
126143
expect(await messages(), await run.context()).toEqual(["loaded", "watching", "napping"])
127144
expect(await leader(tui.pid), await run.context()).toBe(napped)
128145
expect(stripEscapesSince(tui, offset).trim(), await run.context()).toBe("")

‎tests/park.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ describe("park", () => {
2828
env: { PATH: "/usr/bin" },
2929
session: () => ({ title: "Title", directory: "/work/project" }),
3030
card: session => `card for ${String(session.title)} in ${String(session.directory)}`,
31+
wakeOnFocus: false,
3132
stillDue: () => true,
3233
execve: (...args) => {
3334
calls.push(args)
@@ -40,7 +41,7 @@ describe("park", () => {
4041
it("execs the stub with the card, the wake command line and the environment", () => {
4142
const parkInput = input()
4243
expect(park(parkInput)).toEqual({ status: "exec-failed", error: new Error("ENOENT") })
43-
const stub = buildStubExec({ card: "card for Title in /work/project", opencodePath: "/bin/opencode", args: ["--server", "http://127.0.0.1:1", "/abs/project", "-s", "ses_a"] })
44+
const stub = buildStubExec({ card: "card for Title in /work/project", wakeOnFocus: false, opencodePath: "/bin/opencode", args: ["--server", "http://127.0.0.1:1", "/abs/project", "-s", "ses_a"] })
4445
expect(parkInput.calls).toEqual([[stub.file, stub.argv, { PATH: "/usr/bin" }]])
4546
})
4647

‎tests/stub.test.ts‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -72,12 +72,13 @@ const sleep = (ms: number) => new Promise(done => setTimeout(done, ms))
7272
* has not exited within `timeoutMs` is stopped and reported as timed out.
7373
*/
7474
async function runStub(
75-
input: { card?: string; opencodePath?: string; args?: string[] },
75+
input: { card?: string; wakeOnFocus?: boolean; opencodePath?: string; args?: string[] },
7676
steps: Step[],
7777
timeoutMs = 6_000,
7878
): Promise<Run> {
7979
const exec = buildStubExec({
8080
card: input.card ?? CARD,
81+
wakeOnFocus: input.wakeOnFocus ?? false,
8182
opencodePath: input.opencodePath ?? opencode,
8283
args: input.args ?? [],
8384
})
@@ -124,13 +125,14 @@ describe("buildStubExec", () => {
124125
it("passes every value as a positional argument after the script", () => {
125126
const exec = buildStubExec({
126127
card: "My session",
128+
wakeOnFocus: true,
127129
opencodePath: "/opt/opencode",
128130
args: ["-s", "ses_1", "$(touch x)"],
129131
})
130132

131133
expect(exec.file).toBe("/bin/sh")
132134
expect(exec.argv).toEqual([
133-
"sh", "-c", STUB_SCRIPT, "sh", "My session", "/opt/opencode", "-s", "ses_1", "$(touch x)",
135+
"sh", "-c", STUB_SCRIPT, "sh", "My session", "focus", "/opt/opencode", "-s", "ses_1", "$(touch x)",
134136
])
135137
expect(STUB_SCRIPT).not.toContain("My session")
136138
})
@@ -196,6 +198,25 @@ describe("stub under a terminal", () => {
196198
expect(run.fake?.markKept).toBe(true)
197199
})
198200

201+
it("ac-focus-wake: with focus waking, focus in wakes it and reporting is off again for OpenCode", async () => {
202+
const run = await runStub({ wakeOnFocus: true }, wakeSteps([{ send: `${ESC}[O` }, { sleep: 300 }, { send: `${ESC}[I` }]))
203+
const nap = napOutput(run)
204+
expect(nap.lastIndexOf(`${ESC}[?1004l`)).toBeGreaterThan(nap.indexOf(`${ESC}[?1004h`))
205+
expect(run.status).toBe(0)
206+
expect(run.fake?.stdin).toBe(PROBE)
207+
})
208+
209+
it("ac-focus-wake: focus out alone leaves it napping", async () => {
210+
const run = await runStub({ wakeOnFocus: true }, [{ expect: ARMED }, { send: `${ESC}[O` }, { expect: "@@READY@@" }], 1_500)
211+
expect(run.timedOut).toBe(true)
212+
expect(run.output).not.toContain("@@READY@@")
213+
})
214+
215+
it("ac-focus-no-wake: without focus waking, focus reporting stays off", async () => {
216+
const run = await runStub({}, wakeSteps([{ send: SPACE }]))
217+
expect(napOutput(run)).not.toContain(`${ESC}[?1004h`)
218+
})
219+
199220
it("ac-wake-key: the wake key does not reach OpenCode", async () => {
200221
const run = await runStub({}, wakeSteps([{ send: SPACE }]))
201222
expect(run.fake?.stdin).toBe(PROBE)

‎tests/tui.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,7 @@ describe("startNap", () => {
4949
home: "/home/shane",
5050
version: "2.2.4",
5151
}),
52+
wakeOnFocus: false,
5253
opencodePath: "/opt/opencode/bin/opencode",
5354
args: ["--server", SERVER_URL, "-s", SESSION_ID],
5455
})
@@ -63,7 +64,7 @@ describe("startNap", () => {
6364
const { fake } = await start({ edit: context => { context.route = { type: "home" } } })
6465
await fake.advance(IDLE_MS + 5_000)
6566
const [card, ...rest] = fake.execs[0].argv.slice(4)
66-
expect(rest).toEqual(["/opt/opencode/bin/opencode", "--server", SERVER_URL])
67+
expect(rest).toEqual(["keys", "/opt/opencode/bin/opencode", "--server", SERVER_URL])
6768
expect(withoutSequences(card)).toContain("Press any key or click to wake.")
6869
expect(withoutSequences(card)).toContain("/work/project")
6970
})
@@ -97,7 +98,7 @@ describe("startNap", () => {
9798
it("makes a relative directory argument absolute", async () => {
9899
const { fake } = await start({ args: ["--server", SERVER_URL, "project"] })
99100
await fake.advance(IDLE_MS + 5_000)
100-
expect(fake.execs[0].argv.slice(6)).toEqual(["--server", SERVER_URL, "/work/project", "-s", SESSION_ID])
101+
expect(fake.execs[0].argv.slice(7)).toEqual(["--server", SERVER_URL, "/work/project", "-s", SESSION_ID])
101102
})
102103

103104
it("ac-exec-fails: an execve that throws turns the plugin off without a retry", async () => {

0 commit comments

Comments
 (0)