@lethevimlet/sshift 1.7.2 → 1.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,260 +1,456 @@
1
1
  /**
2
2
  * opencode-attention Plugin
3
3
  *
4
- * Detects when opencode (https://opencode.ai) is waiting for user input
5
- * in an SSH terminal and flashes the tab to alert the user.
4
+ * Flashes the tab when OpenCode (https://opencode.ai) finishes working and
5
+ * is waiting for the user (reply complete, or a permission/confirmation
6
+ * dialog).
6
7
  *
7
- * Detection strategy:
8
- * - Detects opencode's TUI by looking for "OpenCode" in the terminal state (sticky: once detected, stays true)
9
- * - Tracks opencode's processing state via spinner characters (⬝ ■ ▣)
10
- * - While opencode is working (spinner seen within idleThreshold), ALL flashing is suppressed
11
- * - When opencode goes idle (no spinner for > idleThreshold ms after working), flashes the tab
12
- * - Schedules an immediate attention check when spinner stops (no delay waiting for timer)
13
- * - Detects opencode-specific prompt patterns ("❯", "> ", "(y/n)", etc.)
14
- * - Prompt detection only activates in confirmed OpenCode sessions (isOpencode gate)
15
- * - Suppresses re-flash for a cooldown period after spinner stops a flash
8
+ * Detection strategy (state-transition based, not text-pattern based):
9
+ *
10
+ * 1. App detection is NON-STICKY: OpenCode is considered present only
11
+ * while one of its UI signatures is visible in the CURRENT viewport of
12
+ * the headless terminal (the "OpenCode x.y.z" status bar, the
13
+ * "ctrl+p commands" hint, the "esc interrupt" hint). When the user
14
+ * exits back to a shell the signatures disappear and, after a few
15
+ * misses, no NEW working episode can start — so a shell prompt can
16
+ * never arm the engine.
17
+ *
18
+ * 2. "Working" is tracked from two signals:
19
+ * - working indicators visible in the viewport footer (braille and
20
+ * block spinner glyphs, "esc to interrupt"/"esc interrupt"), and
21
+ * - sustained agent-driven output: bytes that arrive while the user
22
+ * has NOT typed recently (echo/UI responses to keystrokes are
23
+ * ignored via userEchoWindowMs).
24
+ *
25
+ * 3. The tab flashes ONLY on the working → idle TRANSITION: a working
26
+ * episode was observed, the working indicator is gone, and no work
27
+ * signal has been seen for idleThreshold ms. A finished reply and a
28
+ * permission dialog both look like this transition, so no brittle
29
+ * prompt regexes ("❯ ", "(y/n)", "allow", ...) are needed — those
30
+ * match ordinary chat prose, code and shell prompts.
31
+ *
32
+ * 4. User input (keystrokes) ends the current working episode, stops an
33
+ * active flash and suppresses flashing for cooldownMs — the user is
34
+ * already there. A genuinely running agent re-arms the episode with
35
+ * its very next spinner frame, so nothing is lost.
36
+ *
37
+ * Things that made v1.7.3 miss most "waiting for input" events, and how
38
+ * they are handled now:
39
+ *
40
+ * - The viewport was read through getTerminalState(), which serializes
41
+ * the whole 10k-line scrollback and returns NULL past its 1MB guard.
42
+ * Busy agent sessions — exactly the ones worth watching — went blind.
43
+ * Now it reads getTerminalViewport() (visible screen only) and follows
44
+ * the alternate-screen marker, so OpenCode's full-screen TUI is read
45
+ * from the buffer it actually draws on.
46
+ * - A transition that landed inside the post-keystroke cooldown was
47
+ * dropped and never retried. The engine now keeps a pendingAttention
48
+ * flag and retries on every check until the flash actually goes out.
49
+ * - Losing the app signature (a dialog can cover the status bar) wiped
50
+ * the pending episode. App misses now only stop NEW episodes from
51
+ * starting; an armed one still gets to flash.
52
+ * - A flash the user dismissed by simply looking at the tab left the
53
+ * server stuck in "already flashing", swallowing every later event.
54
+ * Clients now report onSessionFocus, and a fresh transition re-emits
55
+ * the flash anyway.
16
56
  *
17
57
  * Configuration (in config.json under plugins[].config):
18
- * - patterns: string[] - Additional regex patterns to detect attention
19
- * - debounceMs: number - Milliseconds between full-state checks (default: 300)
20
- * - flashDuration: number - Flash duration in ms, 0 = flash until focused (default: 0)
21
- * - excludePatterns: string[] - Regex patterns to exclude from detection
22
- * - checkInterval: number - Milliseconds between periodic terminal state checks (default: 2000)
23
- * - idleThreshold: number - Milliseconds without spinner before considered idle (default: 3000)
24
- * - cooldownMs: number - Milliseconds to suppress re-flash after spinner stops a flash (default: 1000)
58
+ * - flashDuration: number - Flash duration in ms, 0 = flash until focused (default: 0)
59
+ * - checkInterval: number - Milliseconds between periodic viewport checks (default: 2000)
60
+ * - idleThreshold: number - Milliseconds without a work signal before OpenCode
61
+ * is considered idle/finished (default: 2500)
62
+ * - cooldownMs: number - Milliseconds to suppress flashing after user input
63
+ * or after a flash stops (default: 3000)
64
+ * - debounceMs: number - Debounce for output-driven evaluations (default: 300)
65
+ * - footerLines: number - Viewport bottom lines scanned for working
66
+ * indicators / custom patterns (default: 8)
67
+ * - userEchoWindowMs: number - Output arriving within this window after a
68
+ * keystroke counts as echo, not agent work (default: 1200)
69
+ * - minWorkBytes: number - Agent-driven bytes within workWindowMs that
70
+ * mark the session as working (default: 600)
71
+ * - workWindowMs: number - Rolling window for minWorkBytes (default: 2000)
72
+ * - appMissLimit: number - Consecutive viewport checks without an app
73
+ * signature before new episodes are blocked (default: 3)
74
+ * - appPatterns: string[] - Regexes replacing the default app signatures
75
+ * - spinnerStaleMs: number - A bare spinner glyph only counts as "working" if
76
+ * output arrived within this window (default: 2000)
77
+ * - workStaleMs: number - A screen with no output at all for this long is
78
+ * never considered working (default: 60000)
79
+ * - workingPatterns: string[] - Regexes replacing the default working indicators
80
+ * - workingHintPatterns: string[] - Regexes for run hints that count as working
81
+ * even on a quiet screen (default: "esc to interrupt")
82
+ * - patterns: string[] - Extra attention regexes (footer lines, idle only)
83
+ * - excludePatterns: string[] - Remove patterns (by source) from all lists
25
84
  */
26
85
 
27
86
  class OpenCodeAttentionPlugin {
28
87
  constructor(ctx, config = {}) {
29
88
  this.ctx = ctx;
30
89
  this.config = {
31
- debounceMs: config.debounceMs || 300,
32
90
  flashDuration: config.flashDuration || 0,
33
91
  checkInterval: config.checkInterval || 2000,
34
- idleThreshold: config.idleThreshold || 3000,
35
- cooldownMs: config.cooldownMs || 1000,
36
- ...config,
92
+ idleThreshold: config.idleThreshold || 2500,
93
+ cooldownMs: config.cooldownMs || 3000,
94
+ debounceMs: config.debounceMs || 300,
95
+ footerLines: config.footerLines || 8,
96
+ userEchoWindowMs: config.userEchoWindowMs || 1200,
97
+ minWorkBytes: config.minWorkBytes || 600,
98
+ workWindowMs: config.workWindowMs || 2000,
99
+ appMissLimit: config.appMissLimit || 3,
100
+ spinnerStaleMs: config.spinnerStaleMs || 2000,
101
+ workStaleMs: config.workStaleMs || 60000,
37
102
  };
38
103
 
39
- this.patterns = this._buildPatterns(config.patterns || [], config.excludePatterns || []);
104
+ // App signatures: the OpenCode TUI always renders its wordmark (status
105
+ // bar "OpenCode x.y.z", splash logo) plus the command hint in the same
106
+ // bar. Case-SENSITIVE on purpose so lowercase shell text (`cd
107
+ // opencode`, paths, package names) can't arm the engine — and even a
108
+ // false positive here only ARMS it; a flash still requires a real
109
+ // working → idle transition.
110
+ this._appPatterns = this._compileList(
111
+ config.appPatterns || [
112
+ 'OpenCode',
113
+ 'ctrl\\+p commands',
114
+ 'esc interrupt',
115
+ 'esc to interrupt',
116
+ ],
117
+ 'appPatterns',
118
+ '' // case-sensitive
119
+ );
120
+
121
+ // Working indicators, scanned over the viewport footer only:
122
+ // - the full braille block (U+2800–U+28FF) covers every braille
123
+ // spinner variant across OpenCode versions,
124
+ // - ⬝■▣ are the legacy OpenCode spinner frames,
125
+ // - ◐◓◑◒◜◝◞◟ cover the arc/circle spinner frames,
126
+ // - "esc to interrupt"-style hints cover text-based indicators.
127
+ this._workingPatterns = this._compileList(
128
+ config.workingPatterns || [
129
+ '[\\u2800-\\u28FF]',
130
+ '[⬝■▣]',
131
+ '[◐◓◑◒◜◝◞◟]',
132
+ 'esc to interrupt',
133
+ 'esc interrupt',
134
+ ],
135
+ 'workingPatterns'
136
+ );
137
+
138
+ // Text hints that stay on screen for the WHOLE run ("esc to
139
+ // interrupt"). Unlike a spinner glyph these are unambiguous, so they
140
+ // count as "working" even when the screen is completely quiet.
141
+ this._workingHintPatterns = this._compileList(
142
+ config.workingHintPatterns || [
143
+ 'esc to interrupt',
144
+ 'esc interrupt',
145
+ ],
146
+ 'workingHintPatterns'
147
+ );
148
+
149
+ // Optional user-supplied attention patterns (none by default).
150
+ this._attentionPatterns = this._compileList(config.patterns || [], 'patterns');
151
+
152
+ // excludePatterns removes entries (matched by regex source) from all lists.
153
+ for (const p of (config.excludePatterns || [])) {
154
+ try {
155
+ const source = new RegExp(p).source;
156
+ this._appPatterns = this._appPatterns.filter(r => r.source !== source);
157
+ this._workingPatterns = this._workingPatterns.filter(r => r.source !== source);
158
+ this._workingHintPatterns = this._workingHintPatterns.filter(r => r.source !== source);
159
+ this._attentionPatterns = this._attentionPatterns.filter(r => r.source !== source);
160
+ } catch (e) {
161
+ console.error(`[opencode-attention] Invalid exclude pattern "${p}":`, e.message);
162
+ }
163
+ }
40
164
 
41
- this._dataTimers = new Map();
165
+ this._sessionState = new Map();
42
166
  this._checkTimers = new Map();
167
+ this._dataTimers = new Map();
168
+ this._idleTimers = new Map();
43
169
  this._flashing = new Map();
44
- this._sessionState = new Map();
170
+ }
171
+
172
+ _compileList(list, label, flags = 'i') {
173
+ const out = [];
174
+ for (const p of list) {
175
+ try { out.push(new RegExp(p, flags)); } catch (e) {
176
+ console.error(`[opencode-attention] Invalid ${label} regex "${p}":`, e.message);
177
+ }
178
+ }
179
+ return out;
45
180
  }
46
181
 
47
182
  _getSessionState(sessionId) {
48
183
  if (!this._sessionState.has(sessionId)) {
49
184
  this._sessionState.set(sessionId, {
50
- isOpencode: false,
51
- lastSpinnerTime: 0,
52
- wasWorking: false,
185
+ appVisible: false, // signature currently on screen
186
+ appMissStreak: 0, // consecutive checks without a signature
187
+ working: false, // working indicator seen recently
188
+ workEpisode: false, // a working episode is armed (not yet consumed)
189
+ pendingAttention: false, // wants to flash, hasn't managed to yet
190
+ lastWorkSignalAt: 0, // last time any work signal was seen
191
+ lastUserInputAt: 0, // last user keystroke
192
+ lastOutputAt: 0, // last output of any kind
193
+ agentBytes: 0, // agent-driven bytes in the rolling window
194
+ agentWindowStart: 0,
53
195
  cooldownUntil: 0,
54
- idleCheckScheduled: false,
55
196
  });
56
197
  }
57
198
  return this._sessionState.get(sessionId);
58
199
  }
59
200
 
60
- _isWorking(sessionId) {
61
- const s = this._getSessionState(sessionId);
62
- return s.wasWorking && (Date.now() - s.lastSpinnerTime) < this.config.idleThreshold;
201
+ _stripAnsi(str) {
202
+ return str
203
+ .replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '')
204
+ .replace(/\x1b\][^\x07]*\x07/g, '')
205
+ .replace(/\x1b\[\?[0-9]+[hl]/g, '')
206
+ .replace(/\x1b[\(\)]B/g, '')
207
+ .replace(/\x1b[0-9;]*[a-zA-Z]/g, '')
208
+ .replace(/\x1b[^[\]()?P]/g, '')
209
+ .replace(/[\x00-\x08\x0b\x0c\x0d\x0e-\x1f\x7f]/g, '');
63
210
  }
64
211
 
65
- _buildPatterns(extraPatterns, excludePatterns) {
66
- const defaultPatterns = [
67
- /\> $/,
68
- /\> \x1b/,
69
- /❯ /,
70
- /waiting for input/i,
71
- /press enter/i,
72
- /press any key/i,
73
- /confirm\s*\?/i,
74
- /\(y\/n\)/i,
75
- /\(yes\/no\)/i,
76
- /\[Y\/n\]/i,
77
- /\[y\/N\]/i,
78
- ];
79
-
80
- let patterns = [...defaultPatterns];
81
-
82
- for (const p of extraPatterns) {
83
- try { patterns.push(new RegExp(p)); } catch (e) {
84
- console.error(`[opencode-attention] Invalid pattern "${p}":`, e.message);
85
- }
212
+ _matchesAny(patterns, text) {
213
+ for (const p of patterns) {
214
+ if (p.test(text)) return true;
86
215
  }
216
+ return false;
217
+ }
87
218
 
88
- for (const p of excludePatterns) {
89
- try {
90
- const regex = new RegExp(p);
91
- patterns = patterns.filter(pat => pat.source !== regex.source);
92
- } catch (e) {
93
- console.error(`[opencode-attention] Invalid exclude pattern "${p}":`, e.message);
94
- }
219
+ // Extract the current viewport, ANSI-stripped, one entry per screen line.
220
+ //
221
+ // Prefers the cheap viewport-only serialization; getTerminalState() is a
222
+ // fallback for older hosts (it serializes the entire scrollback and
223
+ // returns null once that exceeds its size guard).
224
+ _getViewportLines(sessionId) {
225
+ let state = null;
226
+ if (typeof this.ctx.getTerminalViewport === 'function') {
227
+ state = this.ctx.getTerminalViewport(sessionId);
95
228
  }
229
+ if (!state || !state.state) {
230
+ state = this.ctx.getTerminalState(sessionId);
231
+ }
232
+ if (!state || !state.state) return null;
96
233
 
97
- return patterns;
98
- }
234
+ const rows = state.rows || 24;
235
+ let text = state.state;
99
236
 
100
- _matchesPattern(text) {
101
- for (const pattern of this.patterns) {
102
- if (pattern.test(text)) return true;
237
+ // OpenCode's TUI runs on the alternate buffer, which the serializer
238
+ // appends after a `\x1b[?1049h` marker — everything before it is the
239
+ // scrolled-away normal buffer, not what the user is looking at.
240
+ const altMarker = text.lastIndexOf('\x1b[?1049h');
241
+ if (altMarker !== -1) {
242
+ text = text.slice(altMarker);
103
243
  }
104
- return false;
105
- }
106
244
 
107
- _stripAnsi(str) {
108
- return str
109
- .replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '')
110
- .replace(/\x1b\][^\x07]*\x07/g, '')
111
- .replace(/\x1b\[\?[0-9]+[hl]/g, '')
112
- .replace(/\x1b[\(\)]B/g, '')
113
- .replace(/\x1b[0-9;]*[a-zA-Z]/g, '')
114
- .replace(/\x1b[^[\]()?P]/g, '')
115
- .replace(/[\x00-\x08\x0b\x0c\x0d\x0e-\x1f\x7f]/g, '')
116
- .trim();
245
+ const lines = text.split('\n');
246
+ const viewport = lines.slice(-rows);
247
+ return viewport.map(l => this._stripAnsi(l));
117
248
  }
118
249
 
119
- _startFlash(sessionId) {
120
- const sessionState = this._getSessionState(sessionId);
121
- if (Date.now() < sessionState.cooldownUntil) return;
122
- if (this._isWorking(sessionId)) return;
123
- if (this._flashing.get(sessionId)) return;
250
+ _startFlash(sessionId, { force = false } = {}) {
251
+ const s = this._getSessionState(sessionId);
252
+ const now = Date.now();
253
+ // Suppressed for now — pendingAttention keeps it queued for a retry
254
+ // instead of dropping the event on the floor.
255
+ if (now < s.cooldownUntil) return;
256
+ if (now - s.lastUserInputAt < this.config.userEchoWindowMs) return;
257
+ // `force` is used for a fresh transition: re-emitting is harmless and
258
+ // recovers from a flash the client cleared without telling us.
259
+ if (!force && this._flashing.get(sessionId)) return;
124
260
  this._flashing.set(sessionId, true);
261
+ s.pendingAttention = false;
125
262
  this.ctx.flashTab(sessionId, { duration: this.config.flashDuration || 0 });
126
263
  }
127
264
 
128
- _stopFlash(sessionId) {
265
+ _stopFlash(sessionId, { cooldown = false } = {}) {
266
+ const s = this._getSessionState(sessionId);
267
+ if (cooldown) {
268
+ s.cooldownUntil = Date.now() + this.config.cooldownMs;
269
+ }
270
+ s.pendingAttention = false;
129
271
  if (!this._flashing.get(sessionId)) return;
130
272
  this._flashing.delete(sessionId);
131
273
  this.ctx.stopFlashTab(sessionId);
132
274
  }
133
275
 
134
- _scheduleCheck(sessionId) {
135
- if (this._dataTimers.has(sessionId)) return;
136
-
137
- const timer = setTimeout(() => {
138
- this._dataTimers.delete(sessionId);
139
- this._checkAttention(sessionId);
140
- }, this.config.debounceMs);
141
-
142
- this._dataTimers.set(sessionId, timer);
276
+ _resetSession(sessionId) {
277
+ this._stopFlash(sessionId);
278
+ this._sessionState.delete(sessionId);
279
+ this._clearTimer(this._dataTimers, sessionId);
280
+ this._clearTimer(this._idleTimers, sessionId);
143
281
  }
144
282
 
145
- _scheduleIdleCheck(sessionId) {
146
- const sessionState = this._getSessionState(sessionId);
147
- if (sessionState.idleCheckScheduled) return;
148
- sessionState.idleCheckScheduled = true;
149
-
150
- const delay = this.config.idleThreshold + 200;
151
-
152
- setTimeout(() => {
153
- sessionState.idleCheckScheduled = false;
154
- if (!sessionState.wasWorking) return;
155
- if (this._isWorking(sessionId)) return;
156
- this._checkAttention(sessionId);
157
- }, delay);
283
+ _clearTimer(map, sessionId) {
284
+ const timer = map.get(sessionId);
285
+ if (timer) {
286
+ clearTimeout(timer);
287
+ map.delete(sessionId);
288
+ }
158
289
  }
159
290
 
160
- _isSpinnerChar(text) {
161
- return /[⬝■▣]/.test(text);
291
+ _markWorking(s, sessionId) {
292
+ s.working = true;
293
+ s.workEpisode = true;
294
+ s.pendingAttention = false;
295
+ s.lastWorkSignalAt = Date.now();
296
+ // Re-evaluate as soon as the idle threshold could be met, so the flash
297
+ // doesn't wait for the next periodic check (up to checkInterval later).
298
+ this._clearTimer(this._idleTimers, sessionId);
299
+ this._idleTimers.set(sessionId, setTimeout(() => {
300
+ this._idleTimers.delete(sessionId);
301
+ this._evaluate(sessionId);
302
+ }, this.config.idleThreshold + 100));
162
303
  }
163
304
 
164
- _checkAttention(sessionId) {
165
- if (this._isWorking(sessionId)) return;
166
-
167
- const state = this.ctx.getTerminalState(sessionId);
168
- if (!state || !state.state) return;
169
-
170
- const lines = state.state.split('\n');
171
- const recentLines = lines.slice(-30);
305
+ // Core evaluation: reads the live viewport and drives the state machine.
306
+ _evaluate(sessionId) {
307
+ const viewport = this._getViewportLines(sessionId);
308
+ if (!viewport) return;
172
309
 
173
- let isOpencode = false;
174
- let matchedPrompt = false;
175
-
176
- for (const line of recentLines) {
177
- const stripped = this._stripAnsi(line);
178
- if (!stripped) continue;
179
-
180
- if (/OpenCode/i.test(stripped)) {
181
- isOpencode = true;
182
- }
310
+ const s = this._getSessionState(sessionId);
311
+ const now = Date.now();
183
312
 
184
- if (this._matchesPattern(stripped) || this._matchesPattern(line)) {
185
- matchedPrompt = true;
313
+ // 1) App presence (non-sticky, with a small miss streak so a single
314
+ // mid-redraw check can't reset state).
315
+ const appOnScreen = viewport.some(line => this._matchesAny(this._appPatterns, line));
316
+ if (appOnScreen) {
317
+ s.appVisible = true;
318
+ s.appMissStreak = 0;
319
+ } else {
320
+ s.appMissStreak++;
321
+ if (s.appMissStreak >= this.config.appMissLimit) {
322
+ // OpenCode is off screen: no NEW working episode may start. An
323
+ // already armed episode is kept on purpose — a dialog can hide
324
+ // every signature, and an agent that exited on its own still
325
+ // deserves its one flash. Anything the user did to leave the app
326
+ // went through onUserInput, which clears the episode.
327
+ s.appVisible = false;
328
+ s.working = false;
186
329
  }
187
330
  }
188
331
 
189
- const sessionState = this._getSessionState(sessionId);
190
- if (isOpencode) {
191
- sessionState.isOpencode = true;
332
+ // 2) Working indicator in the footer region, in two tiers:
333
+ // - a run hint ("esc to interrupt") is unambiguous and counts even
334
+ // on a completely quiet screen;
335
+ // - a bare spinner glyph only counts while output is actually
336
+ // flowing. A spinner that animates always produces output, so a
337
+ // glyph with a quiet stream is a LEFTOVER (the finished status
338
+ // line pushed up by a dialog, a braille graph, a progress bar).
339
+ // Treating those as "still working" is what kept sessions
340
+ // pinned in the working state and swallowed the flash.
341
+ const footer = viewport.slice(-this.config.footerLines);
342
+ const hintVisible = footer.some(line => this._matchesAny(this._workingHintPatterns, line));
343
+ const glyphVisible = !hintVisible &&
344
+ footer.some(line => this._matchesAny(this._workingPatterns, line));
345
+ const spinnerLive = (now - s.lastOutputAt) < this.config.spinnerStaleMs;
346
+ // Last resort against a permanently stuck "working" state: a run that
347
+ // is really in progress keeps repainting its elapsed-time counter, so
348
+ // a screen that has produced NOTHING for workStaleMs is showing a
349
+ // leftover, not a live run.
350
+ const outputStale = (now - s.lastOutputAt) > this.config.workStaleMs;
351
+ const workingVisible = s.appVisible && !outputStale &&
352
+ (hintVisible || (glyphVisible && spinnerLive));
353
+
354
+ if (workingVisible) {
355
+ const wasFlashing = this._flashing.get(sessionId) || s.pendingAttention;
356
+ this._markWorking(s, sessionId);
357
+ // Working resumed — anything currently flashing is stale.
358
+ if (wasFlashing) this._stopFlash(sessionId, { cooldown: true });
359
+ return;
192
360
  }
193
361
 
194
- if (!sessionState.isOpencode) return;
362
+ // 3) Idle transition: a working episode ended (indicator gone AND no
363
+ // work signal for idleThreshold) → the agent finished or is waiting
364
+ // on a dialog → flash.
365
+ if (s.workEpisode && (now - s.lastWorkSignalAt) >= this.config.idleThreshold) {
366
+ s.workEpisode = false;
367
+ s.working = false;
368
+ s.pendingAttention = true;
369
+ this._startFlash(sessionId, { force: true });
370
+ return;
371
+ }
195
372
 
196
- if (matchedPrompt) {
373
+ // 4) A transition that was suppressed (cooldown after a keystroke)
374
+ // stays queued and is retried until it goes out or the user shows up.
375
+ if (s.pendingAttention) {
197
376
  this._startFlash(sessionId);
198
377
  return;
199
378
  }
200
379
 
201
- const now = Date.now();
202
- const timeSinceSpinner = now - sessionState.lastSpinnerTime;
203
-
204
- if (sessionState.wasWorking && timeSinceSpinner > this.config.idleThreshold) {
205
- this._startFlash(sessionId);
206
- sessionState.wasWorking = false;
380
+ // 5) Optional custom attention patterns (config-supplied only),
381
+ // evaluated against the footer while idle.
382
+ if (s.appVisible && !s.working && this._attentionPatterns.length > 0) {
383
+ // Level-triggered (the pattern stays on screen), so the dedupe in
384
+ // _startFlash must apply — no force here.
385
+ if (footer.some(line => this._matchesAny(this._attentionPatterns, line))) {
386
+ this._startFlash(sessionId);
387
+ }
207
388
  }
208
389
  }
209
390
 
210
- onData(sessionId, data) {
211
- const stripped = this._stripAnsi(data);
212
- const sessionState = this._getSessionState(sessionId);
391
+ _scheduleEvaluate(sessionId) {
392
+ if (this._dataTimers.has(sessionId)) return;
393
+ const timer = setTimeout(() => {
394
+ this._dataTimers.delete(sessionId);
395
+ this._evaluate(sessionId);
396
+ }, this.config.debounceMs);
397
+ this._dataTimers.set(sessionId, timer);
398
+ }
213
399
 
214
- if (/OpenCode/i.test(stripped) || /OpenCode/i.test(data)) {
215
- sessionState.isOpencode = true;
400
+ onData(sessionId, data) {
401
+ const s = this._getSessionState(sessionId);
402
+ const now = Date.now();
403
+ s.lastOutputAt = now;
404
+
405
+ // Cheap inline work signal: spinner/indicator glyphs in the stream
406
+ // keep the working state fresh without waiting for a viewport check.
407
+ if (s.appVisible && this._matchesAny(this._workingPatterns, data)) {
408
+ const wasFlashing = this._flashing.get(sessionId) || s.pendingAttention;
409
+ this._markWorking(s, sessionId);
410
+ if (wasFlashing) this._stopFlash(sessionId, { cooldown: true });
411
+ return;
216
412
  }
217
413
 
218
- const isSpinner = this._isSpinnerChar(stripped) || this._isSpinnerChar(data);
219
-
220
- if (isSpinner) {
221
- sessionState.lastSpinnerTime = Date.now();
222
- sessionState.wasWorking = true;
223
- this._scheduleIdleCheck(sessionId);
224
- if (this._flashing.get(sessionId)) {
225
- this._stopFlash(sessionId);
226
- sessionState.cooldownUntil = Date.now() + this.config.cooldownMs;
414
+ // Agent-driven output heuristic: bytes arriving while the user hasn't
415
+ // typed recently. Echo/UI reactions to keystrokes don't count.
416
+ if (now - s.lastUserInputAt > this.config.userEchoWindowMs) {
417
+ if (now - s.agentWindowStart > this.config.workWindowMs) {
418
+ s.agentWindowStart = now;
419
+ s.agentBytes = 0;
420
+ }
421
+ s.agentBytes += data.length;
422
+ if (s.appVisible && s.agentBytes >= this.config.minWorkBytes) {
423
+ const wasFlashing = this._flashing.get(sessionId) || s.pendingAttention;
424
+ this._markWorking(s, sessionId);
425
+ if (wasFlashing) this._stopFlash(sessionId, { cooldown: true });
227
426
  }
228
- return;
229
427
  }
230
428
 
231
- if (!sessionState.isOpencode) return;
232
- if (this._isWorking(sessionId)) return;
233
-
234
- if (this._matchesPattern(stripped) || this._matchesPattern(data)) {
235
- this._startFlash(sessionId);
236
- } else {
237
- this._scheduleCheck(sessionId);
238
- }
429
+ // Debounced evaluation so a burst that ends (stream complete, dialog
430
+ // shown) is noticed quickly instead of waiting for the next interval.
431
+ this._scheduleEvaluate(sessionId);
239
432
  }
240
433
 
241
- onTerminalLine(sessionId, strippedLine, rawLine) {
242
- const sessionState = this._getSessionState(sessionId);
243
-
244
- if (/OpenCode/i.test(strippedLine)) {
245
- sessionState.isOpencode = true;
246
- }
247
-
248
- if (!sessionState.isOpencode) return;
249
- if (this._isWorking(sessionId)) return;
434
+ onUserInput(sessionId /*, data */) {
435
+ const s = this._getSessionState(sessionId);
436
+ s.lastUserInputAt = Date.now();
437
+ // The user is here — stop flashing and hold off for a while. The
438
+ // current episode is dropped as well: if the agent really is working,
439
+ // its next spinner frame re-arms it within milliseconds, and if the
440
+ // keystroke was the user quitting to a shell there is nothing left to
441
+ // announce.
442
+ s.workEpisode = false;
443
+ s.working = false;
444
+ this._stopFlash(sessionId, { cooldown: true });
445
+ }
250
446
 
251
- if (this._matchesPattern(strippedLine) || this._matchesPattern(rawLine)) {
252
- this._startFlash(sessionId);
253
- }
447
+ // A client reported the user is looking at this tab.
448
+ onSessionFocus(sessionId) {
449
+ this._stopFlash(sessionId, { cooldown: true });
254
450
  }
255
451
 
256
452
  onSessionConnect(sessionId) {
257
- this._sessionState.delete(sessionId);
453
+ this._resetSession(sessionId);
258
454
  this._flashing.delete(sessionId);
259
455
 
260
456
  const existingTimer = this._checkTimers.get(sessionId);
@@ -266,28 +462,21 @@ class OpenCodeAttentionPlugin {
266
462
  this._checkTimers.delete(sessionId);
267
463
  return;
268
464
  }
269
- this._checkAttention(sessionId);
465
+ this._evaluate(sessionId);
270
466
  }, this.config.checkInterval);
271
467
 
272
468
  this._checkTimers.set(sessionId, timer);
273
469
  }
274
470
 
275
471
  onSessionDisconnect(sessionId) {
276
- this._stopFlash(sessionId);
277
- this._sessionState.delete(sessionId);
472
+ this._resetSession(sessionId);
278
473
 
279
474
  const checkTimer = this._checkTimers.get(sessionId);
280
475
  if (checkTimer) {
281
476
  clearInterval(checkTimer);
282
477
  this._checkTimers.delete(sessionId);
283
478
  }
284
-
285
- const dataTimer = this._dataTimers.get(sessionId);
286
- if (dataTimer) {
287
- clearTimeout(dataTimer);
288
- this._dataTimers.delete(sessionId);
289
- }
290
479
  }
291
480
  }
292
481
 
293
- module.exports = OpenCodeAttentionPlugin;
482
+ module.exports = OpenCodeAttentionPlugin;