@lethevimlet/sshift 1.7.2 → 1.7.3

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lethevimlet/sshift",
3
- "version": "1.7.2",
3
+ "version": "1.7.3",
4
4
  "description": "Web-based SSH + SFTP terminal client with tabs and bookmarks",
5
5
  "main": "src/server/index.js",
6
6
  "bin": {
@@ -1,112 +1,165 @@
1
1
  /**
2
2
  * claude-attention Plugin
3
3
  *
4
- * Detects when Claude (https://claude.ai/claude-code) is waiting for user input
5
- * in an SSH terminal and flashes the tab to alert the user.
4
+ * Flashes the tab when Claude Code (https://claude.ai/claude-code) finishes
5
+ * working and is waiting for the user (reply complete, or a permission
6
+ * dialog like "Do you want to make this edit?").
6
7
  *
7
- * Detection strategy:
8
- * - Detects Claude's TUI by looking for "Claude" in the terminal state (sticky: once detected, stays true)
9
- * - Tracks Claude's processing state via spinner characters (⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⠽⠛ ·✢✳✶✻✽)
10
- * - While Claude is working (spinner seen within idleThreshold), ALL flashing is suppressed
11
- * - When Claude 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 Claude-specific prompt patterns ("❯", "Do you want", "Allow", "Esc to cancel")
14
- * - Prompt detection only activates in confirmed Claude sessions (isClaude 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: Claude Code is considered present only
11
+ * while one of its UI signatures is visible in the CURRENT viewport of
12
+ * the headless terminal ("Claude", the "? for shortcuts" footer hint,
13
+ * "esc to interrupt", edit-mode hints). When the user exits back to a
14
+ * shell the signatures disappear and, after a few misses, all state
15
+ * resets — so a shell prompt can never flash the tab (the old sticky
16
+ * flag caused exactly that).
17
+ *
18
+ * 2. "Working" is tracked from two signals:
19
+ * - working indicators visible in the viewport footer (braille
20
+ * spinner glyphs, the ✢✳✶✻✽ sparkle spinner frames, and the
21
+ * "esc to interrupt" hint Claude Code shows while running), and
22
+ * - sustained agent-driven output: bytes that arrive while the user
23
+ * has NOT typed recently (echo/UI responses to keystrokes are
24
+ * ignored via userEchoWindowMs).
25
+ * NOTE: "·" is deliberately NOT a spinner char anymore — it appears in
26
+ * every status line ("3.2k tokens · esc to interrupt") and made the
27
+ * old working-detection fire on ordinary output.
28
+ *
29
+ * 3. The tab flashes ONLY on the working → idle TRANSITION: a working
30
+ * episode was observed, the working indicator is gone, and no work
31
+ * signal has been seen for idleThreshold ms. A finished reply and a
32
+ * permission dialog both look like this transition, so no brittle
33
+ * prompt regexes ("❯", "Do you want", "allow", ...) are needed.
34
+ *
35
+ * 4. User input (keystrokes) stops an active flash immediately and
36
+ * suppresses flashing for cooldownMs — the user is already there.
37
+ *
38
+ * There are NO default attention text patterns: strings like "(y/n)",
39
+ * "allow" or "❯ " routinely appear inside chat prose, code and shell
40
+ * prompts and caused constant false flashes. Custom `patterns` from the
41
+ * config are still honored, but they are only evaluated while Claude is on
42
+ * screen and not working.
16
43
  *
17
44
  * 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)
45
+ * - flashDuration: number - Flash duration in ms, 0 = flash until focused (default: 0)
46
+ * - checkInterval: number - Milliseconds between periodic viewport checks (default: 2000)
47
+ * - idleThreshold: number - Milliseconds without a work signal before Claude
48
+ * is considered idle/finished (default: 2500)
49
+ * - cooldownMs: number - Milliseconds to suppress flashing after user input
50
+ * or after a flash stops (default: 3000)
51
+ * - debounceMs: number - Debounce for output-driven evaluations (default: 300)
52
+ * - footerLines: number - Viewport bottom lines scanned for working
53
+ * indicators / custom patterns (default: 8)
54
+ * - userEchoWindowMs: number - Output arriving within this window after a
55
+ * keystroke counts as echo, not agent work (default: 1200)
56
+ * - minWorkBytes: number - Agent-driven bytes within workWindowMs that
57
+ * mark the session as working (default: 600)
58
+ * - workWindowMs: number - Rolling window for minWorkBytes (default: 2000)
59
+ * - appMissLimit: number - Consecutive viewport checks without an app
60
+ * signature before state resets (default: 3)
61
+ * - appPatterns: string[] - Regexes replacing the default app signatures
62
+ * - workingPatterns: string[] - Regexes replacing the default working indicators
63
+ * - patterns: string[] - Extra attention regexes (footer lines, idle only)
64
+ * - excludePatterns: string[] - Remove patterns (by source) from all lists
25
65
  */
26
66
 
27
67
  class ClaudeAttentionPlugin {
28
68
  constructor(ctx, config = {}) {
29
69
  this.ctx = ctx;
30
70
  this.config = {
31
- debounceMs: config.debounceMs || 300,
32
71
  flashDuration: config.flashDuration || 0,
33
72
  checkInterval: config.checkInterval || 2000,
34
- idleThreshold: config.idleThreshold || 3000,
35
- cooldownMs: config.cooldownMs || 1000,
36
- ...config,
73
+ idleThreshold: config.idleThreshold || 2500,
74
+ cooldownMs: config.cooldownMs || 3000,
75
+ debounceMs: config.debounceMs || 300,
76
+ footerLines: config.footerLines || 8,
77
+ userEchoWindowMs: config.userEchoWindowMs || 1200,
78
+ minWorkBytes: config.minWorkBytes || 600,
79
+ workWindowMs: config.workWindowMs || 2000,
80
+ appMissLimit: config.appMissLimit || 3,
37
81
  };
38
82
 
39
- this.patterns = this._buildPatterns(config.patterns || [], config.excludePatterns || []);
83
+ // App signatures. Claude Code's welcome box scrolls away in long
84
+ // sessions, so alongside the case-SENSITIVE "Claude" wordmark (keeps
85
+ // lowercase shell text like `cd claude-project` from arming the
86
+ // engine) we accept the persistent footer hints. A false positive
87
+ // here only ARMS the engine; a flash still requires a real
88
+ // working → idle transition.
89
+ this._appPatterns = this._compileList(
90
+ config.appPatterns || [
91
+ 'Claude',
92
+ '\\? for shortcuts',
93
+ 'esc to interrupt',
94
+ 'accept edits',
95
+ 'plan mode',
96
+ 'bypass permissions',
97
+ ],
98
+ 'appPatterns',
99
+ '' // case-sensitive
100
+ );
101
+
102
+ // Working indicators, scanned over the viewport footer only:
103
+ // - the full braille block (U+2800–U+28FF) covers braille spinners,
104
+ // - ✢✳✶✻✽∗ are Claude Code's sparkle spinner frames,
105
+ // - "esc to interrupt" is shown for the whole duration of a run.
106
+ this._workingPatterns = this._compileList(
107
+ config.workingPatterns || [
108
+ '[\\u2800-\\u28FF]',
109
+ '[✢✳✶✻✽∗]',
110
+ 'esc to interrupt',
111
+ ],
112
+ 'workingPatterns'
113
+ );
114
+
115
+ // Optional user-supplied attention patterns (none by default).
116
+ this._attentionPatterns = this._compileList(config.patterns || [], 'patterns');
117
+
118
+ // excludePatterns removes entries (matched by regex source) from all lists.
119
+ for (const p of (config.excludePatterns || [])) {
120
+ try {
121
+ const source = new RegExp(p).source;
122
+ this._appPatterns = this._appPatterns.filter(r => r.source !== source);
123
+ this._workingPatterns = this._workingPatterns.filter(r => r.source !== source);
124
+ this._attentionPatterns = this._attentionPatterns.filter(r => r.source !== source);
125
+ } catch (e) {
126
+ console.error(`[claude-attention] Invalid exclude pattern "${p}":`, e.message);
127
+ }
128
+ }
40
129
 
41
- this._dataTimers = new Map();
130
+ this._sessionState = new Map();
42
131
  this._checkTimers = new Map();
132
+ this._dataTimers = new Map();
43
133
  this._flashing = new Map();
44
- this._sessionState = new Map();
134
+ }
135
+
136
+ _compileList(list, label, flags = 'i') {
137
+ const out = [];
138
+ for (const p of list) {
139
+ try { out.push(new RegExp(p, flags)); } catch (e) {
140
+ console.error(`[claude-attention] Invalid ${label} regex "${p}":`, e.message);
141
+ }
142
+ }
143
+ return out;
45
144
  }
46
145
 
47
146
  _getSessionState(sessionId) {
48
147
  if (!this._sessionState.has(sessionId)) {
49
148
  this._sessionState.set(sessionId, {
50
- isClaude: false,
51
- lastSpinnerTime: 0,
52
- wasWorking: false,
149
+ appVisible: false, // signature currently on screen
150
+ appMissStreak: 0, // consecutive checks without a signature
151
+ working: false, // inside a working episode
152
+ lastWorkSignalAt: 0, // last time any work signal was seen
153
+ lastUserInputAt: 0, // last user keystroke
154
+ lastOutputAt: 0, // last output of any kind
155
+ agentBytes: 0, // agent-driven bytes in the rolling window
156
+ agentWindowStart: 0,
53
157
  cooldownUntil: 0,
54
- idleCheckScheduled: false,
55
158
  });
56
159
  }
57
160
  return this._sessionState.get(sessionId);
58
161
  }
59
162
 
60
- _isWorking(sessionId) {
61
- const s = this._getSessionState(sessionId);
62
- return s.wasWorking && (Date.now() - s.lastSpinnerTime) < this.config.idleThreshold;
63
- }
64
-
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
- /do you want/i,
79
- /allow/i,
80
- /Esc to cancel/i,
81
- ];
82
-
83
- let patterns = [...defaultPatterns];
84
-
85
- for (const p of extraPatterns) {
86
- try { patterns.push(new RegExp(p)); } catch (e) {
87
- console.error(`[claude-attention] Invalid pattern "${p}":`, e.message);
88
- }
89
- }
90
-
91
- for (const p of excludePatterns) {
92
- try {
93
- const regex = new RegExp(p);
94
- patterns = patterns.filter(pat => pat.source !== regex.source);
95
- } catch (e) {
96
- console.error(`[claude-attention] Invalid exclude pattern "${p}":`, e.message);
97
- }
98
- }
99
-
100
- return patterns;
101
- }
102
-
103
- _matchesPattern(text) {
104
- for (const pattern of this.patterns) {
105
- if (pattern.test(text)) return true;
106
- }
107
- return false;
108
- }
109
-
110
163
  _stripAnsi(str) {
111
164
  return str
112
165
  .replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '')
@@ -115,149 +168,174 @@ class ClaudeAttentionPlugin {
115
168
  .replace(/\x1b[\(\)]B/g, '')
116
169
  .replace(/\x1b[0-9;]*[a-zA-Z]/g, '')
117
170
  .replace(/\x1b[^[\]()?P]/g, '')
118
- .replace(/[\x00-\x08\x0b\x0c\x0d\x0e-\x1f\x7f]/g, '')
119
- .trim();
171
+ .replace(/[\x00-\x08\x0b\x0c\x0d\x0e-\x1f\x7f]/g, '');
172
+ }
173
+
174
+ _matchesAny(patterns, text) {
175
+ for (const p of patterns) {
176
+ if (p.test(text)) return true;
177
+ }
178
+ return false;
179
+ }
180
+
181
+ // Extract the current viewport (last `rows` lines) from the serialized
182
+ // terminal state, ANSI-stripped, one entry per screen line.
183
+ _getViewportLines(sessionId) {
184
+ const state = this.ctx.getTerminalState(sessionId);
185
+ if (!state || !state.state) return null;
186
+ const rows = state.rows || 24;
187
+ const lines = state.state.split('\n');
188
+ const viewport = lines.slice(-rows);
189
+ return viewport.map(l => this._stripAnsi(l));
120
190
  }
121
191
 
122
192
  _startFlash(sessionId) {
123
- const sessionState = this._getSessionState(sessionId);
124
- if (Date.now() < sessionState.cooldownUntil) return;
125
- if (this._isWorking(sessionId)) return;
193
+ const s = this._getSessionState(sessionId);
194
+ const now = Date.now();
195
+ if (now < s.cooldownUntil) return;
196
+ if (now - s.lastUserInputAt < this.config.userEchoWindowMs) return;
126
197
  if (this._flashing.get(sessionId)) return;
127
198
  this._flashing.set(sessionId, true);
128
199
  this.ctx.flashTab(sessionId, { duration: this.config.flashDuration || 0 });
129
200
  }
130
201
 
131
- _stopFlash(sessionId) {
202
+ _stopFlash(sessionId, { cooldown = false } = {}) {
203
+ if (cooldown) {
204
+ const s = this._getSessionState(sessionId);
205
+ s.cooldownUntil = Date.now() + this.config.cooldownMs;
206
+ }
132
207
  if (!this._flashing.get(sessionId)) return;
133
208
  this._flashing.delete(sessionId);
134
209
  this.ctx.stopFlashTab(sessionId);
135
210
  }
136
211
 
137
- _scheduleCheck(sessionId) {
138
- if (this._dataTimers.has(sessionId)) return;
139
-
140
- const timer = setTimeout(() => {
212
+ _resetSession(sessionId) {
213
+ this._stopFlash(sessionId);
214
+ this._sessionState.delete(sessionId);
215
+ const dataTimer = this._dataTimers.get(sessionId);
216
+ if (dataTimer) {
217
+ clearTimeout(dataTimer);
141
218
  this._dataTimers.delete(sessionId);
142
- this._checkAttention(sessionId);
143
- }, this.config.debounceMs);
144
-
145
- this._dataTimers.set(sessionId, timer);
146
- }
147
-
148
- _scheduleIdleCheck(sessionId) {
149
- const sessionState = this._getSessionState(sessionId);
150
- if (sessionState.idleCheckScheduled) return;
151
- sessionState.idleCheckScheduled = true;
152
-
153
- const delay = this.config.idleThreshold + 200;
154
-
155
- setTimeout(() => {
156
- sessionState.idleCheckScheduled = false;
157
- if (!sessionState.wasWorking) return;
158
- if (this._isWorking(sessionId)) return;
159
- this._checkAttention(sessionId);
160
- }, delay);
219
+ }
161
220
  }
162
221
 
163
- _isSpinnerChar(text) {
164
- return /[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏⠽⠛·✢✳✶✻✽]/.test(text);
222
+ _markWorking(s) {
223
+ const now = Date.now();
224
+ s.working = true;
225
+ s.lastWorkSignalAt = now;
165
226
  }
166
227
 
167
- _checkAttention(sessionId) {
168
- if (this._isWorking(sessionId)) return;
169
-
170
- const state = this.ctx.getTerminalState(sessionId);
171
- if (!state || !state.state) return;
228
+ // Core evaluation: reads the live viewport and drives the state machine.
229
+ _evaluate(sessionId) {
230
+ const viewport = this._getViewportLines(sessionId);
231
+ if (!viewport) return;
172
232
 
173
- const lines = state.state.split('\n');
174
- const recentLines = lines.slice(-30);
175
-
176
- let foundClaude = false;
177
- let matchedPrompt = false;
178
-
179
- for (const line of recentLines) {
180
- const stripped = this._stripAnsi(line);
181
- if (!stripped) continue;
182
-
183
- if (/Claude/i.test(stripped)) {
184
- foundClaude = true;
185
- }
233
+ const s = this._getSessionState(sessionId);
234
+ const now = Date.now();
186
235
 
187
- if (this._matchesPattern(stripped) || this._matchesPattern(line)) {
188
- matchedPrompt = true;
236
+ // 1) App presence (non-sticky, with a small miss streak so a single
237
+ // mid-redraw check can't reset state).
238
+ const appOnScreen = viewport.some(line => this._matchesAny(this._appPatterns, line));
239
+ if (appOnScreen) {
240
+ s.appVisible = true;
241
+ s.appMissStreak = 0;
242
+ } else {
243
+ s.appMissStreak++;
244
+ if (s.appMissStreak >= this.config.appMissLimit) {
245
+ // Claude left the screen (user exited to shell, switched apps).
246
+ const wasFlashing = this._flashing.get(sessionId);
247
+ s.appVisible = false;
248
+ s.working = false;
249
+ if (wasFlashing) this._stopFlash(sessionId);
189
250
  }
251
+ return;
190
252
  }
191
253
 
192
- const sessionState = this._getSessionState(sessionId);
193
- if (foundClaude) {
194
- sessionState.isClaude = true;
195
- }
254
+ // 2) Working indicator in the footer region.
255
+ const footer = viewport.slice(-this.config.footerLines);
256
+ const workingVisible = footer.some(line => this._matchesAny(this._workingPatterns, line));
196
257
 
197
- if (!sessionState.isClaude) return;
258
+ if (workingVisible) {
259
+ this._markWorking(s);
260
+ // Working resumed — anything currently flashing is stale.
261
+ if (this._flashing.get(sessionId)) {
262
+ this._stopFlash(sessionId, { cooldown: true });
263
+ }
264
+ return;
265
+ }
198
266
 
199
- if (matchedPrompt) {
267
+ // 3) Idle transition: a working episode ended (indicator gone AND no
268
+ // work signal for idleThreshold) → the reply finished or a
269
+ // permission dialog is waiting → flash.
270
+ if (s.working && (now - s.lastWorkSignalAt) >= this.config.idleThreshold) {
271
+ s.working = false;
200
272
  this._startFlash(sessionId);
201
273
  return;
202
274
  }
203
275
 
204
- const now = Date.now();
205
- const timeSinceSpinner = now - sessionState.lastSpinnerTime;
206
-
207
- if (sessionState.wasWorking && timeSinceSpinner > this.config.idleThreshold) {
208
- this._startFlash(sessionId);
209
- sessionState.wasWorking = false;
276
+ // 4) Optional custom attention patterns (config-supplied only),
277
+ // evaluated against the footer while idle.
278
+ if (!s.working && this._attentionPatterns.length > 0) {
279
+ if (footer.some(line => this._matchesAny(this._attentionPatterns, line))) {
280
+ this._startFlash(sessionId);
281
+ }
210
282
  }
211
283
  }
212
284
 
213
- onData(sessionId, data) {
214
- const stripped = this._stripAnsi(data);
215
- const sessionState = this._getSessionState(sessionId);
216
-
217
- if (/Claude/i.test(stripped) || /Claude/i.test(data)) {
218
- sessionState.isClaude = true;
219
- }
285
+ _scheduleEvaluate(sessionId) {
286
+ if (this._dataTimers.has(sessionId)) return;
287
+ const timer = setTimeout(() => {
288
+ this._dataTimers.delete(sessionId);
289
+ this._evaluate(sessionId);
290
+ }, this.config.debounceMs);
291
+ this._dataTimers.set(sessionId, timer);
292
+ }
220
293
 
221
- const isSpinner = this._isSpinnerChar(stripped) || this._isSpinnerChar(data);
294
+ onData(sessionId, data) {
295
+ const s = this._getSessionState(sessionId);
296
+ const now = Date.now();
297
+ s.lastOutputAt = now;
222
298
 
223
- if (isSpinner) {
224
- sessionState.lastSpinnerTime = Date.now();
225
- sessionState.wasWorking = true;
226
- this._scheduleIdleCheck(sessionId);
299
+ // Cheap inline work signal: spinner/indicator glyphs in the stream
300
+ // keep the working state fresh without waiting for a viewport check.
301
+ if (s.appVisible && this._matchesAny(this._workingPatterns, data)) {
302
+ this._markWorking(s);
227
303
  if (this._flashing.get(sessionId)) {
228
- this._stopFlash(sessionId);
229
- sessionState.cooldownUntil = Date.now() + this.config.cooldownMs;
304
+ this._stopFlash(sessionId, { cooldown: true });
230
305
  }
231
306
  return;
232
307
  }
233
308
 
234
- if (!sessionState.isClaude) return;
235
- if (this._isWorking(sessionId)) return;
236
-
237
- if (this._matchesPattern(stripped) || this._matchesPattern(data)) {
238
- this._startFlash(sessionId);
239
- } else {
240
- this._scheduleCheck(sessionId);
241
- }
242
- }
243
-
244
- onTerminalLine(sessionId, strippedLine, rawLine) {
245
- const sessionState = this._getSessionState(sessionId);
246
-
247
- if (/Claude/i.test(strippedLine)) {
248
- sessionState.isClaude = true;
309
+ // Agent-driven output heuristic: bytes arriving while the user hasn't
310
+ // typed recently. Echo/UI reactions to keystrokes don't count.
311
+ if (now - s.lastUserInputAt > this.config.userEchoWindowMs) {
312
+ if (now - s.agentWindowStart > this.config.workWindowMs) {
313
+ s.agentWindowStart = now;
314
+ s.agentBytes = 0;
315
+ }
316
+ s.agentBytes += data.length;
317
+ if (s.appVisible && s.agentBytes >= this.config.minWorkBytes) {
318
+ this._markWorking(s);
319
+ if (this._flashing.get(sessionId)) {
320
+ this._stopFlash(sessionId, { cooldown: true });
321
+ }
322
+ }
249
323
  }
250
324
 
251
- if (!sessionState.isClaude) return;
252
- if (this._isWorking(sessionId)) return;
325
+ // Debounced evaluation so a burst that ends (stream complete, dialog
326
+ // shown) is noticed quickly instead of waiting for the next interval.
327
+ this._scheduleEvaluate(sessionId);
328
+ }
253
329
 
254
- if (this._matchesPattern(strippedLine) || this._matchesPattern(rawLine)) {
255
- this._startFlash(sessionId);
256
- }
330
+ onUserInput(sessionId /*, data */) {
331
+ const s = this._getSessionState(sessionId);
332
+ s.lastUserInputAt = Date.now();
333
+ // The user is here — stop flashing and hold off for a while.
334
+ this._stopFlash(sessionId, { cooldown: true });
257
335
  }
258
336
 
259
337
  onSessionConnect(sessionId) {
260
- this._sessionState.delete(sessionId);
338
+ this._resetSession(sessionId);
261
339
  this._flashing.delete(sessionId);
262
340
 
263
341
  const existingTimer = this._checkTimers.get(sessionId);
@@ -269,28 +347,21 @@ class ClaudeAttentionPlugin {
269
347
  this._checkTimers.delete(sessionId);
270
348
  return;
271
349
  }
272
- this._checkAttention(sessionId);
350
+ this._evaluate(sessionId);
273
351
  }, this.config.checkInterval);
274
352
 
275
353
  this._checkTimers.set(sessionId, timer);
276
354
  }
277
355
 
278
356
  onSessionDisconnect(sessionId) {
279
- this._stopFlash(sessionId);
280
- this._sessionState.delete(sessionId);
357
+ this._resetSession(sessionId);
281
358
 
282
359
  const checkTimer = this._checkTimers.get(sessionId);
283
360
  if (checkTimer) {
284
361
  clearInterval(checkTimer);
285
362
  this._checkTimers.delete(sessionId);
286
363
  }
287
-
288
- const dataTimer = this._dataTimers.get(sessionId);
289
- if (dataTimer) {
290
- clearTimeout(dataTimer);
291
- this._dataTimers.delete(sessionId);
292
- }
293
364
  }
294
365
  }
295
366
 
296
- module.exports = ClaudeAttentionPlugin;
367
+ module.exports = ClaudeAttentionPlugin;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-attention",
3
- "version": "1.0.0",
4
- "description": "Flashes SSH tabs when Claude is waiting for user input",
3
+ "version": "2.0.0",
4
+ "description": "Flashes SSH tabs when Claude Code finishes working and is waiting for you (state-transition detection, no brittle prompt patterns)",
5
5
  "type": "sshift-plugin"
6
- }
6
+ }
@@ -1,109 +1,153 @@
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/question dialog).
6
6
  *
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
7
+ * Detection strategy (state-transition based, not text-pattern based):
8
+ *
9
+ * 1. App detection is NON-STICKY: OpenCode is considered present only
10
+ * while its UI signature (the "OpenCode" wordmark in the status bar /
11
+ * splash) is visible in the CURRENT viewport of the headless terminal.
12
+ * When the user exits back to a shell, the signature disappears and,
13
+ * after a few misses, all state resets — so a shell prompt like "❯ "
14
+ * can never flash the tab (the old sticky flag caused exactly that).
15
+ *
16
+ * 2. "Working" is tracked from two signals:
17
+ * - working indicators visible in the viewport footer (braille
18
+ * spinner glyphs, legacy ⬝■▣ spinners, "esc to interrupt"), and
19
+ * - sustained agent-driven output: bytes that arrive while the user
20
+ * has NOT typed recently (echo/UI responses to keystrokes are
21
+ * ignored via userEchoWindowMs).
22
+ *
23
+ * 3. The tab flashes ONLY on the working → idle TRANSITION: a working
24
+ * episode was observed, the working indicator is gone, and no work
25
+ * signal has been seen for idleThreshold ms. A finished reply and a
26
+ * confirmation dialog both look like this transition, so no brittle
27
+ * prompt regexes are needed.
28
+ *
29
+ * 4. User input (keystrokes) stops an active flash immediately and
30
+ * suppresses flashing for cooldownMs — the user is already there.
31
+ *
32
+ * There are NO default attention text patterns: strings like "(y/n)",
33
+ * "press enter" or "❯ " routinely appear inside chat prose, code and shell
34
+ * prompts and caused constant false flashes. Custom `patterns` from the
35
+ * config are still honored, but they are only evaluated while OpenCode is
36
+ * on screen and not working.
16
37
  *
17
38
  * 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)
39
+ * - flashDuration: number - Flash duration in ms, 0 = flash until focused (default: 0)
40
+ * - checkInterval: number - Milliseconds between periodic viewport checks (default: 2000)
41
+ * - idleThreshold: number - Milliseconds without a work signal before OpenCode
42
+ * is considered idle/finished (default: 2500)
43
+ * - cooldownMs: number - Milliseconds to suppress flashing after user input
44
+ * or after a flash stops (default: 3000)
45
+ * - debounceMs: number - Debounce for output-driven evaluations (default: 300)
46
+ * - footerLines: number - Viewport bottom lines scanned for working
47
+ * indicators / custom patterns (default: 8)
48
+ * - userEchoWindowMs: number - Output arriving within this window after a
49
+ * keystroke counts as echo, not agent work (default: 1200)
50
+ * - minWorkBytes: number - Agent-driven bytes within workWindowMs that
51
+ * mark the session as working (default: 600)
52
+ * - workWindowMs: number - Rolling window for minWorkBytes (default: 2000)
53
+ * - appMissLimit: number - Consecutive viewport checks without the app
54
+ * signature before state resets (default: 3)
55
+ * - appPatterns: string[] - Regexes replacing the default app signature
56
+ * - workingPatterns: string[] - Regexes replacing the default working indicators
57
+ * - patterns: string[] - Extra attention regexes (footer lines, idle only)
58
+ * - excludePatterns: string[] - Remove patterns (by source) from all lists
25
59
  */
26
60
 
27
61
  class OpenCodeAttentionPlugin {
28
62
  constructor(ctx, config = {}) {
29
63
  this.ctx = ctx;
30
64
  this.config = {
31
- debounceMs: config.debounceMs || 300,
32
65
  flashDuration: config.flashDuration || 0,
33
66
  checkInterval: config.checkInterval || 2000,
34
- idleThreshold: config.idleThreshold || 3000,
35
- cooldownMs: config.cooldownMs || 1000,
36
- ...config,
67
+ idleThreshold: config.idleThreshold || 2500,
68
+ cooldownMs: config.cooldownMs || 3000,
69
+ debounceMs: config.debounceMs || 300,
70
+ footerLines: config.footerLines || 8,
71
+ userEchoWindowMs: config.userEchoWindowMs || 1200,
72
+ minWorkBytes: config.minWorkBytes || 600,
73
+ workWindowMs: config.workWindowMs || 2000,
74
+ appMissLimit: config.appMissLimit || 3,
37
75
  };
38
76
 
39
- this.patterns = this._buildPatterns(config.patterns || [], config.excludePatterns || []);
77
+ // App signature: the OpenCode TUI always renders its wordmark (status
78
+ // bar "OpenCode x.y.z", splash logo). Case-SENSITIVE on purpose so
79
+ // lowercase shell text (`cd opencode`, paths, package names) can't arm
80
+ // the engine — and even a false positive here only ARMS it; a flash
81
+ // still requires a real working → idle transition.
82
+ this._appPatterns = this._compileList(
83
+ config.appPatterns || ['OpenCode'],
84
+ 'appPatterns',
85
+ '' // case-sensitive
86
+ );
87
+
88
+ // Working indicators, scanned over the viewport footer only:
89
+ // - the full braille block (U+2800–U+28FF) covers every braille
90
+ // spinner variant across OpenCode versions,
91
+ // - ⬝■▣ are the legacy OpenCode spinner frames,
92
+ // - "esc to interrupt"-style hints cover text-based indicators.
93
+ this._workingPatterns = this._compileList(
94
+ config.workingPatterns || [
95
+ '[\\u2800-\\u28FF]',
96
+ '[⬝■▣]',
97
+ 'esc to interrupt',
98
+ 'esc interrupt',
99
+ ],
100
+ 'workingPatterns'
101
+ );
102
+
103
+ // Optional user-supplied attention patterns (none by default).
104
+ this._attentionPatterns = this._compileList(config.patterns || [], 'patterns');
105
+
106
+ // excludePatterns removes entries (matched by regex source) from all lists.
107
+ for (const p of (config.excludePatterns || [])) {
108
+ try {
109
+ const source = new RegExp(p).source;
110
+ this._appPatterns = this._appPatterns.filter(r => r.source !== source);
111
+ this._workingPatterns = this._workingPatterns.filter(r => r.source !== source);
112
+ this._attentionPatterns = this._attentionPatterns.filter(r => r.source !== source);
113
+ } catch (e) {
114
+ console.error(`[opencode-attention] Invalid exclude pattern "${p}":`, e.message);
115
+ }
116
+ }
40
117
 
41
- this._dataTimers = new Map();
118
+ this._sessionState = new Map();
42
119
  this._checkTimers = new Map();
120
+ this._dataTimers = new Map();
43
121
  this._flashing = new Map();
44
- this._sessionState = new Map();
122
+ }
123
+
124
+ _compileList(list, label, flags = 'i') {
125
+ const out = [];
126
+ for (const p of list) {
127
+ try { out.push(new RegExp(p, flags)); } catch (e) {
128
+ console.error(`[opencode-attention] Invalid ${label} regex "${p}":`, e.message);
129
+ }
130
+ }
131
+ return out;
45
132
  }
46
133
 
47
134
  _getSessionState(sessionId) {
48
135
  if (!this._sessionState.has(sessionId)) {
49
136
  this._sessionState.set(sessionId, {
50
- isOpencode: false,
51
- lastSpinnerTime: 0,
52
- wasWorking: false,
137
+ appVisible: false, // signature currently on screen
138
+ appMissStreak: 0, // consecutive checks without the signature
139
+ working: false, // inside a working episode
140
+ lastWorkSignalAt: 0, // last time any work signal was seen
141
+ lastUserInputAt: 0, // last user keystroke
142
+ lastOutputAt: 0, // last output of any kind
143
+ agentBytes: 0, // agent-driven bytes in the rolling window
144
+ agentWindowStart: 0,
53
145
  cooldownUntil: 0,
54
- idleCheckScheduled: false,
55
146
  });
56
147
  }
57
148
  return this._sessionState.get(sessionId);
58
149
  }
59
150
 
60
- _isWorking(sessionId) {
61
- const s = this._getSessionState(sessionId);
62
- return s.wasWorking && (Date.now() - s.lastSpinnerTime) < this.config.idleThreshold;
63
- }
64
-
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
- }
86
- }
87
-
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
- }
95
- }
96
-
97
- return patterns;
98
- }
99
-
100
- _matchesPattern(text) {
101
- for (const pattern of this.patterns) {
102
- if (pattern.test(text)) return true;
103
- }
104
- return false;
105
- }
106
-
107
151
  _stripAnsi(str) {
108
152
  return str
109
153
  .replace(/\x1b\[[0-9;]*[a-zA-Z]/g, '')
@@ -112,149 +156,174 @@ class OpenCodeAttentionPlugin {
112
156
  .replace(/\x1b[\(\)]B/g, '')
113
157
  .replace(/\x1b[0-9;]*[a-zA-Z]/g, '')
114
158
  .replace(/\x1b[^[\]()?P]/g, '')
115
- .replace(/[\x00-\x08\x0b\x0c\x0d\x0e-\x1f\x7f]/g, '')
116
- .trim();
159
+ .replace(/[\x00-\x08\x0b\x0c\x0d\x0e-\x1f\x7f]/g, '');
160
+ }
161
+
162
+ _matchesAny(patterns, text) {
163
+ for (const p of patterns) {
164
+ if (p.test(text)) return true;
165
+ }
166
+ return false;
167
+ }
168
+
169
+ // Extract the current viewport (last `rows` lines) from the serialized
170
+ // terminal state, ANSI-stripped, one entry per screen line.
171
+ _getViewportLines(sessionId) {
172
+ const state = this.ctx.getTerminalState(sessionId);
173
+ if (!state || !state.state) return null;
174
+ const rows = state.rows || 24;
175
+ const lines = state.state.split('\n');
176
+ const viewport = lines.slice(-rows);
177
+ return viewport.map(l => this._stripAnsi(l));
117
178
  }
118
179
 
119
180
  _startFlash(sessionId) {
120
- const sessionState = this._getSessionState(sessionId);
121
- if (Date.now() < sessionState.cooldownUntil) return;
122
- if (this._isWorking(sessionId)) return;
181
+ const s = this._getSessionState(sessionId);
182
+ const now = Date.now();
183
+ if (now < s.cooldownUntil) return;
184
+ if (now - s.lastUserInputAt < this.config.userEchoWindowMs) return;
123
185
  if (this._flashing.get(sessionId)) return;
124
186
  this._flashing.set(sessionId, true);
125
187
  this.ctx.flashTab(sessionId, { duration: this.config.flashDuration || 0 });
126
188
  }
127
189
 
128
- _stopFlash(sessionId) {
190
+ _stopFlash(sessionId, { cooldown = false } = {}) {
191
+ if (cooldown) {
192
+ const s = this._getSessionState(sessionId);
193
+ s.cooldownUntil = Date.now() + this.config.cooldownMs;
194
+ }
129
195
  if (!this._flashing.get(sessionId)) return;
130
196
  this._flashing.delete(sessionId);
131
197
  this.ctx.stopFlashTab(sessionId);
132
198
  }
133
199
 
134
- _scheduleCheck(sessionId) {
135
- if (this._dataTimers.has(sessionId)) return;
136
-
137
- const timer = setTimeout(() => {
200
+ _resetSession(sessionId) {
201
+ this._stopFlash(sessionId);
202
+ this._sessionState.delete(sessionId);
203
+ const dataTimer = this._dataTimers.get(sessionId);
204
+ if (dataTimer) {
205
+ clearTimeout(dataTimer);
138
206
  this._dataTimers.delete(sessionId);
139
- this._checkAttention(sessionId);
140
- }, this.config.debounceMs);
141
-
142
- this._dataTimers.set(sessionId, timer);
143
- }
144
-
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);
207
+ }
158
208
  }
159
209
 
160
- _isSpinnerChar(text) {
161
- return /[⬝■▣]/.test(text);
210
+ _markWorking(s) {
211
+ const now = Date.now();
212
+ s.working = true;
213
+ s.lastWorkSignalAt = now;
162
214
  }
163
215
 
164
- _checkAttention(sessionId) {
165
- if (this._isWorking(sessionId)) return;
166
-
167
- const state = this.ctx.getTerminalState(sessionId);
168
- if (!state || !state.state) return;
216
+ // Core evaluation: reads the live viewport and drives the state machine.
217
+ _evaluate(sessionId) {
218
+ const viewport = this._getViewportLines(sessionId);
219
+ if (!viewport) return;
169
220
 
170
- const lines = state.state.split('\n');
171
- const recentLines = lines.slice(-30);
172
-
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
- }
221
+ const s = this._getSessionState(sessionId);
222
+ const now = Date.now();
183
223
 
184
- if (this._matchesPattern(stripped) || this._matchesPattern(line)) {
185
- matchedPrompt = true;
224
+ // 1) App presence (non-sticky, with a small miss streak so a single
225
+ // mid-redraw check can't reset state).
226
+ const appOnScreen = viewport.some(line => this._matchesAny(this._appPatterns, line));
227
+ if (appOnScreen) {
228
+ s.appVisible = true;
229
+ s.appMissStreak = 0;
230
+ } else {
231
+ s.appMissStreak++;
232
+ if (s.appMissStreak >= this.config.appMissLimit) {
233
+ // OpenCode left the screen (user exited to shell, switched apps).
234
+ const wasFlashing = this._flashing.get(sessionId);
235
+ s.appVisible = false;
236
+ s.working = false;
237
+ if (wasFlashing) this._stopFlash(sessionId);
186
238
  }
239
+ return;
187
240
  }
188
241
 
189
- const sessionState = this._getSessionState(sessionId);
190
- if (isOpencode) {
191
- sessionState.isOpencode = true;
192
- }
242
+ // 2) Working indicator in the footer region.
243
+ const footer = viewport.slice(-this.config.footerLines);
244
+ const workingVisible = footer.some(line => this._matchesAny(this._workingPatterns, line));
193
245
 
194
- if (!sessionState.isOpencode) return;
246
+ if (workingVisible) {
247
+ this._markWorking(s);
248
+ // Working resumed — anything currently flashing is stale.
249
+ if (this._flashing.get(sessionId)) {
250
+ this._stopFlash(sessionId, { cooldown: true });
251
+ }
252
+ return;
253
+ }
195
254
 
196
- if (matchedPrompt) {
255
+ // 3) Idle transition: a working episode ended (indicator gone AND no
256
+ // work signal for idleThreshold) → the agent finished or is waiting
257
+ // on a dialog → flash.
258
+ if (s.working && (now - s.lastWorkSignalAt) >= this.config.idleThreshold) {
259
+ s.working = false;
197
260
  this._startFlash(sessionId);
198
261
  return;
199
262
  }
200
263
 
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;
264
+ // 4) Optional custom attention patterns (config-supplied only),
265
+ // evaluated against the footer while idle.
266
+ if (!s.working && this._attentionPatterns.length > 0) {
267
+ if (footer.some(line => this._matchesAny(this._attentionPatterns, line))) {
268
+ this._startFlash(sessionId);
269
+ }
207
270
  }
208
271
  }
209
272
 
210
- onData(sessionId, data) {
211
- const stripped = this._stripAnsi(data);
212
- const sessionState = this._getSessionState(sessionId);
213
-
214
- if (/OpenCode/i.test(stripped) || /OpenCode/i.test(data)) {
215
- sessionState.isOpencode = true;
216
- }
273
+ _scheduleEvaluate(sessionId) {
274
+ if (this._dataTimers.has(sessionId)) return;
275
+ const timer = setTimeout(() => {
276
+ this._dataTimers.delete(sessionId);
277
+ this._evaluate(sessionId);
278
+ }, this.config.debounceMs);
279
+ this._dataTimers.set(sessionId, timer);
280
+ }
217
281
 
218
- const isSpinner = this._isSpinnerChar(stripped) || this._isSpinnerChar(data);
282
+ onData(sessionId, data) {
283
+ const s = this._getSessionState(sessionId);
284
+ const now = Date.now();
285
+ s.lastOutputAt = now;
219
286
 
220
- if (isSpinner) {
221
- sessionState.lastSpinnerTime = Date.now();
222
- sessionState.wasWorking = true;
223
- this._scheduleIdleCheck(sessionId);
287
+ // Cheap inline work signal: spinner/indicator glyphs in the stream
288
+ // keep the working state fresh without waiting for a viewport check.
289
+ if (s.appVisible && this._matchesAny(this._workingPatterns, data)) {
290
+ this._markWorking(s);
224
291
  if (this._flashing.get(sessionId)) {
225
- this._stopFlash(sessionId);
226
- sessionState.cooldownUntil = Date.now() + this.config.cooldownMs;
292
+ this._stopFlash(sessionId, { cooldown: true });
227
293
  }
228
294
  return;
229
295
  }
230
296
 
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
- }
239
- }
240
-
241
- onTerminalLine(sessionId, strippedLine, rawLine) {
242
- const sessionState = this._getSessionState(sessionId);
243
-
244
- if (/OpenCode/i.test(strippedLine)) {
245
- sessionState.isOpencode = true;
297
+ // Agent-driven output heuristic: bytes arriving while the user hasn't
298
+ // typed recently. Echo/UI reactions to keystrokes don't count.
299
+ if (now - s.lastUserInputAt > this.config.userEchoWindowMs) {
300
+ if (now - s.agentWindowStart > this.config.workWindowMs) {
301
+ s.agentWindowStart = now;
302
+ s.agentBytes = 0;
303
+ }
304
+ s.agentBytes += data.length;
305
+ if (s.appVisible && s.agentBytes >= this.config.minWorkBytes) {
306
+ this._markWorking(s);
307
+ if (this._flashing.get(sessionId)) {
308
+ this._stopFlash(sessionId, { cooldown: true });
309
+ }
310
+ }
246
311
  }
247
312
 
248
- if (!sessionState.isOpencode) return;
249
- if (this._isWorking(sessionId)) return;
313
+ // Debounced evaluation so a burst that ends (stream complete, dialog
314
+ // shown) is noticed quickly instead of waiting for the next interval.
315
+ this._scheduleEvaluate(sessionId);
316
+ }
250
317
 
251
- if (this._matchesPattern(strippedLine) || this._matchesPattern(rawLine)) {
252
- this._startFlash(sessionId);
253
- }
318
+ onUserInput(sessionId /*, data */) {
319
+ const s = this._getSessionState(sessionId);
320
+ s.lastUserInputAt = Date.now();
321
+ // The user is here — stop flashing and hold off for a while.
322
+ this._stopFlash(sessionId, { cooldown: true });
254
323
  }
255
324
 
256
325
  onSessionConnect(sessionId) {
257
- this._sessionState.delete(sessionId);
326
+ this._resetSession(sessionId);
258
327
  this._flashing.delete(sessionId);
259
328
 
260
329
  const existingTimer = this._checkTimers.get(sessionId);
@@ -266,28 +335,21 @@ class OpenCodeAttentionPlugin {
266
335
  this._checkTimers.delete(sessionId);
267
336
  return;
268
337
  }
269
- this._checkAttention(sessionId);
338
+ this._evaluate(sessionId);
270
339
  }, this.config.checkInterval);
271
340
 
272
341
  this._checkTimers.set(sessionId, timer);
273
342
  }
274
343
 
275
344
  onSessionDisconnect(sessionId) {
276
- this._stopFlash(sessionId);
277
- this._sessionState.delete(sessionId);
345
+ this._resetSession(sessionId);
278
346
 
279
347
  const checkTimer = this._checkTimers.get(sessionId);
280
348
  if (checkTimer) {
281
349
  clearInterval(checkTimer);
282
350
  this._checkTimers.delete(sessionId);
283
351
  }
284
-
285
- const dataTimer = this._dataTimers.get(sessionId);
286
- if (dataTimer) {
287
- clearTimeout(dataTimer);
288
- this._dataTimers.delete(sessionId);
289
- }
290
352
  }
291
353
  }
292
354
 
293
- module.exports = OpenCodeAttentionPlugin;
355
+ module.exports = OpenCodeAttentionPlugin;
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-attention",
3
- "version": "1.0.0",
4
- "description": "Flashes SSH tabs when opencode is waiting for user input",
3
+ "version": "2.0.0",
4
+ "description": "Flashes SSH tabs when OpenCode finishes working and is waiting for you (state-transition detection, no brittle prompt patterns)",
5
5
  "type": "sshift-plugin"
6
- }
6
+ }
@@ -5,6 +5,7 @@
5
5
  const { loadConfig, getStickySetting, getScrollback } = require('../../utils/config');
6
6
  const { addTab, getTab, addSocketToTab, removeSocketFromTab, removeTab, getTabOrder, setCloseTimer, clearCloseTimer, getCloseTimer } = require('../../utils/tab-manager');
7
7
  const { sshManager } = require('../../services');
8
+ const pluginManager = require('../../plugins/plugin-manager');
8
9
 
9
10
  // Per-session rate limiting for ssh-request-sync. A non-controller could
10
11
  // otherwise trigger a 1MB serialization + base64 + emit on every
@@ -159,6 +160,10 @@ function registerSSHHandlers(socket, io) {
159
160
  }
160
161
  try {
161
162
  sshManager.write(data.sessionId, data.data);
163
+ // Notify plugins that the user is actively typing in this session
164
+ // (attention plugins use this to stop flashing / suppress false
165
+ // "needs attention" transitions while the user is present).
166
+ try { pluginManager.onUserInput(data.sessionId, data.data); } catch (_) {}
162
167
  } catch (err) {
163
168
  console.error(`[SSH] ssh-data: write failed for ${data.sessionId}:`, err.message);
164
169
  socket.emit('ssh-error', {
@@ -9,6 +9,7 @@
9
9
  * - onSessionDisconnect(sessionId) - SSH session closed
10
10
  * - onData(sessionId, data) - Raw terminal output data
11
11
  * - onTerminalLine(sessionId, line) - Individual terminal lines
12
+ * - onUserInput(sessionId, data) - User keystrokes/input sent to the session
12
13
  *
13
14
  * Plugin actions (via context object):
14
15
  * - ctx.flashTab(sessionId, options) - Flash a tab to get attention
@@ -32,6 +33,7 @@ class PluginManager {
32
33
  onSessionDisconnect: [],
33
34
  onData: [],
34
35
  onTerminalLine: [],
36
+ onUserInput: [],
35
37
  };
36
38
  this.io = null;
37
39
  this.sshManager = null;
@@ -302,6 +304,13 @@ _stripAnsi(str) {
302
304
  this._processLineBuffer(sessionId, data);
303
305
  }
304
306
 
307
+ // User keystrokes / input written to the session (via ssh-manager.write).
308
+ // Lets attention-style plugins know the user is actively present so they
309
+ // can stop flashing and suppress false "needs attention" transitions.
310
+ onUserInput(sessionId, data) {
311
+ this.emit('onUserInput', sessionId, data);
312
+ }
313
+
305
314
  onSessionConnect(sessionId, sessionInfo) {
306
315
  this.emit('onSessionConnect', sessionId, sessionInfo);
307
316
  }
@@ -10167,6 +10167,17 @@ if (keepaliveCountMaxInput && this.sshKeepaliveCountMax) {
10167
10167
  // Tab Management
10168
10168
 
10169
10169
  startTabFlash(sessionId, options = {}) {
10170
+ // Don't flash a terminal the user is already looking at: its wrapper is
10171
+ // visible (active in some panel) AND this browser window is focused and
10172
+ // visible. Each client decides locally, so a background device still
10173
+ // flashes while the one you're staring at stays quiet.
10174
+ const wrapper = document.getElementById(`terminal-wrapper-${sessionId}`);
10175
+ if (wrapper && wrapper.classList.contains('active') &&
10176
+ document.hasFocus() && !document.hidden) {
10177
+ console.log('[SSHIFT] Suppressing tab flash for visible+focused session:', sessionId);
10178
+ return;
10179
+ }
10180
+
10170
10181
  const flashingSessions = this._flashingSessions || (this._flashingSessions = new Set());
10171
10182
  flashingSessions.add(sessionId);
10172
10183