hopdeck 1.6.0 → 1.7.0

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/bin/hopdeck.js CHANGED
@@ -10,37 +10,70 @@ const os = require('os');
10
10
  const path = require('path');
11
11
  const cp = require('child_process');
12
12
  const readline = require('readline');
13
+ const { StringDecoder } = require('string_decoder');
13
14
  let provider;
14
15
  try { provider = require('../lib/provider'); }
15
16
  catch (err) { if (require.main !== module) throw err; console.error(err.message); process.exit(2); }
16
- const codexHistory = require('../lib/codex-history');
17
+ const codexHistory = () => require('../lib/codex-history');
18
+ const closeCodexHistory = () => { if (provider.isCodex) codexHistory().close(); };
17
19
  const providerSetup = require('../lib/provider-setup');
18
20
 
19
21
  const { LANG, T } = require('../lib/i18n');
20
22
  const { showWelcome } = require('../lib/welcome');
21
- const { TRUE, NOCOL, LIGHT, setTheme, isLight, fg, bg, R, C, cw, strW, fit, clean } = require('../lib/style');
23
+ const { rgbTo256, TRUE, NOCOL, LIGHT, setTheme, isLight, fg, bg, R, C, cw, strW, fit, clean } = require('../lib/style');
22
24
  const mascot = require('../lib/mascot');
23
25
  const stats = require('../lib/stats');
24
- const { baseName, tidy, home, shortPath, fold, queryWords, matchWords, fuzzy, wrapText } = require('../lib/text');
26
+ const { samePath, baseName, tidy, home, shortPath, fold, queryWords, matchWords, fuzzy, fuzzyWords, wrapText } = require('../lib/text');
25
27
  const hist = require('../lib/history');
26
28
  const { CONFIG_DIR, CACHE_FILE, textOf, isType, cacheLoad, cacheSave, readSession, decodeDir, projectDirs, buildProject, beginScan, endScan } = hist;
27
29
  const images = require('../lib/images');
28
- const { urlAt, openUrl } = require('../lib/links');
29
- const { encodeSixel } = require('../lib/sixel');
30
+ const { urlAt, openUrl, spawnOpener } = require('../lib/links');
31
+ const { LRU } = require('../lib/lru');
32
+ const { createImageWorker } = require('../lib/image-worker');
33
+ const imageWorker = createImageWorker();
30
34
  const gitlib = require('../lib/git');
31
35
  const deepsearch = require('../lib/deepsearch');
36
+ const { createBackground, coalesceMouse } = require('../lib/background');
32
37
  const { collectImages, decodePNG, decodeImage, scaleBox, fitSize, halfBlocks } = images;
33
38
  const { parseKeys, KEYMAP, printable, editBuf, normalizeKeys, isCopyKey } = require('../lib/keys');
34
39
  const { stripJsonc, wtCtrlV, wtSettingsFile } = require('../lib/windows-terminal');
35
40
 
41
+ const { cmdLine } = require('../lib/winshell');
42
+ const { writeJsonAtomic, readJsonSafe, backupCorrupt } = require('../lib/atomic');
43
+ const { readConfig } = require('../lib/config');
44
+ const { readText, writeText } = require('../lib/textfile');
45
+ const { isWSL } = require('../lib/wsl');
46
+ const { copyText } = require('../lib/clipboard');
47
+ const { createInput, PASTE, END } = require('../lib/input');
48
+ const { escapeTmux, parseTmuxVersion, canUseTmux, tmuxMode, tmuxSession } = require('../lib/tmux');
49
+
50
+ const profile = require('../lib/profile');
51
+ profile.mark('moduleLoaded');
52
+ const historyScanner = hist.createProjectScanner({ reloadMs: profile.reloadMs });
53
+ const historyAbort = new AbortController();
54
+
36
55
  let VERSION = '0.0.0';
37
56
  try { VERSION = require('../package.json').version; } catch { /* sin package.json */ }
38
57
  const WIN = process.platform === 'win32';
39
58
  // Preferencias propias: proyectos fijados/ocultos, ancho del panel, ratón.
40
59
  const CFG_FILE = process.env.HOPDECK_CONFIG || provider.configFile;
41
60
  const CFG = { pinned: [], hidden: [], archived: [], sidebar: 0, mouse: true, notify: true, last: null };
42
- const saveCfg = () => { try { fs.writeFileSync(CFG_FILE, JSON.stringify(CFG, null, 2), { mode: 0o600 }); } catch { /* solo lectura */ } };
43
- try { Object.assign(CFG, JSON.parse(fs.readFileSync(CFG_FILE, 'utf8'))); } catch { /* primera vez */ }
61
+ function loadCfg(file, defaults, read = readJsonSafe) {
62
+ let backedUp = false;
63
+ const { value, status } = read(file, (raw) => { try { backupCorrupt(file, raw); backedUp = true; } catch { /* solo lectura */ } });
64
+ if (status === 'ok') Object.assign(defaults, value);
65
+ return status !== 'corrupt' || backedUp;
66
+ }
67
+ const canSaveCfg = loadCfg(CFG_FILE, CFG, readConfig);
68
+ const archived = new Set(CFG.archived);
69
+ function toggleArchive(id) {
70
+ const i = CFG.archived.indexOf(id);
71
+ if (i >= 0) CFG.archived.splice(i, 1); else CFG.archived.push(id);
72
+ archived.clear(); for (const sid of CFG.archived) archived.add(sid);
73
+ invalidateView();
74
+ return i < 0;
75
+ }
76
+ const saveCfg = () => { if (canSaveCfg) try { writeJsonAtomic(CFG_FILE, CFG, { space: 2 }); } catch { /* solo lectura */ } };
44
77
 
45
78
  // ───────────────────────── i18n ─────────────────────────
46
79
 
@@ -51,25 +84,31 @@ function sortProjects(list) {
51
84
  return list.sort((a, b) => (b.pinned - a.pinned) || (b.isCwd - a.isCwd) || (b.mtime - a.mtime));
52
85
  }
53
86
 
87
+ function realFolder(dir) { try { return fs.realpathSync.native(dir); } catch { return dir; } }
88
+ const sameFolder = (a, b) => samePath(realFolder(a), realFolder(b));
89
+
54
90
  function finishScan(projects) {
55
- if (!provider.isCodex) endScan();
56
91
  if (provider.isCodex) for (const p of projects) for (const s of p.sessions) s.title = CFG.titles?.[s.id] || s.title;
57
- const cur = process.cwd();
58
- const have = (d) => projects.some((p) => p.cwd === d);
92
+ const cur = realFolder(process.cwd()), paths = new Map();
93
+ const real = (d) => { if (!paths.has(d)) paths.set(d, realFolder(d)); return paths.get(d); };
94
+ const have = (d) => projects.some((p) => samePath(real(p.cwd), real(d)));
59
95
  if (!have(cur)) projects.push({ key: '__cwd', cwd: cur, name: baseName(cur), sessions: [], mtime: Date.now() });
60
96
  // carpetas abiertas desde el selector y chats vivos que aún no tienen historial: se muestran igualmente
61
97
  for (const x of Array.isArray(CFG.recent) ? CFG.recent : []) {
62
- if (x && x.dir && !have(x.dir) && fs.existsSync(x.dir)) projects.push({ key: '__recent:' + x.dir, cwd: x.dir, name: baseName(x.dir), sessions: [], mtime: x.t || 0 });
98
+ if (!x || typeof x.dir !== 'string' || !x.dir || !fs.existsSync(x.dir)) continue;
99
+ const d = real(x.dir);
100
+ if (!have(d)) projects.push({ key: '__recent:' + d, cwd: d, name: baseName(d), sessions: [], mtime: x.t || 0 });
63
101
  }
64
102
  for (const x of E.sessions.values()) if (!have(x.cwd)) projects.push({ key: '__live:' + x.cwd, cwd: x.cwd, name: baseName(x.cwd), sessions: [], mtime: Date.now() });
65
103
  linkChats(projects);
66
104
  for (const p of projects) {
67
- p.isCwd = p.cwd === cur;
105
+ p.isCwd = samePath(real(p.cwd), cur);
68
106
  p.pinned = CFG.pinned.includes(p.cwd) ? 1 : 0;
69
107
  p.hidden = CFG.hidden.includes(p.cwd) && !p.isCwd;
70
108
  p.isCwd = p.isCwd ? 1 : 0;
71
109
  }
72
- return sortProjects(projects);
110
+ sortProjects(projects); profile.scanEnd(projects);
111
+ return projects;
73
112
  }
74
113
 
75
114
  /** Un chat nuevo ya escribió su historial: se enlaza con su archivo para que la lista lo muestre como la conversación real. */
@@ -92,11 +131,11 @@ function toggleProject(p, field) {
92
131
  const i = list.indexOf(p.cwd);
93
132
  if (i >= 0) list.splice(i, 1); else list.push(p.cwd);
94
133
  p[field] = field === 'pinned' ? (i < 0 ? 1 : 0) : i < 0;
95
- saveCfg(); sortProjects(S.projects);
134
+ saveCfg(); sortProjects(S.projects); invalidateView();
96
135
  }
97
136
 
98
137
  // Se llama en cada dibujo; en WSL leer un archivo de /mnt/c cuesta unos 4 ms, así que el resultado se guarda unos segundos.
99
- const BRANCH = new Map();
138
+ const BRANCH = new LRU(256);
100
139
  function gitBranch(cwd) {
101
140
  const now = Date.now(), hit = BRANCH.get(cwd);
102
141
  if (hit && now - hit.t < 3000) return hit.v;
@@ -111,21 +150,19 @@ function gitBranch(cwd) {
111
150
  }
112
151
 
113
152
  function scan() {
114
- if (provider.isCodex) return finishScan(codexHistory.scanSync());
153
+ profile.mark('scanStart');
154
+ if (provider.isCodex) return finishScan(codexHistory().scanSync());
115
155
  beginScan();
116
- return finishScan(projectDirs().map(buildProject).filter(Boolean));
156
+ const projects = projectDirs().map(buildProject).filter(Boolean);
157
+ endScan();
158
+ return finishScan(projects);
117
159
  }
118
160
 
119
161
  /** Igual que scan() pero cede el control al bucle de eventos para poder animar el loader. */
120
- async function scanAsync(onProgress) {
121
- if (provider.isCodex) return finishScan(await codexHistory.scanProjectsAsync(onProgress));
122
- const dirs = projectDirs(); const projects = [];
123
- beginScan();
124
- for (let i = 0; i < dirs.length; i++) {
125
- const p = buildProject(dirs[i]); if (p) projects.push(p);
126
- if (i % 3 === 2) { if (onProgress) onProgress(i + 1, dirs.length); await new Promise((r) => setImmediate(r)); }
127
- }
128
- return finishScan(projects);
162
+ async function scanAsync(onProgress, full = false) {
163
+ profile.mark('scanStart');
164
+ if (provider.isCodex) return finishScan(await codexHistory().scanProjectsAsync(onProgress));
165
+ return finishScan(await historyScanner.scanProjectsAsync({ onProgress, full, signal: historyAbort.signal }));
129
166
  }
130
167
 
131
168
  function ago(ms) {
@@ -140,31 +177,55 @@ function ago(ms) {
140
177
 
141
178
  // ───────────────────────── estado ─────────────────────────
142
179
  const S = { auto: false, qpos: 0, pc: 0, fb: null, confirmMk: null, confirmClose: null, more: new Set(), qs: null, promptKind: 'folder', renameTarget: null, deep: false, deepHits: null, showHidden: false, prompt: null, help: false, loading: false, projects: [], pi: 0, si: 0, focus: 0, query: '', searching: false, poff: 0, soff: 0, flash: '', c: 0, coff: 0, open: null, live: new Set(), liveKey: '' };
180
+ let viewMemo, flatMemo, qsView;
181
+ // Las referencias y los valores simples se comparan al leer; las mutaciones in situ se invalidan aquí.
182
+ const qsMemo = new Map();
183
+ function invalidateView() { viewMemo = flatMemo = qsView = null; qsMemo.clear(); }
184
+ // Los dos buscadores usan el mismo texto normalizado.
185
+ const searchText = (p, s) => s._f ?? (s._f = fold(p.name + ' ' + s.title + ' ' + s.first));
186
+ function replaceProjects(projects) {
187
+ const prev = new Map();
188
+ for (const p of S.projects) for (const s of p.sessions) if (s._f !== undefined) prev.set(s.id, { p, s });
189
+ if (prev.size) for (const p of projects) for (const s of p.sessions) {
190
+ const old = prev.get(s.id);
191
+ if (old && old.s.mtime === s.mtime && old.p.name === p.name && old.s.title === s.title && old.s.first === s.first) s._f = old.s._f;
192
+ }
193
+ S.projects = projects; invalidateView();
194
+ }
143
195
  const SIDEBAR = process.argv.includes('--sidebar');
144
196
  let EMBED = false; // vista dividida con terminal embebido (Windows / sin tmux)
145
197
  const E = { sessions: new Map(), shown: null, focus: 'left', pend: null, deps: null, mouse: CFG.mouse !== false, hideSide: false, git: !!CFG.git, note: null, sel: null, gallery: null, hover: null, sixelDetected: false, cell: { w: 10, h: 20 }, sixelKey: null, sixelAt: 0, sixelStale: false, sixelRetry: null };
146
198
  const SPIN = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
147
- let spinT = null, frameN = 0, reloading = false;
148
- const needsSpin = () => S.loading || (E.gallery && (E.gallery.loading || E.gallery.pending)) || (E.hover && E.hover.g.pending) || [...E.sessions.values()].some((x) => x.working || (!x.ready && x === E.sessions.get(E.shown)));
149
- function ensureSpin() {
150
- if (spinT) return;
151
- spinT = setInterval(() => {
152
- if (!needsSpin()) { clearInterval(spinT); spinT = null; if (active) render(); return; }
153
- frameN++; if (active) render();
154
- }, 90);
199
+ let spinT = null, frameN = 0, reloading = false, scanLoading = false, cachePaint = false, spinVisible = false;
200
+ function needsSpin() {
201
+ if (scanLoading || S.loading || (E.gallery && (E.gallery.loading || E.gallery.pending)) || E.hover?.g.pending || E.sessions.get(E.shown)?.ready === false) return true;
202
+ for (const x of E.sessions.values()) if (x.working) return true;
203
+ return false;
204
+ }
205
+ function spinTick(drawing = active, visible = !EMBED || spinVisible) {
206
+ if (!needsSpin()) { clearInterval(spinT); spinT = null; return; }
207
+ frameN++;
208
+ if (drawing && visible) scheduleRender();
155
209
  }
210
+ function ensureSpin() { if (!spinT) spinT = setInterval(spinTick, 90); }
156
211
  const spin = () => SPIN[frameN % SPIN.length];
157
212
 
158
- /** Recarga la lista sin congelar la pantalla; `after` restaura la selección. */
159
- async function reloadAsync(after, silent) {
213
+ /** Recarga la lista conservando la selección; `after` aplica cambios del llamador. */
214
+ async function reloadAsync(after, silent, { incremental = false, startup = false } = {}) {
160
215
  if (reloading) return;
161
- reloading = true; if (!silent) { S.loading = true; ensureSpin(); if (active) render(); }
216
+ const started = profile.now();
217
+ reloading = true; if (!silent && !scanLoading) { scanLoading = true; ensureSpin(); if (active) render(); }
162
218
  deepPrev = null;
163
- try { S.projects = await scanAsync(); }
219
+ try {
220
+ const projects = await scanAsync(undefined, !incremental);
221
+ const restore = selectionRestore();
222
+ replaceProjects(projects); restore();
223
+ }
164
224
  catch (err) { S.flash = String(err.message).split('\n')[0]; }
165
- finally { reloading = false; if (!silent) S.loading = false; }
225
+ finally { reloading = false; scanLoading = false; }
166
226
  if (after) after();
167
227
  if (active) render();
228
+ if (profile.enabled && !startup) profile.duration('reload', started);
168
229
  }
169
230
 
170
231
  const clamp = (n, a, b) => Math.max(a, Math.min(b, n));
@@ -173,13 +234,20 @@ const clamp = (n, a, b) => Math.max(a, Math.min(b, n));
173
234
  const sessTag = (s) => (s.parts ? '↻' + s.parts : s.dup ? '#' + s.id.slice(0, 4) : '');
174
235
 
175
236
  function view() {
237
+ if (viewMemo && viewMemo.projects === S.projects && viewMemo.query === S.query && viewMemo.hidden === S.showHidden && viewMemo.hits === S.deepHits) return viewMemo.result;
238
+ const result = computeView();
239
+ viewMemo = { projects: S.projects, query: S.query, hidden: S.showHidden, hits: S.deepHits, result };
240
+ return result;
241
+ }
242
+
243
+ function computeView() {
176
244
  // La búsqueda son palabras sueltas, sin importar el orden, mayúsculas ni acentos: «vistas roles» encuentra «Roles y vistas».
177
245
  // Cada conversación se compara con proyecto + título + primer mensaje; el proyecto entero sale si lo que se busca está en su nombre o ruta.
178
246
  const ws = queryWords(S.query);
179
247
  const base = S.projects.filter((p) => S.showHidden || !p.hidden);
180
- const vis = (x) => S.showHidden || !CFG.archived.includes(x.id);
248
+ const vis = (x) => S.showHidden || !archived.has(x.id);
181
249
  if (!ws.length) return base.map((p) => ({ p, ss: p.sessions.filter(vis) }));
182
- const hitS = (p, x) => matchWords(ws, x._f || (x._f = fold(p.name + ' ' + x.title + ' ' + x.first))) || !!(S.deepHits && S.deepHits.has(x.id));
250
+ const hitS = (p, x) => matchWords(ws, searchText(p, x)) || !!(S.deepHits && S.deepHits.has(x.id));
183
251
  const out = [];
184
252
  for (const p of base) {
185
253
  const hit = matchWords(ws, p._f || (p._f = fold(p.name + ' ' + p.cwd)));
@@ -209,7 +277,8 @@ function queryChanged() {
209
277
  const list = (deepPrev && q.startsWith(deepPrev.q) ? all.filter((x) => deepPrev.hits.has(x.id)) : all).filter((x) => x.file);
210
278
  const idOf = new Map(list.map((x) => [x.file, x.id]));
211
279
  S.deepHits = hits; // se va llenando: los aciertos aparecen en la lista según se encuentran
212
- const job = deepsearch.deepSearch(list.map((x) => x.file), q, (file) => { if (tok !== deepTok) return; hits.add(idOf.get(file)); if (active) scheduleRender(); });
280
+ const files = cacheLoad().files;
281
+ const job = deepsearch.deepSearch(list.map((x) => ({ file: x.file, size: files[x.file]?.z })), q, (file) => { if (tok !== deepTok) return; hits.add(idOf.get(file)); invalidateView(); if (active) scheduleRender(); });
213
282
  deepJob = job;
214
283
  job.done.then(() => { if (tok === deepTok) { deepPrev = { q, hits }; S.loading = false; deepJob = null; if (active) render(); } });
215
284
  }, 250);
@@ -244,7 +313,7 @@ function frame(cols, rows) {
244
313
  // cabeceras
245
314
  const hl = S.focus === 0 ? C.accent + C.bold : C.dim;
246
315
  const hr = S.focus === 1 ? C.accent + C.bold : C.dim;
247
- lines.push(B('│') + fit([[' ' + T.projects, hl], [' ' + V.length, C.dim], [S.loading ? ' ' + spin() : '', C.accent]], lw) + B('│') +
316
+ lines.push(B('│') + fit([[' ' + T.projects, hl], [' ' + V.length, C.dim], [(scanLoading || S.loading) ? ' ' + spin() : '', C.accent]], lw) + B('│') +
248
317
  fit([[' ' + T.sessions, hr], [cur ? ' · ' + cur.p.name : '', C.dim]], rw) + B('│'));
249
318
  lines.push(B('├' + '─'.repeat(lw) + '┼' + '─'.repeat(rw) + '┤'));
250
319
 
@@ -329,14 +398,23 @@ function frame(cols, rows) {
329
398
  // ───────────────────────── utilidades de interfaz ─────────────────────────
330
399
  // ───────────────────────── modo panel lateral (tmux) ─────────────────────────
331
400
  const LIMIT = 8; // sesiones visibles por proyecto antes de "mostrar N más…"
332
- function flatList() {
401
+ function flatList(embed = EMBED) {
402
+ const projects = view();
403
+ if (flatMemo && flatMemo.projects === projects && flatMemo.open === S.open && flatMemo.embed === embed &&
404
+ flatMemo.more === S.more && flatMemo.size === S.more.size) return flatMemo.result;
405
+ const result = computeFlatList(projects, embed);
406
+ flatMemo = { projects, open: S.open, embed, more: S.more, size: S.more.size, result };
407
+ return result;
408
+ }
409
+
410
+ function computeFlatList(projects, embed = EMBED) {
333
411
  const q = S.query.trim(); const out = [];
334
- for (const { p, ss } of view()) {
412
+ for (const { p, ss } of projects) {
335
413
  const open = p.key === S.open || (!!q && ss.length < p.sessions.length);
336
414
  out.push({ t: 'p', p, open });
337
415
  if (open) {
338
416
  out.push({ t: 'n', p });
339
- if (EMBED) for (const [key, x] of E.sessions) if (!x.sid && x.cwd === p.cwd) out.push({ t: 'l', p, key, x }); // chat nuevo aún sin historial
417
+ if (embed) for (const [key, x] of E.sessions) if (!x.sid && x.cwd === p.cwd) out.push({ t: 'l', p, key, x }); // chat nuevo aún sin historial
340
418
  const lim = q || S.more.has(p.key) ? ss.length : LIMIT;
341
419
  for (const s of ss.slice(0, lim)) out.push({ t: 's', p, s });
342
420
  if (ss.length > lim) out.push({ t: 'm', p, n: ss.length - lim });
@@ -396,9 +474,14 @@ function frameTree(W, H) {
396
474
  S.coff = scroll(S.coff, S.c, bodyH);
397
475
  const lines = [];
398
476
  const searchOn = !S.fb && !S.qs && S.prompt === null && !S.help && (S.searching || !!S.query.trim()); // hay una búsqueda en marcha
399
- const head = [[' » ', C.brand], ['Hop', C.brand + C.bold], ['deck', C.text + C.bold], [' ' + provider.label, C.dim], [' ' + S.projects.length, C.dim], [S.loading && !searchOn ? ' ' + spin() : '', C.accent], ...liveSummary()];
477
+ const head = [[' » ', C.brand], ['Hop', C.brand + C.bold], ['deck', C.text + C.bold], [' ' + provider.label, C.dim], [' ' + S.projects.length, C.dim], [(scanLoading || S.loading) && !searchOn ? ' ' + spin() : '', C.accent], ...liveSummary()];
400
478
  // «⌕ / buscar» siempre a la vista, arriba a la derecha (sin la palabra si el título y los chats abiertos ya ocupan el sitio)
401
- const headW = head.reduce((a, [t]) => a + strW(t), 0), longHint = ' ⌕ / ' + T.k.find + ' ', hint = headW + strW(longHint) <= W ? longHint : headW + 5 <= W ? ' ⌕ / ' : '';
479
+ const headW = head.reduce((a, [t]) => a + strW(t), 0);
480
+ if (EMBED && !searchOn && !(S.fb && !S.qs)) {
481
+ const spinner = head.findIndex(([t]) => t.startsWith(' ' + spin()));
482
+ if (spinner >= 0 && head.slice(0, spinner).reduce((n, [t]) => n + strW(t), 0) + 3 <= (headW > W ? W - 1 : W)) spinVisible = true;
483
+ }
484
+ const longHint = ' ⌕ / ' + T.k.find + ' ', hint = headW + strW(longHint) <= W ? longHint : headW + 5 <= W ? ' ⌕ / ' : '';
402
485
  lines.push(searchOn
403
486
  // el cuadro de búsqueda ocupa el lugar del título, arriba, donde se mira primero
404
487
  ? fit([[' ⌕ ', C.accent], ...withCursor(S.query, S.searching ? S.qpos : [...S.query].length, S.searching), [S.query ? '' : ' ' + T.searchPh, C.dim]], W)
@@ -441,6 +524,7 @@ function frameTree(W, H) {
441
524
  if (S.help) { const t = T.help[r]; lines.push(fit([[t ? ' ' + t : '', r === 0 ? C.accent + C.bold : C.dim]], W)); continue; }
442
525
  const e = L[S.coff + r];
443
526
  if (!e && searchOn && !L.length && r <= 2) { // búsqueda sin resultados: se dice, y se explica qué hacer
527
+ if (EMBED && r === 2 && S.loading && (S.deep || S.auto)) spinVisible = true;
444
528
  const msg = r === 0 ? [[' ' + T.noRes(S.query.trim()), C.warn]]
445
529
  : r === 2 ? [[' ' + ((S.deep || S.auto) ? (S.loading ? spin() + ' ' + T.searchingContent : '') : T.tryContent), C.dim]] : [];
446
530
  lines.push(fit(msg, W)); continue;
@@ -462,13 +546,15 @@ function frameTree(W, H) {
462
546
  lines.push(fit([mark, [' ', ''], [T.more(e.n), sel ? C.text : C.dim]], W, base));
463
547
  } else if (e.t === 'l') {
464
548
  const [mk, mc] = chatMark(e.key);
549
+ if (EMBED && mk === spin() + ' ' && W >= 20) spinVisible = true;
465
550
  lines.push(fit([mark, [' ', ''], [mk, mc], [T.newChat + ' …', sel ? C.text + C.bold : C.text]], W - 13, base) +
466
551
  fit([[''.padEnd(6), ''], [ago(e.x.t0).padStart(6), C.dim], [' ', '']], 13, base));
467
552
  } else if (e.t === 'n') {
468
553
  lines.push(fit([mark, [' + ', C.accent], [T.newChat, sel ? C.accent + C.bold : C.accent]], W, base));
469
554
  } else {
470
555
  const [mk, mc] = chatMark(e.s.id);
471
- const arch = CFG.archived.includes(e.s.id), tag = sessTag(e.s);
556
+ if (EMBED && mk === spin() + ' ' && W >= 20) spinVisible = true;
557
+ const arch = archived.has(e.s.id), tag = sessTag(e.s);
472
558
  const ts = sel ? C.text + C.bold : arch ? C.dim : C.text, inTxt = qWords.length && !matchWords(qWords, fold(e.s.title)); // ⌕: coincide por el proyecto, el primer mensaje o el contenido
473
559
  lines.push(fit([mark, [' ', ''], [mk, mc], ...hl(e.s.title, sq0, ts), ...(inTxt ? [[' ⌕', C.dim]] : [])], W - 13, base) +
474
560
  fit([[tag.padEnd(6), C.accent], [ago(e.s.mtime).padStart(6), C.dim], [' ', '']], 13, base));
@@ -479,6 +565,7 @@ function frameTree(W, H) {
479
565
  const br = cur && !S.flash ? gitBranch(cur.p.cwd) : '';
480
566
  const note = EMBED && E.note;
481
567
  const deepOn = S.deep || S.auto;
568
+ if (EMBED && !S.flash && searchOn && deepOn && S.loading && strW(nHits ? T.found(nHits) : T.noMatch) + 5 <= W) spinVisible = true;
482
569
  lines.push(fit(S.flash ? [[' ' + S.flash, C.warn]] : searchOn // durante una búsqueda, esta fila dice cuántos resultados hay y dónde se busca
483
570
  ? [[' ', ''], nHits ? [T.found(nHits), C.accent + C.bold] : [T.noMatch, C.warn], deepOn ? [S.loading ? ' ' + spin() + ' ' + T.searchingContent : ' · ' + T.inContent, C.dim] : ['', '']]
484
571
  : S.fb ? [[S.prompt !== null ? ' ' + T.mkIn + ' ' : ' ⌂ ', C.dim], [tailFit(S.fb.dir === '' ? T.fbDrives : shortPath(S.fb.dir) + (S.prompt !== null ? path.sep : ''), W - 14), C.accent]] : note ? [[' ' + note.t, C.ok]]
@@ -508,10 +595,13 @@ function frameTree(W, H) {
508
595
  }
509
596
 
510
597
  const tmux = (...a) => cp.execFileSync('tmux', a, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
598
+ const tmuxConfig = () => path.resolve(provider.isCodex ? codexHistory().CONFIG_DIR : CONFIG_DIR);
599
+ const sessionName = () => tmuxSession(provider.id, tmuxConfig());
600
+ const tmuxProviderEnv = () => ['HOPDECK_PROVIDER=' + provider.id, (provider.isCodex ? 'CODEX_HOME=' : 'CLAUDE_CONFIG_DIR=') + tmuxConfig()];
511
601
  const sq = (x) => `'${String(x).replace(/'/g, "'\\''")}'`;
512
602
 
513
603
  function chatCmd(bin, args, left) {
514
- const run = ['env', 'HOPDECK_SKIP=1', 'HOPDECK_INSIDE=1', bin, ...args].map(sq).join(' ');
604
+ const run = ['env', 'HOPDECK_SKIP=1', 'HOPDECK_INSIDE=1', ...tmuxProviderEnv(), bin, ...args].map(sq).join(' ');
515
605
  const self = [process.execPath, __filename, '--idle'].map(sq).join(' ');
516
606
  const win = (t) => `"$(tmux display -p -t ${t} '#{window_id}')"`;
517
607
  return `printf '\\033[38;5;105m»\\033[0m %s…\\n\\n' ${sq(T.opening)}; ${run}; tmux set-option -p -t "$TMUX_PANE" -u @hopdeck_key; tmux set-option -p -t "$TMUX_PANE" -u @hopdeck_title; ` +
@@ -519,7 +609,7 @@ function chatCmd(bin, args, left) {
519
609
  }
520
610
 
521
611
  function tmuxPanes() {
522
- return tmux('list-panes', '-a', '-F', '#{pane_id}\t#{@hopdeck_key}').split('\n').filter(Boolean)
612
+ return tmux('list-panes', '-s', '-t', process.env.TMUX_PANE, '-F', '#{pane_id}\t#{@hopdeck_key}').split('\n').filter(Boolean)
523
613
  .map((l) => { const [id, key = ''] = l.split('\t'); return { id, key }; });
524
614
  }
525
615
 
@@ -537,10 +627,10 @@ function launchSlot(project, session) {
537
627
  if (!target) {
538
628
  const cmd = chatCmd(bin, provider.launchArgs(session, extraArgs), mine);
539
629
  const slotInfo = panes.find((x) => x.id === slot);
540
- if (slotInfo && !slotInfo.key) { tmux('respawn-pane', '-k', '-t', slot, '-c', project.cwd, cmd); target = slot; }
541
- else target = tmux('new-window', '-d', '-P', '-F', '#{pane_id}', '-c', project.cwd, cmd);
630
+ if (slotInfo && !slotInfo.key) { tmux('respawn-pane', '-k', '-t', slot, '-c', escapeTmux(project.cwd), cmd); target = slot; }
631
+ else target = tmux('new-window', '-d', '-t', '=' + sessionName() + ':', '-P', '-F', '#{pane_id}', '-c', escapeTmux(project.cwd), cmd);
542
632
  tmux('set-option', '-p', '-t', target, '@hopdeck_key', key);
543
- tmux('set-option', '-p', '-t', target, '@hopdeck_title', project.name + ' › ' + (session ? session.title : T.newChat));
633
+ tmux('set-option', '-p', '-t', target, '@hopdeck_title', escapeTmux(clean(project.name + ' › ' + (session ? session.title : T.newChat))));
544
634
  }
545
635
  if (target !== slot) tmux('swap-pane', '-d', '-s', target, '-t', slot);
546
636
  tmux('select-pane', '-t', target);
@@ -556,25 +646,57 @@ function refreshLive() {
556
646
  } catch { /* sin tmux */ }
557
647
  }
558
648
 
559
- function reloadKeep() {
560
- const e = flatList()[S.c];
561
- return reloadAsync(() => {
562
- if (!e) return;
563
- const same = (x) => x.t === e.t && x.p.key === e.p.key && (e.t !== 's' || x.s.id === e.s.id);
564
- const i = flatList().findIndex(same);
565
- if (i >= 0) S.c = i;
566
- });
649
+ function selectionRestore() {
650
+ if (SIDEBAR || EMBED) {
651
+ const e = flatList()[S.c], open = S.projects.find((p) => p.key === S.open);
652
+ return () => {
653
+ if (open && !S.projects.some((p) => p.key === open.key)) S.open = S.projects.find((p) => samePath(p.cwd, open.cwd))?.key ?? null;
654
+ if (!e) return;
655
+ const key = S.projects.some((p) => p.key === e.p.key) ? e.p.key : S.projects.find((p) => samePath(p.cwd, e.p.cwd))?.key;
656
+ const sameSession = (s) => s.id === e.s.id || s.prior?.includes(e.s.id);
657
+ const sameRow = (x) => x.t === e.t && x.p.key === key && (e.t === 's' ? sameSession(x.s) : e.t !== 'l' || x.key === e.key);
658
+ let rows = flatList(), i = rows.findIndex(sameRow);
659
+ if (i < 0 && e.t === 's' && S.open === key && view().find((v) => v.p.key === key)?.ss.some(sameSession)) {
660
+ S.more.add(key); rows = flatList(); i = rows.findIndex(sameRow);
661
+ }
662
+ if (i < 0) i = rows.findIndex((x) => x.t === 'p' && x.p.key === key);
663
+ if (i >= 0) S.c = i;
664
+ };
665
+ }
666
+ const cur = view()[S.pi], session = cur?.ss[S.si - 1];
667
+ return () => {
668
+ if (!cur) return;
669
+ const list = view(), i = list.findIndex((v) => v.p.key === cur.p.key);
670
+ if (i < 0) return;
671
+ S.pi = i;
672
+ if (session) S.si = list[i].ss.findIndex((s) => s.id === session.id || s.prior?.includes(session.id)) + 1;
673
+ };
567
674
  }
568
675
 
676
+ const reloadKeep = () => reloadAsync();
677
+ const closeClaudeHistory = () => { historyAbort.abort(); historyScanner.closeWatcher(); };
678
+
569
679
  function qsItems() {
570
- const q = S.qs.q.trim(); const items = [];
680
+ const version = flatList(), q = S.qs.q.trim();
681
+ if (qsView !== version) { qsMemo.clear(); qsView = version; }
682
+ if (qsMemo.has(q)) return qsMemo.get(q);
683
+ const result = computeQsItems(q);
684
+ if (qsMemo.size >= 32) qsMemo.delete(qsMemo.keys().next().value);
685
+ qsMemo.set(q, result);
686
+ return result;
687
+ }
688
+
689
+ function computeQsItems(q) {
690
+ const words = queryWords(q), items = [];
571
691
  for (const p of S.projects) {
572
692
  if (p.hidden && !S.showHidden) continue;
573
- for (const x of p.sessions) { if (CFG.archived.includes(x.id) && !S.showHidden) continue; items.push({ p, s: x }); }
693
+ for (const x of p.sessions) {
694
+ if (archived.has(x.id) && !S.showHidden) continue;
695
+ const sc = q ? fuzzyWords(words, searchText(p, x)) : 0;
696
+ if (sc >= 0) items.push({ p, s: x, sc });
697
+ }
574
698
  }
575
- if (!q) return items.sort((a, b) => b.s.mtime - a.s.mtime).slice(0, 200);
576
- return items.map((it) => ({ it, sc: fuzzy(q, it.p.name + ' ' + it.s.title + ' ' + it.s.first) })).filter((x) => x.sc >= 0)
577
- .sort((a, b) => b.sc - a.sc || b.it.s.mtime - a.it.s.mtime).slice(0, 200).map((x) => x.it);
699
+ return items.sort((a, b) => b.sc - a.sc || b.s.mtime - a.s.mtime).slice(0, 200).map(({ p, s }) => ({ p, s }));
578
700
  }
579
701
 
580
702
  function doRename(x, name) {
@@ -626,14 +748,17 @@ const newFolderBase = () => (S.fb && S.fb.dir ? S.fb.dir : os.homedir());
626
748
 
627
749
  // ── Selector de carpetas: se navega con flechas desde ~ y se elige dónde abrir el chat ──
628
750
  const FB_SKIP = new Set(['AppData', 'Application Data', 'Local Settings', 'Cookies', 'NetHood', 'PrintHood', 'Recent', 'SendTo', 'Start Menu', 'Templates', 'node_modules', '$Recycle.Bin', 'System Volume Information']);
629
- function listDrives() { // Windows: letras de unidad disponibles
630
- const out = [];
631
- for (let c = 65; c <= 90; c++) { const r = String.fromCharCode(c) + ':\\'; try { if (fs.existsSync(r)) out.push(r); } catch { /* */ } }
632
- return out;
751
+ function listDrives(onDrive, { access = fs.promises.access, timeout = 1500 } = {}) {
752
+ for (let c = 65; c <= 90; c++) {
753
+ const root = String.fromCharCode(c) + ':\\';
754
+ let expired = false;
755
+ const timer = setTimeout(() => { expired = true; }, timeout);
756
+ access(root).then(() => { clearTimeout(timer); if (!expired) onDrive(root); }, () => clearTimeout(timer));
757
+ }
633
758
  }
634
759
  /** Subcarpetas visibles de `dir` (ocultas y carpetas de sistema solo si `hid`). dir === '' → unidades de Windows. */
635
760
  function fbNames(dir, hid) {
636
- if (dir === '') return listDrives();
761
+ if (dir === '') return [];
637
762
  try {
638
763
  return fs.readdirSync(dir, { withFileTypes: true })
639
764
  .filter((d) => {
@@ -652,6 +777,17 @@ function fbOpen(dir, sel) {
652
777
  S.fb = { dir, names: fbNames(dir, hid), i: 0, off: 0, hid, q: '', qp: 0, filt: false };
653
778
  const rows = fbRows(), j = sel ? rows.findIndex((r) => r.k === 'dir' && r.n === sel) : -1;
654
779
  S.fb.i = j >= 0 ? j : 0;
780
+ if (dir === '') {
781
+ const f = S.fb;
782
+ listDrives((root) => {
783
+ if (S.fb !== f) return;
784
+ const current = (f.i || f.names.includes(sel)) ? fbRows()[f.i]?.n : null;
785
+ const selected = root === sel && !f.q ? sel : current;
786
+ f.names.push(root); f.names.sort();
787
+ f.i = Math.max(0, fbRows().findIndex((row) => row.n === selected));
788
+ render();
789
+ });
790
+ }
655
791
  }
656
792
  function fbRows() {
657
793
  const f = S.fb, r = [];
@@ -660,7 +796,9 @@ function fbRows() {
660
796
  if (f.dir === os.homedir() && !f.q) {
661
797
  for (const x of (Array.isArray(CFG.recent) ? CFG.recent : [])) {
662
798
  if (r.filter((y) => y.k === 'recent').length >= 5) break;
663
- if (x && x.dir && x.dir !== f.dir && fs.existsSync(x.dir)) r.push({ k: 'recent', dir: x.dir });
799
+ if (!x || typeof x.dir !== 'string' || !x.dir || !fs.existsSync(x.dir)) continue;
800
+ const dir = realFolder(x.dir);
801
+ if (!sameFolder(dir, f.dir) && !r.some((y) => y.k === 'recent' && samePath(y.dir, dir))) r.push({ k: 'recent', dir });
664
802
  }
665
803
  }
666
804
  const q = f.q.toLowerCase(), ds = f.names.filter((n) => !q || n.toLowerCase().includes(q));
@@ -710,13 +848,20 @@ function fbKey(k, raw) {
710
848
  else if (k === ' ') return fbChoose();
711
849
  else if (k === 'n' && f.dir !== '') setPrompt('', 'folder');
712
850
  else if (k === '/') { f.filt = true; f.qp = [...f.q].length; }
713
- else if (k === '.') { const sel = (fbRows()[f.i] || {}).n; f.hid = !f.hid; f.names = fbNames(f.dir, f.hid); f.i = Math.max(0, fbRows().findIndex((r) => r.k === 'dir' && r.n === sel)); f.off = 0; }
851
+ else if (k === '.') { const sel = (fbRows()[f.i] || {}).n; f.hid = !f.hid; if (f.dir !== '') f.names = fbNames(f.dir, f.hid); f.i = Math.max(0, fbRows().findIndex((r) => r.k === 'dir' && r.n === sel)); f.off = 0; }
714
852
  else if (k === '~') fbOpen(os.homedir());
715
853
  render();
716
854
  }
717
855
 
718
856
  function recordFolder(d) {
719
- CFG.recent = [{ dir: d, t: Date.now() }, ...(Array.isArray(CFG.recent) ? CFG.recent : []).filter((x) => x && x.dir !== d)].slice(0, 12);
857
+ const recent = [{ dir: realFolder(d), t: Date.now() }];
858
+ for (const x of Array.isArray(CFG.recent) ? CFG.recent : []) {
859
+ if (recent.length === 12) break;
860
+ if (!x || typeof x.dir !== 'string' || !x.dir) continue;
861
+ const dir = realFolder(x.dir);
862
+ if (!recent.some((y) => samePath(y.dir, dir))) recent.push({ ...x, dir });
863
+ }
864
+ CFG.recent = recent;
720
865
  saveCfg();
721
866
  }
722
867
 
@@ -731,9 +876,10 @@ function openFolder(txt) {
731
876
  S.confirmMk = null;
732
877
  try { fs.mkdirSync(d, { recursive: true }); } catch (e) { flash(T.mkFail + ': ' + String(e.message).split('\n')[0]); return; }
733
878
  }
734
- S.fb = null; recordFolder(d);
735
- const proj = S.projects.find((p) => p.cwd === d) || { key: '__open', cwd: d, name: baseName(d), sessions: [], mtime: Date.now() };
736
- launch(proj, null);
879
+ const dir = realFolder(d);
880
+ S.fb = null; recordFolder(dir);
881
+ const proj = S.projects.find((p) => sameFolder(p.cwd, dir)) || { key: '__open', name: baseName(dir), sessions: [], mtime: Date.now() };
882
+ launch({ ...proj, cwd: dir }, null);
737
883
  }
738
884
 
739
885
  function onKeyTree(raw) {
@@ -748,10 +894,9 @@ function onKeyTree(raw) {
748
894
  if (S.help) { S.help = false; return render(); }
749
895
  if (k === 'ctrlp' || k === 'f5') { S.qs = S.qs ? null : { q: '', pc: 0, i: 0, off: 0 }; return render(); }
750
896
  if (S.qs) {
751
- const items = qsItems();
752
897
  if (k === 'esc') S.qs = null;
753
898
  else if (k === 'enter') {
754
- const it = items[S.qs.i]; S.qs = null;
899
+ const it = qsItems()[S.qs.i]; S.qs = null;
755
900
  if (it) {
756
901
  S.open = it.p.key; S.query = ''; queryChanged();
757
902
  const i = flatList().findIndex((x) => x.t === 's' && x.s.id === it.s.id); if (i >= 0) S.c = i;
@@ -759,7 +904,7 @@ function onKeyTree(raw) {
759
904
  }
760
905
  }
761
906
  else if (k === 'up') S.qs.i = Math.max(0, S.qs.i - 1);
762
- else if (k === 'down') S.qs.i = Math.min(items.length - 1, S.qs.i + 1);
907
+ else if (k === 'down') S.qs.i = Math.min(qsItems().length - 1, S.qs.i + 1);
763
908
  else { const r = editBuf(S.qs.q, S.qs.pc, k, raw); if (r) { if (r.s !== S.qs.q) S.qs.i = 0; S.qs.q = r.s; S.qs.pc = r.pos; } }
764
909
  return render();
765
910
  }
@@ -804,7 +949,7 @@ function onKeyTree(raw) {
804
949
  case 'enter': case 'right': case 'l':
805
950
  if (!e) break;
806
951
  if (e.t === 'p') { S.open = (e.open && k === 'enter') ? null : e.p.key; top(); }
807
- else if (e.t === 'm') { S.more.add(e.p.key); }
952
+ else if (e.t === 'm') { S.more.add(e.p.key); flatMemo = null; }
808
953
  else if (e.t === 'l') { const x = E.sessions.get(e.key); if (x) { x.unseen = false; E.shown = e.key; E.focus = 'right'; } return render(); }
809
954
  else return launch(e.p, e.t === 's' ? e.s : null);
810
955
  break;
@@ -820,9 +965,8 @@ function onKeyTree(raw) {
820
965
  case 'R': if (e && e.t === 's') { setPrompt(e.s.title, 'rename'); S.renameTarget = e.s; } break;
821
966
  case 'a':
822
967
  if (e && e.t === 's') {
823
- const i = CFG.archived.indexOf(e.s.id);
824
- if (i >= 0) CFG.archived.splice(i, 1); else CFG.archived.push(e.s.id);
825
- saveCfg(); S.flash = i >= 0 ? T.unarchMsg : T.archMsg;
968
+ const added = toggleArchive(e.s.id);
969
+ saveCfg(); S.flash = added ? T.archMsg : T.unarchMsg;
826
970
  }
827
971
  break;
828
972
  case 'c': {
@@ -834,15 +978,15 @@ function onKeyTree(raw) {
834
978
  case 'i': case 'f7':
835
979
  if (e && e.t === 's') {
836
980
  if (EMBED) return openGallery(e.p.name, e.s);
837
- imagesOf(e.s).then((imgs) => { // con tmux no hay panel propio: se abren en el visor del sistema
981
+ imagesOf(e.s).then(async (imgs) => { // con tmux no hay panel propio: se abren en el visor del sistema
838
982
  if (!imgs.length) return flash(T.noImages);
839
- openExternal(exportImages(imgs).dir); flash(T.imgFolder);
983
+ flash(await openerMessage(openExternal, exportImages(imgs).dir, T.imgFolder, T.imgOpenFailed));
840
984
  });
841
985
  } else if (EMBED) return openGalleryShown();
842
986
  break;
843
987
  case '[': return adjustSidebar(-4);
844
988
  case ']': return adjustSidebar(4);
845
- case 'H': S.showHidden = !S.showHidden; break;
989
+ case 'H': S.showHidden = !S.showHidden; invalidateView(); break;
846
990
  case 'p': case 'x':
847
991
  if (e) {
848
992
  const pr = e.p, f = k === 'p' ? 'pinned' : 'hidden';
@@ -869,51 +1013,79 @@ function idle() {
869
1013
  rows.forEach(([st, t], i) => { out += `\x1b[${top + art.length + gap + i};${Math.max(1, Math.floor((c - strW(t.replace('\u0001', ''))) / 2) + 1)}H${st}${paintMark(t)}${R}`; });
870
1014
  process.stdout.write(out);
871
1015
  };
1016
+ watchShutdown(); idleCursor = true;
872
1017
  draw(); process.stdout.on('resize', draw);
873
- const bye = () => { process.stdout.write('\x1b[?25h'); process.exit(0); };
874
- process.on('SIGTERM', bye); process.on('SIGHUP', bye);
875
1018
  setInterval(() => { /* mantiene vivo el panel */ }, 1 << 30);
876
1019
  }
877
1020
 
878
- function hasTmux() { try { return cp.spawnSync('tmux', ['-V'], { stdio: 'ignore' }).status === 0; } catch { return false; } }
1021
+ function installedTmux() {
1022
+ if (WIN) return null;
1023
+ const result = cp.spawnSync('tmux', ['-V'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
1024
+ return result.status === 0 ? parseTmuxVersion(result.stdout) : null;
1025
+ }
879
1026
 
880
1027
  /** Crea (o reabre) la sesión tmux: panel lateral con el hub + panel derecho para los chats. */
881
1028
  function bootstrap() {
882
1029
  const cols = process.stdout.columns || 120, rows = process.stdout.rows || 32;
883
- const sock = ['-L', 'hopdeck'];
884
- let confDir = null; // carpeta privada y aleatoria: un nombre fijo en /tmp permitiría que otro usuario del equipo colara su configuración
885
- const has = cp.spawnSync('tmux', [...sock, 'has-session', '-t', 'hopdeck'], { stdio: 'ignore' }).status === 0;
1030
+ const sock = ['-L', 'hopdeck'], name = sessionName(), target = '=' + name;
1031
+ const has = cp.spawnSync('tmux', [...sock, 'has-session', '-t', target], { stdio: 'ignore' }).status === 0;
1032
+ let created = false;
886
1033
  if (!has) {
887
- confDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hopdeck-tmux-'));
1034
+ const confDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hopdeck-tmux-'));
888
1035
  const conf = path.join(confDir, 'tmux.conf');
889
- fs.writeFileSync(conf, [
890
- 'set -g default-shell /bin/sh', 'set -g mouse on', 'set -g escape-time 10', 'set -g history-limit 50000',
891
- 'set -g focus-events on', 'set -g default-terminal "screen-256color"', 'set -ga terminal-overrides ",*:Tc"',
892
- 'set -g status on', 'set -g status-style "bg=default,fg=colour244"', 'set -g status-left ""', 'set -g status-right-length 120',
893
- `set -g status-right "#[fg=colour105]F1#[fg=colour244] ${T.bar1} #[fg=colour105]F2#[fg=colour244] ${T.bar2} #[fg=colour105]Ctrl+b d#[fg=colour244] ${T.bar3} "`,
894
- 'setw -g window-status-format ""', 'setw -g window-status-current-format ""',
895
- 'set -g pane-border-status top',
896
- 'set -g pane-border-format "#{?@hopdeck_title, #[fg=colour105#,bold]#{@hopdeck_title}#[default] ,}"',
897
- 'set -g pane-border-style "fg=colour239"', 'set -g pane-active-border-style "fg=colour105"',
898
- 'bind -n F1 select-pane -L', 'bind -n F2 select-pane -R', '',
899
- ].join('\n'));
900
- const me = [process.execPath, __filename];
901
- const t = (...a) => cp.execFileSync('tmux', [...sock, ...a], { encoding: 'utf8' }).trim();
902
- const right = t('-f', conf, 'new-session', '-d', '-s', 'hopdeck', '-x', String(cols), '-y', String(rows), '-P', '-F', '#{pane_id}',
903
- ['env', 'HOPDECK_INSIDE=1', ...me, '--idle'].map(sq).join(' '));
904
- try { fs.rmSync(confDir, { recursive: true, force: true }); } catch { /* */ } // tmux ya leyó la configuración
905
- const sw = CFG.sidebar ? clamp(CFG.sidebar, 24, 80) : clamp(Math.floor(cols * 0.3), 38, 46);
906
- const left = t('split-window', '-hb', '-t', right, '-l', String(sw), '-P', '-F', '#{pane_id}',
907
- ['env', 'HOPDECK_INSIDE=1', ...me, '--sidebar', ...extraArgs].map(sq).join(' '));
908
- t('select-pane', '-t', left);
909
- }
910
- cp.spawnSync('tmux', [...sock, 'attach', '-t', 'hopdeck'], { stdio: 'inherit' });
1036
+ try {
1037
+ fs.writeFileSync(conf, [
1038
+ 'set -g default-shell /bin/sh', 'set -g mouse on', 'set -g escape-time 10', 'set -g history-limit 50000',
1039
+ 'set -g focus-events on', 'set -g default-terminal "screen-256color"', ...(TRUE ? ['set -ga terminal-overrides ",*:Tc"'] : []),
1040
+ 'set -g status on', 'set -g status-style "bg=default,fg=colour244"', 'set -g status-left ""', 'set -g status-right-length 120',
1041
+ `set -g status-right "#[fg=colour105]F1#[fg=colour244] ${T.bar1} #[fg=colour105]F2#[fg=colour244] ${T.bar2} #[fg=colour105]Ctrl+b d#[fg=colour244] ${T.bar3} "`,
1042
+ 'setw -g window-status-format ""', 'setw -g window-status-current-format ""',
1043
+ 'set -g pane-border-status top',
1044
+ 'set -g pane-border-format "#{?@hopdeck_title, #[fg=colour105#,bold]#{@hopdeck_title}#[default] ,}"',
1045
+ 'set -g pane-border-style "fg=colour239"', 'set -g pane-active-border-style "fg=colour105"',
1046
+ 'bind -n F1 select-pane -L', 'bind -n F2 select-pane -R', '',
1047
+ ].join('\n'));
1048
+ const me = [process.execPath, __filename];
1049
+ const t = (...a) => cp.execFileSync('tmux', [...sock, ...a], { encoding: 'utf8' }).trim();
1050
+ const right = t('-f', conf, 'new-session', '-d', '-s', name, '-x', String(cols), '-y', String(rows), '-P', '-F', '#{pane_id}',
1051
+ ['env', 'HOPDECK_INSIDE=1', ...tmuxProviderEnv(), ...me, '--idle'].map(sq).join(' '));
1052
+ created = true;
1053
+ const sw = CFG.sidebar ? clamp(CFG.sidebar, 24, 80) : clamp(Math.floor(cols * 0.3), 38, 46);
1054
+ const left = t('split-window', '-hb', '-t', right, '-l', String(sw), '-P', '-F', '#{pane_id}',
1055
+ ['env', 'HOPDECK_INSIDE=1', ...tmuxProviderEnv(), ...me, '--sidebar', ...extraArgs].map(sq).join(' '));
1056
+ t('select-pane', '-t', left);
1057
+ } catch (err) {
1058
+ if (created) cp.spawnSync('tmux', [...sock, 'kill-session', '-t', target], { stdio: 'ignore' });
1059
+ console.error(T.tmuxStartFailed(clean(err.message)));
1060
+ process.exitCode = 1;
1061
+ return;
1062
+ } finally { try { fs.rmSync(confDir, { recursive: true, force: true }); } catch { /* */ } }
1063
+ }
1064
+ const result = cp.spawnSync('tmux', [...sock, 'attach', '-t', target], { stdio: 'inherit' });
1065
+ if (result.status !== 0) {
1066
+ if (created) cp.spawnSync('tmux', [...sock, 'kill-session', '-t', target], { stdio: 'ignore' });
1067
+ console.error(T.tmuxAttachFailed(result.error?.message || result.signal || result.status));
1068
+ process.exitCode = result.status || 1;
1069
+ }
911
1070
  }
912
1071
 
913
1072
  // ───────────────────────── modo embebido (PowerShell / sin tmux) ─────────────────────────
914
1073
  // Un terminal virtual (xterm headless + PTY) dibujado dentro del panel derecho.
1074
+ const UNIX_PTY = ['darwin', 'linux'].includes(process.platform);
1075
+ function spawnHelper() {
1076
+ const system = process.platform + '-' + process.arch;
1077
+ try {
1078
+ const entry = require.resolve('@lydell/node-pty');
1079
+ const platformEntry = require.resolve('@lydell/node-pty-' + system, { paths: [path.dirname(entry)] });
1080
+ const helper = path.resolve(path.dirname(platformEntry), '..', 'prebuilds', system, 'spawn-helper');
1081
+ return fs.existsSync(helper) ? helper : null;
1082
+ } catch { return null; }
1083
+ }
1084
+ const spawnHelperHint = (helper) => helper ? T.ptyChmod(sq(helper)) : T.ptyGeneric;
1085
+
915
1086
  function loadDeps() {
916
1087
  try { return { pty: require('@lydell/node-pty'), Terminal: require('@xterm/headless').Terminal }; } catch { return null; }
1088
+ finally { profile.first('loadDepsDone'); }
917
1089
  }
918
1090
 
919
1091
  /** Límites de un panel lateral al arrastrar su borde con el ratón: del 15 % al 50 % del ancho (y nunca menos de 20 columnas). */
@@ -954,14 +1126,19 @@ function dragPanel(which, x) {
954
1126
 
955
1127
  // ───────────────────────── panel de git (tercer panel, F8) ─────────────────────────
956
1128
  const GIT_W = 38, GIT_MIN_CHAT = 60;
957
- const GITC = new Map(); // carpeta → { t, loading, data }
958
- /** Estado de git de la carpeta, de la caché; si tiene más de 4 s se vuelve a leer en segundo plano. */
959
- function gitInfo(cwd) {
1129
+ const GITC = new LRU(32); // carpeta → { t, loading, read }
1130
+ let background;
1131
+ function gitInfo(cwd, checkNow = false) {
960
1132
  const hit = GITC.get(cwd), now = Date.now();
961
- if (hit && (hit.loading || now - hit.t < 4000)) return hit.data;
962
- GITC.set(cwd, { t: hit ? hit.t : 0, loading: true, data: hit ? hit.data : null });
963
- gitlib.readGit(cwd).then((data) => { GITC.set(cwd, { t: Date.now(), loading: false, data }); if (active && E.git) scheduleRender(); });
964
- return hit ? hit.data : null;
1133
+ if (hit && (hit.loading || (!checkNow && (background?.focused === false || now - hit.t < 4000)))) return hit.read?.data ?? null;
1134
+ const entry = { t: now, loading: true, read: hit?.read };
1135
+ GITC.set(cwd, entry);
1136
+ gitlib.refreshGit(cwd, entry.read).then((result) => {
1137
+ const changed = entry.read !== result;
1138
+ entry.read = result; entry.t = Date.now(); entry.loading = false;
1139
+ if (changed && GITC.peek(cwd) === entry && active && E.git) scheduleRender();
1140
+ });
1141
+ return entry.read?.data ?? null;
965
1142
  }
966
1143
  const gitCwd = () => {
967
1144
  const sh = E.sessions.get(E.shown);
@@ -1027,15 +1204,36 @@ function sgr(c, fgMode) {
1027
1204
  const isDef = fgMode ? c.isFgDefault() : c.isBgDefault();
1028
1205
  if (isDef) return '';
1029
1206
  const v = fgMode ? c.getFgColor() : c.getBgColor();
1030
- if (fgMode ? c.isFgRGB() : c.isBgRGB()) return `;${base + 8};2;${(v >> 16) & 255};${(v >> 8) & 255};${v & 255}`;
1207
+ if (fgMode ? c.isFgRGB() : c.isBgRGB()) {
1208
+ const r = (v >> 16) & 255, g = (v >> 8) & 255, b = v & 255;
1209
+ return TRUE ? `;${base + 8};2;${r};${g};${b}` : `;${base + 8};5;${rgbTo256(r, g, b)}`;
1210
+ }
1031
1211
  if (v < 8) return `;${base + v}`;
1032
1212
  if (v < 16) return `;${base + 60 + v - 8}`;
1033
1213
  return `;${base + 8};5;${v}`;
1034
1214
  }
1035
1215
 
1216
+ const termRows = new WeakMap();
1036
1217
  function termRow(term, y, width, sel, from = 0) {
1037
- const buf = term.buffer.active;
1038
- const line = buf.getLine(buf.viewportY + y);
1218
+ const buf = term.buffer.active, line = buf.getLine(buf.viewportY + y);
1219
+ // xterm 6 guarda los caracteres simples y sus estilos en tres enteros por celda.
1220
+ // Las celdas combinadas o con atributos extendidos usan el dibujo normal.
1221
+ const raw = line?._line, data = raw?._data;
1222
+ if (sel || from || width !== term.cols || !(data instanceof Uint32Array) || data.length !== line.length * 3 ||
1223
+ !raw._combined || !raw._extendedAttrs || Object.keys(raw._combined).length || Object.keys(raw._extendedAttrs).length) {
1224
+ return drawTermRow(term, buf, line, width, sel, from);
1225
+ }
1226
+ let cache = termRows.get(term);
1227
+ if (!cache) { cache = new Map(); termRows.set(term, cache); }
1228
+ const bytes = Buffer.from(data.buffer, data.byteOffset, data.byteLength), hit = cache.get(raw);
1229
+ if (hit && hit.width === width && hit.bytes.equals(bytes)) return hit.row;
1230
+ if (!hit && cache.size >= term.rows * 2) cache.delete(cache.keys().next().value);
1231
+ const row = drawTermRow(term, buf, line, width, sel, from);
1232
+ cache.set(raw, { width, bytes: Buffer.from(bytes), row });
1233
+ return row;
1234
+ }
1235
+
1236
+ function drawTermRow(term, buf, line, width, sel, from) {
1039
1237
  let out = '', used = 0, last = null;
1040
1238
  if (line) {
1041
1239
  const cell = buf.getNullCell();
@@ -1100,7 +1298,7 @@ function loaderRow(y, width, height, title) {
1100
1298
  // ───────────────────────── imágenes de las conversaciones ─────────────────────────
1101
1299
  // Claude Code guarda las imágenes adjuntas como bloques base64 dentro del historial. Se muestran con
1102
1300
  // "medios bloques" (▀: dos píxeles por celda), que funciona en cualquier terminal con color.
1103
- const IMG = new Map(); // archivo → { m, images }
1301
+ const IMG = new LRU(3, 150 * 1024 * 1024); // archivo → { m, images }
1104
1302
 
1105
1303
  const maxImages = () => (CFG.maxImages > 0 ? CFG.maxImages : 200); // configurable en ~/.hopdeck.json
1106
1304
  const previewMsgs = () => (CFG.previewMsgs > 0 ? CFG.previewMsgs : 12);
@@ -1110,20 +1308,34 @@ async function imagesOf(x) {
1110
1308
  const key = provider.isCodex ? 'codex:' + x.id : x.file, hit = IMG.get(key);
1111
1309
  if (hit && hit.m === x.mtime && Date.now() < hit.until) return hit.images;
1112
1310
  const entry = { m: x.mtime, until: provider.isCodex ? Date.now() + 2000 : Infinity,
1113
- images: provider.isCodex ? codexHistory.imagesSession(x, maxImages()) : extractImages(x.file) };
1311
+ images: provider.isCodex ? codexHistory().imagesSession(x, maxImages()) : extractImages(x.file) };
1114
1312
  IMG.set(key, entry);
1115
- try { return await entry.images; } catch (err) { if (IMG.get(key) === entry) IMG.delete(key); throw err; }
1313
+ try {
1314
+ const list = await entry.images;
1315
+ if (IMG.peek(key) === entry) IMG.weigh(key, list.reduce((bytes, im) => bytes + im.data.length * 2, 0));
1316
+ return list;
1317
+ } catch (err) { if (IMG.peek(key) === entry) IMG.delete(key); throw err; }
1116
1318
  }
1117
1319
 
1118
1320
  /** Abre un archivo o carpeta con el programa por defecto del sistema. */
1119
- function openExternal(target) {
1120
- if (process.env.HOPDECK_OPEN_LOG) { try { fs.appendFileSync(process.env.HOPDECK_OPEN_LOG, target + '\n'); } catch { /* */ } return; } // pruebas: no se abre ningún visor
1121
- const quiet = (cmd, args) => { try { const c = cp.spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true }); c.on('error', () => {}); c.unref(); } catch { /* */ } };
1122
- if (WIN) quiet('cmd', ['/c', 'start', '', target]);
1123
- else if (process.platform === 'darwin') quiet('open', [target]);
1124
- else if (process.env.WSL_DISTRO_NAME) { try { quiet('explorer.exe', [cp.execFileSync('wslpath', ['-w', target], { encoding: 'utf8' }).trim()]); } catch { quiet('xdg-open', [target]); } }
1125
- else quiet('xdg-open', [target]);
1321
+ function openExternal(target, { platform = process.platform, env = process.env, spawn = cp.spawn, onError } = {}) {
1322
+ if (env.HOPDECK_OPEN_LOG) {
1323
+ try { fs.appendFileSync(env.HOPDECK_OPEN_LOG, target + '\n'); return Promise.resolve(true); } catch { return Promise.resolve(false); }
1324
+ }
1325
+ const open = (command, file) => spawnOpener(command, file, { spawn, onError });
1326
+ if (platform === 'win32') return open('explorer.exe', target);
1327
+ if (platform === 'darwin') return open('open', target);
1328
+ if (isWSL({ platform, env })) {
1329
+ try { return open('explorer.exe', cp.execFileSync('wslpath', ['-w', target], { encoding: 'utf8' }).trim()); } catch { /* */ }
1330
+ }
1331
+ return open('xdg-open', target);
1332
+ }
1333
+ async function openerMessage(open, target, success, failed) {
1334
+ let missing = false;
1335
+ const ok = await open(target, { onError: (error, command) => { missing = process.platform === 'linux' && command === 'xdg-open' && error.code === 'ENOENT'; } });
1336
+ return ok ? success : failed(missing);
1126
1337
  }
1338
+ function openerNote(t) { E.note = { t, until: Date.now() + 2500 }; scheduleRender(); }
1127
1339
 
1128
1340
  /**
1129
1341
  * Extensión de una imagen según sus primeros bytes (no según el "media_type" del historial, que no es de fiar:
@@ -1150,13 +1362,14 @@ function exportImages(images) {
1150
1362
  return ext ? f : null; // lo que no es una imagen reconocible se guarda como .bin y no se abre
1151
1363
  }) };
1152
1364
  }
1153
- function cleanExports() { for (const d of EXPORT_DIRS) { try { fs.rmSync(d, { recursive: true, force: true }); } catch { /* */ } } EXPORT_DIRS.clear(); }
1365
+ function cleanExports() { for (const d of EXPORT_DIRS) { try { fs.rmSync(d, { recursive: true, force: true, maxRetries: 3, retryDelay: 100 }); } catch { /* */ } } EXPORT_DIRS.clear(); }
1154
1366
 
1155
1367
  async function openGallery(project, x) {
1156
1368
  const g = { project, title: x.title, file: x.file, id: x.id, images: [], i: 0, loading: true, pending: false, dec: new Map(), cache: new Map() };
1369
+ if (E.hover) E.hover.g.pending = false;
1157
1370
  E.gallery = g; ensureSpin(); render();
1158
1371
  try { g.images = await imagesOf(x); } catch { g.images = []; }
1159
- g.loading = false; render();
1372
+ g.loading = false; if (E.gallery === g && active) render();
1160
1373
  }
1161
1374
 
1162
1375
  /** Galería del chat abierto: si es nuevo, su archivo es la sesión más reciente del proyecto. */
@@ -1229,24 +1442,17 @@ async function openGalleryShown() {
1229
1442
  /** Cuadro flotante con la imagen del hover: se dibuja sobre el chat, pegado a la marca [Image #N], sin tapar el resto. */
1230
1443
  function hoverPopup(hv, rw, th) {
1231
1444
  const g = hv.g, img = g.images[0]; if (!img) return null;
1232
- if (!g.dec.has(0) && !g.pending) {
1233
- g.pending = true; ensureSpin();
1234
- setImmediate(() => { let d = false; try { d = decodeImage(img) || false; } catch { d = false; } g.dec.set(0, d); g.pending = false; if (active) render(); });
1235
- }
1445
+ const sxOn = sixelOn();
1446
+ const layout = sxOn ? { maxW: Math.max(8, Math.min(rw - 6, 36)), maxH: Math.max(2, Math.min(th - 5, 9)), cw: E.cell.w, ch: E.cell.h }
1447
+ : { maxW: Math.max(8, Math.min(rw - 6, 96)), maxH: Math.max(2, Math.min(th - 6, 18)) * 2 };
1448
+ const { result, key } = galleryImage(g, layout, () => E.hover === hv && !E.gallery);
1236
1449
  const d = g.dec.get(0), lab = ` [Image #${hv.n}] `;
1237
1450
  let rows, tw, sx = null;
1238
- if (d && d.rgba && sixelOn()) { // imagen real: se deja un hueco en blanco del tamaño de la imagen y se dibuja encima con Sixel
1239
- const cw = E.cell.w, ch = E.cell.h, maxCols = Math.max(8, Math.min(rw - 6, 36)), maxRows = Math.max(2, Math.min(th - 5, 9)); // vista previa pequeña: como mucho 36×9 celdas
1240
- const k = Math.min((maxCols * cw) / d.w, (maxRows * ch) / d.h, 3);
1241
- const iw = Math.max(1, Math.min(maxCols, Math.round((d.w * k) / cw))), ih = Math.max(1, Math.min(maxRows, Math.round((d.h * k) / ch))), key = `sx:${iw}x${ih}`;
1242
- let data = g.cache.get(key);
1243
- if (!data) { data = encodeSixel(scaleBox(d.rgba, d.w, d.h, iw * cw, ih * ch), iw * cw, ih * ch); g.cache.clear(); g.cache.set(key, data); }
1244
- sx = { data, iw, ih, key }; tw = iw; rows = Array.from({ length: ih }, () => ' '.repeat(iw));
1245
- } else if (d && d.rgba) {
1246
- const sz = fitSize(d.w, d.h, Math.max(8, Math.min(rw - 6, 96)), Math.max(2, Math.min(th - 6, 18)) * 2), key = `${sz.tw}x${sz.th}`;
1247
- let hb = g.cache.get(key);
1248
- if (!hb) { hb = halfBlocks(scaleBox(d.rgba, d.w, d.h, sz.tw, sz.th), sz.tw, sz.th); g.cache.clear(); g.cache.set(key, hb); }
1249
- rows = hb; tw = sz.tw;
1451
+ if (result?.iw) {
1452
+ const { display: data, iw, ih } = result;
1453
+ sx = { data, iw, ih, key: hv.k + ':' + key }; tw = iw; rows = Array.from({ length: ih }, () => ' '.repeat(iw));
1454
+ } else if (result) {
1455
+ rows = result.display; tw = result.tw;
1250
1456
  } else {
1251
1457
  const txt = d === undefined ? spin() + ' …' : `${T.imgNoPrev} (${img.media || '?'})`; // el formato ayuda a saber por qué no se pudo leer
1252
1458
  tw = Math.max(strW(lab) + 1, Math.min(strW(txt) + 2, Math.max(8, rw - 4)));
@@ -1268,7 +1474,7 @@ async function imageForMarker(sh, n, y) {
1268
1474
  try {
1269
1475
  const sess = await shownSession(sh);
1270
1476
  if (!sess) return null;
1271
- if (provider.isCodex) return await codexHistory.imageForNumber(sess, n, codexMarkerOffset(sh.term, y, n));
1477
+ if (provider.isCodex) return await codexHistory().imageForNumber(sess, n, codexMarkerOffset(sh.term, y, n));
1272
1478
  const imgs = await imagesOf(sess);
1273
1479
  let img = imgs.find((im) => im.n === n) || (imgs.some((im) => im.n) ? null : imgs[n - 1]) || null;
1274
1480
  if (!img && imgs.length >= maxImages()) img = await images.findImageByNumber(sess.file, n); // pasó el límite de la galería: se busca en todo el archivo
@@ -1294,12 +1500,10 @@ function codexMarkerOffset(term, y, n) {
1294
1500
  */
1295
1501
  async function openMarkerImage(sh, n, y) {
1296
1502
  const img = await imageForMarker(sh, n, y);
1297
- const note = (t) => { E.note = { t, until: Date.now() + 2500 }; scheduleRender(); };
1298
- if (!img) return note(T.hoverMiss(n));
1503
+ if (!img) return openerNote(T.hoverMiss(n));
1299
1504
  const { files } = exportImages([img]);
1300
- if (!files[0]) return note(T.imgNoPrev); // no es una imagen reconocible: no se abre
1301
- openExternal(files[0]);
1302
- note(T.imgOpened(n));
1505
+ if (!files[0]) return openerNote(T.imgNoPrev); // no es una imagen reconocible: no se abre
1506
+ openerNote(await openerMessage(openExternal, files[0], T.imgOpened(n), T.imgOpenFailed));
1303
1507
  }
1304
1508
 
1305
1509
  function hoverChat(sh, x, y) {
@@ -1322,6 +1526,30 @@ function hoverChat(sh, x, y) {
1322
1526
  })();
1323
1527
  }
1324
1528
 
1529
+ function pruneGallery(g) {
1530
+ for (const map of [g.dec, g.cache]) for (const index of map.keys()) if (Math.abs(index - g.i) > 2) map.delete(index);
1531
+ }
1532
+
1533
+ function galleryImage(g, layout, visible) {
1534
+ const i = g.i, key = `${layout.maxW}:${layout.maxH}:${layout.cw || 0}:${layout.ch || 0}`;
1535
+ const hit = g.cache.get(i), decoded = g.dec.get(i);
1536
+ if (hit?.key === key) { g.pending = false; return { result: hit.result, key }; }
1537
+ if (decoded === false) { g.pending = false; return {}; }
1538
+ if (g.pending?.i === i && g.pending.key === key) return {};
1539
+ const job = g.pending = { i, key };
1540
+ const current = () => visible() && g.i === i && g.pending === job;
1541
+ if (decoded) g.dec.delete(i); // el búfer pasa al hilo y se recupera con el resultado
1542
+ ensureSpin();
1543
+ imageWorker.request({ img: decoded ? null : g.images[i], decoded, layout }, current).then((result) => {
1544
+ if (!current()) { if (g.pending === job) g.pending = false; return; }
1545
+ g.pending = false; g.dec.set(i, result?.decoded || false);
1546
+ if (result) g.cache.set(i, { key, result: { ...result, decoded: undefined, w: result.decoded.w, h: result.decoded.h } });
1547
+ else g.cache.delete(i);
1548
+ if (active) scheduleRender();
1549
+ });
1550
+ return {};
1551
+ }
1552
+
1325
1553
  function galleryRows(rw, th, g = E.gallery) {
1326
1554
  const rows = [], blank = ' '.repeat(rw);
1327
1555
  const center = (segs) => { const t = segs.map((q) => q[0]).join(''); const pad = Math.max(0, Math.floor((rw - strW(t)) / 2)); return ' '.repeat(pad) + fit(segs, Math.max(1, rw - pad)); };
@@ -1330,17 +1558,11 @@ function galleryRows(rw, th, g = E.gallery) {
1330
1558
  else if (!g.images.length) content = [center([[T.noImages, C.dim]])];
1331
1559
  else {
1332
1560
  const img = g.images[g.i];
1333
- if (!g.dec.has(g.i) && !g.pending) {
1334
- g.pending = true; ensureSpin();
1335
- setImmediate(() => { let d = false; try { d = decodeImage(img) || false; } catch { d = false; } g.dec.set(g.i, d); g.pending = false; if (active) render(); });
1336
- }
1337
- const d = g.dec.get(g.i);
1338
- if (d === undefined) content = [center([[spin() + ' ' + T.decoding, C.accent]])];
1339
- else if (d === false) content = [center([[T.imgNoPrev, C.warn]]), center([[img.media + ' · o', C.dim]])];
1561
+ const { result } = galleryImage(g, { maxW: rw, maxH: body * 2 }, () => E.gallery === g);
1562
+ if (g.dec.get(g.i) === false) content = [center([[T.imgNoPrev, C.warn]]), center([[img.media + ' · o', C.dim]])];
1563
+ else if (!result) content = [center([[spin() + ' ' + T.decoding, C.accent]])];
1340
1564
  else {
1341
- const { tw, th: th2 } = fitSize(d.w, d.h, rw, body * 2), key = `${g.i}:${tw}x${th2}`;
1342
- let img2 = g.cache.get(key);
1343
- if (!img2) { img2 = halfBlocks(scaleBox(d.rgba, d.w, d.h, tw, th2), tw, th2); g.cache.clear(); g.cache.set(key, img2); }
1565
+ const { tw, display: img2 } = result;
1344
1566
  const pad = Math.floor((rw - tw) / 2);
1345
1567
  content = img2.map((l) => ' '.repeat(pad) + l + ' '.repeat(Math.max(0, rw - pad - tw)));
1346
1568
  }
@@ -1358,22 +1580,25 @@ function galleryKey(raw) {
1358
1580
  else if (k === 'right' || k === 'l' || k === 'n') g.i = Math.min(Math.max(0, n - 1), g.i + 1);
1359
1581
  else if (k === 'home') g.i = 0;
1360
1582
  else if (k === 'end') g.i = Math.max(0, n - 1);
1361
- else if (k === 'o' && n) { cleanExports(); const { files } = exportImages(g.images); if (files[g.i]) { openExternal(files[g.i]); E.note = { t: T.imgFolder, until: Date.now() + 2500 }; } else E.note = { t: T.imgNoPrev, until: Date.now() + 2500 }; }
1362
- render();
1583
+ else if (k === 'o' && n) { cleanExports(); const { files } = exportImages(g.images); if (files[g.i]) openerMessage(openExternal, files[g.i], T.imgFolder, T.imgOpenFailed).then(openerNote); else E.note = { t: T.imgNoPrev, until: Date.now() + 2500 }; }
1584
+ if (g.pending && g.pending.i !== g.i) g.pending = false;
1585
+ pruneGallery(g); render();
1363
1586
  }
1364
1587
 
1365
1588
  // Vista previa de los últimos mensajes de la conversación seleccionada (cuando no hay un chat abierto).
1366
- const PREV = new Map();
1589
+ const PREV = new LRU(200);
1367
1590
  function previewFor(x) {
1368
1591
  const key = provider.isCodex ? x.id : x.file;
1369
1592
  const hit = PREV.get(key);
1370
1593
  if (hit && hit.m === x.mtime) return hit.msgs;
1371
- PREV.set(key, { m: x.mtime, msgs: null });
1594
+ const entry = { m: x.mtime, msgs: null };
1595
+ PREV.set(key, entry);
1596
+ const finish = (msgs) => { entry.msgs = msgs; if (PREV.peek(key) === entry && active) render(); };
1372
1597
  if (provider.isCodex) {
1373
- codexHistory.previewSession(x, previewMsgs()).then((msgs) => {
1374
- PREV.set(key, { m: x.mtime, msgs }); if (active) render();
1598
+ codexHistory().previewSession(x, previewMsgs()).then((msgs) => {
1599
+ finish(msgs);
1375
1600
  }, () => {
1376
- PREV.set(key, { m: x.mtime, msgs: x.first ? [{ role: 'user', text: x.first }] : [] }); if (active) render();
1601
+ finish(x.first ? [{ role: 'user', text: x.first }] : []);
1377
1602
  });
1378
1603
  return null;
1379
1604
  }
@@ -1395,8 +1620,7 @@ function previewFor(x) {
1395
1620
  }
1396
1621
  } finally { await fh.close(); }
1397
1622
  } catch { msgs = []; }
1398
- PREV.set(x.file, { m: x.mtime, msgs });
1399
- if (active) render();
1623
+ finish(msgs);
1400
1624
  })();
1401
1625
  return null;
1402
1626
  }
@@ -1424,7 +1648,7 @@ function previewRows(msgs, width, height, info = '') {
1424
1648
 
1425
1649
  /** Título del panel del chat: proyecto › conversación ⎇ rama */
1426
1650
  // ── Estadísticas de la conversación (mensajes, tokens, herramientas, modelo), en la fila del título del chat ──
1427
- const STATS = new Map(); // archivo → { st, sum, at, busy, m, z }; solo se guardan las últimas conversaciones vistas
1651
+ const STATS = new LRU(12); // archivo → { st, sum, at, busy, m, z }; solo se guardan las últimas conversaciones vistas
1428
1652
  let sidIdx = { src: null, map: new Map() };
1429
1653
  /** Archivo de una conversación por su id (la lista se recorre una vez por escaneo). */
1430
1654
  function fileOfSid(sid) {
@@ -1440,8 +1664,7 @@ function chatStats(file) {
1440
1664
  if (provider.isCodex) return undefined;
1441
1665
  if (!file) return undefined;
1442
1666
  let e = STATS.get(file);
1443
- if (e) { STATS.delete(file); STATS.set(file, e); } // los más recientes al final
1444
- else { e = { st: stats.newState(), sum: null, at: 0, busy: false, m: -1, z: -1 }; STATS.set(file, e); if (STATS.size > 12) STATS.delete(STATS.keys().next().value); }
1667
+ if (!e) { e = { st: stats.newState(), sum: null, at: 0, busy: false, m: -1, z: -1 }; STATS.set(file, e); }
1445
1668
  const now = Date.now();
1446
1669
  if (!e.busy && now - e.at > (e.sum ? 3000 : 0)) {
1447
1670
  e.at = now;
@@ -1483,6 +1706,7 @@ function headerRow(sh, width, sum) {
1483
1706
  }
1484
1707
 
1485
1708
  function renderEmbed() {
1709
+ spinVisible = false;
1486
1710
  const { W, H, SW, GW, rw, rh, th } = embedLayout();
1487
1711
  if (W < 70 || H < 12) { process.stdout.write('\x1b[2J\x1b[H' + T.small); invalidate(); return; }
1488
1712
  const left = SW ? frameTree(SW, rh) : null;
@@ -1490,25 +1714,26 @@ function renderEmbed() {
1490
1714
  const rowsOut = [];
1491
1715
  // sin chat abierto: vista previa de la conversación seleccionada en la lista
1492
1716
  const selEnt = !sh && !S.help && !S.qs ? flatList()[S.c] : null;
1493
- const pvMsgs = selEnt && selEnt.t === 's' ? previewFor(selEnt.s) : null;
1717
+ const pvMsgs = !cachePaint && selEnt?.t === 's' ? previewFor(selEnt.s) : null;
1494
1718
  const pvRows = pvMsgs && pvMsgs.length ? previewRows(pvMsgs, rw, th, T.prevInfo(ago(selEnt.s.mtime), pvMsgs.length)) : null;
1495
1719
  const hdr = sh || (selEnt && selEnt.t === 's' ? { project: selEnt.p.name, title: selEnt.s.title, branch: gitBranch(selEnt.p.cwd), file: selEnt.s.file } : null);
1496
1720
  const gRows = E.gallery ? galleryRows(rw, th) : null;
1497
1721
  const hv = !E.gallery && sh && sh.ready && E.hover && !E.hover.g.loading && E.hover.g.images.length ? E.hover : null;
1498
1722
  const pop = hv ? hoverPopup(hv, rw, th) : null;
1723
+ if (gRows ? E.gallery.loading || E.gallery.pending : sh && (!sh.ready || (pop && hv.g.pending))) spinVisible = true;
1499
1724
  const popRow = (ty) => (pop && ty >= pop.top && ty < pop.top + pop.rows.length
1500
1725
  ? termRow(sh.term, ty, pop.left, selRange(ty, rw)) + pop.rows[ty - pop.top] + termRow(sh.term, ty, rw - pop.left - pop.bw, selRange(ty, rw), pop.left + pop.bw)
1501
1726
  : null);
1502
1727
  const div = (E.drag === 'side' || E.focus === 'right' ? C.accent : C.faint) + '│' + R;
1503
1728
  const gdiv = (E.drag === 'git' ? C.accent : C.faint) + '│' + R; // la línea que se está arrastrando se resalta
1504
1729
  const gitR = GW ? gitRows(GW, rh) : null;
1730
+ const gd = E.gallery && (E.gallery.dec.get(E.gallery.i) || E.gallery.cache.get(E.gallery.i)?.result);
1505
1731
  for (let y = 0; y < rh; y++) {
1506
1732
  const ty = y - 2; // las 2 primeras filas del panel derecho son el título y su línea
1507
- const gd = E.gallery && E.gallery.dec.get(E.gallery.i);
1508
1733
  const right = gRows ? (y === 0 ? fit([[' ' + E.gallery.project, C.accent + C.bold], [' › ' + E.gallery.title, C.text],
1509
1734
  [E.gallery.images.length ? ` ▣ ${E.gallery.i + 1}/${E.gallery.images.length}` + (gd ? ` · ${gd.w}×${gd.h}` : '') : '', C.dim]], rw)
1510
1735
  : y === 1 ? C.faint + '─'.repeat(rw) + R : gRows[ty])
1511
- : y === 0 ? headerRow(hdr, rw, hdr ? chatStats(chatFile(hdr)) : undefined) : y === 1 ? C.faint + '─'.repeat(rw) + R
1736
+ : y === 0 ? headerRow(hdr, rw, hdr && !cachePaint ? chatStats(chatFile(hdr)) : undefined) : y === 1 ? C.faint + '─'.repeat(rw) + R
1512
1737
  : sh && sh.ready ? (popRow(ty) || termRow(sh.term, ty, rw, selRange(ty, rw))) : sh ? loaderRow(ty, rw, th, sh.title) : pvRows ? pvRows[ty] : idleRow(ty, rw, th);
1513
1738
  rowsOut.push((left ? (left[y] || ' '.repeat(SW)) + div : '') + right + (gitR ? gdiv + gitR[y] : ''));
1514
1739
  }
@@ -1543,6 +1768,7 @@ function renderEmbed() {
1543
1768
  cur = `\x1b[${Math.min(th, b.cursorY + 1) + 2};${(SW ? SW + 1 : 0) + 1 + Math.min(rw - 1, b.cursorX)}H\x1b[?25h`;
1544
1769
  }
1545
1770
  process.stdout.write((changes || sx ? '\x1b[?2026h\x1b[?25l' + changes + sx : '\x1b[?25l') + cur + (changes || sx ? '\x1b[?2026l' : ''));
1771
+ if (SW) profile.first('firstListRender');
1546
1772
  }
1547
1773
 
1548
1774
  function scheduleRender() {
@@ -1550,7 +1776,7 @@ function scheduleRender() {
1550
1776
  E.pend = setTimeout(() => { E.pend = null; render(); }, 16);
1551
1777
  }
1552
1778
 
1553
- function embedLive() { S.live = new Set([...E.sessions.keys(), ...[...E.sessions.values()].map((x) => x.sid).filter(Boolean)]); }
1779
+ function embedLive() { invalidateView(); S.live = new Set([...E.sessions.keys(), ...[...E.sessions.values()].map((x) => x.sid).filter(Boolean)]); }
1554
1780
 
1555
1781
  function embedLaunch(project, session) {
1556
1782
  if (!fs.existsSync(project.cwd)) { flash(T.missing + ': ' + shortPath(project.cwd)); return; }
@@ -1561,13 +1787,18 @@ function embedLaunch(project, session) {
1561
1787
  if (ex) { const x = E.sessions.get(ex); x.unseen = false; E.shown = ex; E.focus = 'right'; render(); return; }
1562
1788
  const { pty, Terminal } = E.deps; const { rw, th } = embedLayout();
1563
1789
  const args = provider.launchArgs(session, extraArgs);
1564
- const win = WIN && !/\.exe$/i.test(bin);
1790
+ if (WIN && !/\.(exe|com|cmd|bat)$/i.test(bin)) return flash(T.winUnsupported(shortPath(bin)));
1791
+ const batch = WIN && /\.(cmd|bat)$/i.test(bin);
1565
1792
  const env = { ...process.env, HOPDECK_SKIP: '1', HOPDECK_INSIDE: '1', TERM: 'xterm-256color', COLORTERM: 'truecolor' };
1566
1793
  let p;
1567
1794
  try {
1568
- p = pty.spawn(win ? (process.env.ComSpec || 'cmd.exe') : bin, win ? ['/d', '/c', bin, ...args] : args,
1795
+ p = pty.spawn(batch ? (process.env.ComSpec || 'cmd.exe') : bin, batch ? `/d /s /c "${cmdLine(bin, args)}"` : args,
1569
1796
  { name: 'xterm-256color', cols: rw, rows: th, cwd: project.cwd, env });
1570
- } catch (e) { flash(String(e.message).split('\n')[0]); return; }
1797
+ } catch (e) {
1798
+ flash(e.code === 'HOPDECK_CMD_LINE' ? T.winBadArgs : UNIX_PTY && /posix_spawnp failed/i.test(e.message)
1799
+ ? spawnHelperHint(spawnHelper()) : String(e.message).split('\n')[0]);
1800
+ return;
1801
+ }
1571
1802
  const term = new Terminal({ cols: rw, rows: th, allowProposedApi: true, scrollback: 2000 });
1572
1803
  const sess = { p, term, cursorHidden: false, ready: false, lastData: Date.now(), quietUntil: 0, working: false, busy: false, unseen: false, title: session ? session.title : T.newChat, t0: Date.now(), project: project.name, cwd: project.cwd, sid: session ? session.id : null, closing: false, branch: gitBranch(project.cwd) };
1573
1804
  if (provider.isCodex) sess.knownIds = new Set(project.sessions.map((s) => s.id));
@@ -1578,9 +1809,9 @@ function embedLaunch(project, session) {
1578
1809
  p.onData((d) => {
1579
1810
  if (Date.now() >= sess.quietUntil) sess.lastData = Date.now(); // lo que Claude repinta justo tras redimensionar no es trabajo
1580
1811
  // "listo" = ya hay texto visible. En Windows ConPTY manda secuencias de control al arrancar, antes de que Claude dibuje nada.
1581
- term.write(d, () => { if (!sess.ready && hasContent(term)) sess.ready = true; if (E.shown === key) scheduleRender(); });
1812
+ term.write(d, () => { if (!sess.ready && hasContent(term)) sess.ready = true; if (background?.focused === false) background.update(); if (E.shown === key) scheduleRender(); });
1582
1813
  });
1583
- setTimeout(() => { if (!sess.ready) { sess.ready = true; if (E.shown === key) scheduleRender(); } }, 20000); // por si el chat nunca imprime
1814
+ setTimeout(() => { if (!sess.ready) { sess.ready = true; if (E.shown === key) scheduleRender(); } }, 20000).unref(); // por si el chat nunca imprime
1584
1815
  p.onExit((ev) => {
1585
1816
  const code = ev && ev.exitCode;
1586
1817
  if ((code || !sess.ready) && !sess.closing) flash(T.exited(code || 0));
@@ -1622,7 +1853,12 @@ function selText(sh, sl) {
1622
1853
  function copySelection(sh) {
1623
1854
  const sl = E.sel; E.sel = null; stopSelScroll();
1624
1855
  const t = sl && sh ? selText(sh, sl) : '';
1625
- if (t) { copyText(t); E.note = { t: T.copied(t.length), until: Date.now() + 3000 }; }
1856
+ if (t) copyText(t).then((result) => {
1857
+ E.note = { t: result === 'ok' ? T.copied(t.length) : result === 'missing' && process.platform === 'linux' && !isWSL()
1858
+ ? T.copyNoTool(!!process.env.WAYLAND_DISPLAY) : T.copyFailed,
1859
+ until: Date.now() + 3000 };
1860
+ if (active) render();
1861
+ });
1626
1862
  }
1627
1863
 
1628
1864
  // Al arrastrar contra el borde de arriba o de abajo, el chat se desplaza solo (aunque el ratón se quede quieto) y la selección sigue.
@@ -1643,17 +1879,6 @@ function selEdge(sh, row) {
1643
1879
  if (dir && sh.term.buffer.active.type !== 'alternate') { if (!selTimer) { selTimer = setInterval(selScrollTick, 60); selScrollTick(); } }
1644
1880
  else if (selTimer) { clearInterval(selTimer); selTimer = null; }
1645
1881
  }
1646
- /** Copia al portapapeles: OSC 52 (la mayoría de terminales) + comando del sistema como respaldo. */
1647
- function copyText(t) {
1648
- if (process.env.HOPDECK_COPY_LOG) { try { fs.appendFileSync(process.env.HOPDECK_COPY_LOG, JSON.stringify(t) + '\n'); } catch { /* */ } return; } // pruebas: se anota en un archivo y no se toca el portapapeles
1649
- try { process.stdout.write(`\x1b]52;c;${Buffer.from(t).toString('base64')}\x07`); } catch { /* */ }
1650
- const run = (cmd, args) => { try { const c = cp.spawn(cmd, args, { stdio: ['pipe', 'ignore', 'ignore'] }); c.on('error', () => {}); c.stdin.on('error', () => {}); c.stdin.end(t); } catch { /* */ } };
1651
- if (process.platform === 'darwin') run('pbcopy', []);
1652
- else if (WIN) run('powershell', ['-NoProfile', '-Command', '[Console]::InputEncoding=[Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())']);
1653
- else if (process.env.WAYLAND_DISPLAY) run('wl-copy', []);
1654
- else run('xclip', ['-selection', 'clipboard']);
1655
- }
1656
-
1657
1882
  function scrollSession(sh, lines) { // lines > 0 = hacia arriba
1658
1883
  if (!sh || sh.term.buffer.active.type === 'alternate') return;
1659
1884
  sh.term.scrollLines(-lines);
@@ -1703,7 +1928,7 @@ function sidebarMouse(b, x, y, type, rows = process.stdout.rows || 30) {
1703
1928
  if (flatList()[i]) { S.c = i; return onKeyTree('\r'); }
1704
1929
  }
1705
1930
 
1706
- function onMouse(b, x, y, type) {
1931
+ function onMouse(b, x, y, type, movedBetweenFrames = false) {
1707
1932
  if (E.gallery) return;
1708
1933
  const { SW, GW, rw, rh, th } = embedLayout();
1709
1934
  const sh = E.sessions.get(E.shown);
@@ -1738,7 +1963,7 @@ function onMouse(b, x, y, type) {
1738
1963
  // celda del chat bajo el ratón; `y` es la línea del historial (ver selRange), así que sirve aunque el chat esté desplazado
1739
1964
  const cell = () => { const L = embedLayout(); return { x: clamp(x - x0, 0, L.rw - 1), y: sh.term.buffer.active.viewportY + clamp(y - 3, 0, L.th - 1) }; };
1740
1965
  if ((b & 32) && (b & 3) === 0) { // arrastre
1741
- if (E.sel && E.sel.down && sh) { E.sel.b = cell(); if (E.sel.a.x !== E.sel.b.x || E.sel.a.y !== E.sel.b.y) E.sel.moved = true; selEdge(sh, y - 3); render(); }
1966
+ if (E.sel && E.sel.down && sh) { E.sel.b = cell(); if (movedBetweenFrames || E.sel.a.x !== E.sel.b.x || E.sel.a.y !== E.sel.b.y) E.sel.moved = true; selEdge(sh, y - 3); render(); }
1742
1967
  return;
1743
1968
  }
1744
1969
  if (type === 'm') { // soltar
@@ -1750,7 +1975,7 @@ function onMouse(b, x, y, type) {
1750
1975
  if (sh && sh.ready) {
1751
1976
  const row = sl.a.y - sh.term.buffer.active.viewportY, hit = imageMarkerAt(sh.term, row, sl.a.x);
1752
1977
  if (hit) openMarkerImage(sh, hit.n, row);
1753
- else { const url = urlAt(sh.term, row, sl.a.x); if (url && openUrl(url)) E.note = { t: T.linkOpened, until: Date.now() + 2500 }; }
1978
+ else { const url = urlAt(sh.term, row, sl.a.x); if (url) openerMessage(openUrl, url, T.linkOpened, T.linkFailed).then(openerNote); }
1754
1979
  }
1755
1980
  return render();
1756
1981
  }
@@ -1785,27 +2010,26 @@ function hasContent(term) {
1785
2010
  return false;
1786
2011
  }
1787
2012
 
1788
- function embedInput(s) {
2013
+ function embedInput(s, write) {
1789
2014
  if (E.sel && !E.sel.down) { // copiar/Esc actúan sobre la selección sin llegar al chat
1790
2015
  if (isCopyKey(s)) { copySelection(E.sessions.get(E.shown)); return render(); }
1791
2016
  if (s === '\x1b') { E.sel = null; E.note = null; return render(); }
1792
2017
  }
1793
2018
  stopSelScroll(); E.sel = null; E.hover = null;
1794
- if (s === '\x1bOP' || s === '\x1b[11~' || s === '\x1b[1;1P') { E.focus = 'left'; if (E.hideSide) { E.hideSide = false; embedResize(); } else render(); return; }
1795
2019
  const sh = E.sessions.get(E.shown);
1796
2020
  const b = sh.term.buffer.active, scrolled = b.baseY > b.viewportY;
1797
- const page = Math.max(1, Math.floor(embedLayout().th / 2));
1798
- if (s === '\x1b[5~' || s === '\x1b[5;2~') { scrollSession(sh, page); return render(); }
1799
- if (s === '\x1b[6~' || s === '\x1b[6;2~') { scrollSession(sh, -page); return render(); }
2021
+ const paging = /^\x1b\[([56])(?:;2)?~$/.exec(s);
2022
+ if (paging) { scrollSession(sh, Math.max(1, Math.floor(embedLayout().th / 2)) * (paging[1] === '5' ? 1 : -1)); return render(); }
1800
2023
  if (scrolled && (s === '\x1b[F' || s === '\x1b[4~' || s === '\x1bOF')) { sh.term.scrollToBottom(); return render(); }
1801
2024
  if (scrolled) { sh.term.scrollToBottom(); render(); }
1802
2025
  let d = s;
1803
2026
  // Ctrl+V → Alt+V: en Windows Claude Code pega imágenes con Alt+V; así funciona el atajo de siempre.
1804
2027
  if (WIN && d === '\x16') d = '\x1bv';
1805
- if (!sh.term.modes.bracketedPasteMode) d = d.replace(/\x1b\[20[01]~/g, '');
1806
- if (sh.term.modes.applicationCursorKeysMode) d = d.replace(/\x1b\[([ABCDHF])/g, '\x1bO$1');
2028
+ if (s.startsWith(PASTE) && s.endsWith(END)) {
2029
+ if (!sh.term.modes.bracketedPasteMode) d = s.slice(PASTE.length, -END.length);
2030
+ } else if (sh.term.modes.applicationCursorKeysMode) d = d.replace(/^\x1b\[([ABCDHF])$/, '\x1bO$1');
1807
2031
  if (d.includes('\r')) { sh.busy = true; if (!sh.sid) { clearTimeout(sh.linkT); sh.linkT = setTimeout(() => reloadAsync(null, true), 4000); } } // se envió un mensaje: avisar cuando termine
1808
- try { sh.p.write(d); } catch { /* cerrado */ }
2032
+ write(sh, d);
1809
2033
  }
1810
2034
 
1811
2035
  /** Aviso de escritorio cuando un chat termina mientras miras otra cosa. */
@@ -1843,6 +2067,7 @@ function closeChat(key) {
1843
2067
  S.confirmClose = { key, until: Date.now() + 4000 }; return flash(T.confirmClose);
1844
2068
  }
1845
2069
  S.confirmClose = null; x.closing = true;
2070
+ if (WIN) killTree(x.p.pid);
1846
2071
  try { x.p.kill(); } catch { /* ya terminó */ }
1847
2072
  flash(T.closed(x.title));
1848
2073
  }
@@ -1862,11 +2087,13 @@ function showsBusy(term) {
1862
2087
  return false;
1863
2088
  }
1864
2089
 
2090
+ const chatWorking = (x, now) => x.ready && now - x.lastData < 1200 && (process.env.HOPDECK_BUSY === 'output' || showsBusy(x.term));
2091
+
1865
2092
  function pollChats() {
1866
2093
  const now = Date.now(); let changed = false;
1867
2094
  for (const [key, x] of E.sessions) {
1868
2095
  // HOPDECK_BUSY=output devuelve el criterio antiguo (cualquier salida reciente) por si una versión de Claude cambia ese texto
1869
- const working = x.ready && now - x.lastData < 1200 && (process.env.HOPDECK_BUSY === 'output' || showsBusy(x.term));
2096
+ const working = chatWorking(x, now);
1870
2097
  if (x.working && !working && x.busy) {
1871
2098
  x.busy = false;
1872
2099
  if (E.shown !== key || E.focus !== 'right') { x.unseen = true; E.note = { t: '✔ ' + x.project + ' › ' + x.title, until: now + 6000 }; process.stdout.write('\x07'); notifyDesktop(x.project + ' › ' + x.title); }
@@ -1875,9 +2102,8 @@ function pollChats() {
1875
2102
  if (x.unseen && E.shown === key && E.focus === 'right') { x.unseen = false; changed = true; }
1876
2103
  }
1877
2104
  if (E.note && E.note.until < now) { E.note = null; changed = true; }
1878
- if (changed) { if (x_any(E)) ensureSpin(); render(); }
2105
+ if (changed) { if (needsSpin()) ensureSpin(); render(); }
1879
2106
  }
1880
- const x_any = (e) => [...e.sessions.values()].some((x) => x.working);
1881
2107
 
1882
2108
  function embedResize() {
1883
2109
  invalidate(); stopSelScroll(); E.sel = null; // al cambiar el ancho las líneas se reajustan: la selección ya no marcaría lo mismo
@@ -1886,20 +2112,22 @@ function embedResize() {
1886
2112
  render();
1887
2113
  }
1888
2114
 
2115
+ function killTree(...pids) {
2116
+ const ids = pids.filter((pid) => Number.isInteger(pid) && pid > 0);
2117
+ if (!ids.length) return;
2118
+ try { cp.spawnSync('taskkill.exe', [...ids.flatMap((pid) => ['/PID', String(pid)]), '/T', '/F'],
2119
+ { stdio: 'ignore', windowsHide: true, timeout: 5000 }); } catch { /* */ }
2120
+ }
1889
2121
  function embedKillAll() {
1890
- if (WIN) {
1891
- // node-pty enumerates console processes asynchronously before killing them. quit()
1892
- // exits immediately, so that enumeration may never finish and leave ConPTY open.
1893
- // Stop all owned process trees before releasing the PTYs and exiting the hub.
1894
- const pids = [...E.sessions.values()].map((sess) => sess.p.pid).filter((pid) => Number.isInteger(pid) && pid > 0);
1895
- if (pids.length) {
1896
- try {
1897
- cp.spawnSync('taskkill.exe', [...pids.flatMap((pid) => ['/PID', String(pid)]), '/T', '/F'],
1898
- { stdio: 'ignore', windowsHide: true, timeout: 5000 });
1899
- } catch { /* still release the PTYs below */ }
2122
+ // quit() puede salir antes de que node-pty termine de enumerar los procesos de ConPTY.
2123
+ if (WIN) killTree(...[...E.sessions.values()].map((sess) => sess.p.pid));
2124
+ for (const { p } of E.sessions.values()) {
2125
+ if (!WIN && Number.isInteger(p.pid) && p.pid > 0) {
2126
+ // node-pty's kill() signals only the session leader on POSIX.
2127
+ try { process.kill(-p.pid, 'SIGHUP'); continue; } catch { /* sin grupo */ }
1900
2128
  }
2129
+ try { p.kill(); } catch { /* */ }
1901
2130
  }
1902
- for (const sess of E.sessions.values()) { try { sess.p.kill(); } catch { /* */ } }
1903
2131
  }
1904
2132
 
1905
2133
  // Redibujado diferencial: solo se reescriben las filas que cambiaron desde el último cuadro.
@@ -1917,39 +2145,77 @@ function diffRows(rows) {
1917
2145
 
1918
2146
  function render() {
1919
2147
  if (!active) return;
1920
- if (EMBED) return renderEmbed();
2148
+ if (EMBED) { if (!profile.enabled) return renderEmbed(); const started = profile.now(); renderEmbed(); profile.frame(started); return; }
1921
2149
  const cols = process.stdout.columns || 100, rows = process.stdout.rows || 30;
1922
2150
  const lines = SIDEBAR ? frameTree(cols, rows) : frame(cols, rows);
1923
2151
  const full = [];
1924
2152
  for (let i = 0; i < rows; i++) full.push(lines[i] || ' '.repeat(cols));
1925
2153
  const out = diffRows(full);
1926
2154
  if (out) process.stdout.write(out);
2155
+ if (SIDEBAR ? cols >= 24 && rows >= 8 : cols >= 60 && rows >= 12) profile.first('firstListRender');
1927
2156
  }
1928
2157
 
1929
2158
  // ───────────────────────── terminal ─────────────────────────
1930
- let active = false;
2159
+ let active = false, idleCursor = false, hubInput;
2160
+ const terminalReset = '\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1004l\x1b[?25h\x1b[?1049l' + R;
2161
+ function safely(fn) { try { fn(); } catch { /* */ } }
2162
+ // sync: al salir por una señal o un fallo se escribe directamente al descriptor (el proceso termina enseguida);
2163
+ // en leave() se usa el stream para no adelantarse a un cuadro aún en cola (en Windows el TTY puede ser asíncrono).
2164
+ function restoreTerminal(sync = false) {
2165
+ const reset = active ? terminalReset : idleCursor ? '\x1b[?25h' : '';
2166
+ active = idleCursor = false;
2167
+ safely(() => hubInput?.reset());
2168
+ safely(() => embeddedMouse.close());
2169
+ if (reset) safely(() => (sync ? fs.writeSync(process.stdout.fd, reset) : process.stdout.write(reset)));
2170
+ if (process.stdin.isRaw) safely(() => process.stdin.setRawMode(false));
2171
+ safely(() => process.stdin.pause());
2172
+ }
1931
2173
  function enter() {
1932
2174
  if (active) return; active = true; invalidate();
1933
- process.stdout.write('\x1b[?1049h\x1b[?25l\x1b[2J' + ((EMBED || SIDEBAR) && E.mouse ? mouseModes(true) : '') + (EMBED && process.env.HOPDECK_SIXEL !== '0' ? '\x1b[c\x1b[16t' : '')); // consulta: ¿admite imágenes (Sixel)? ¿qué tamaño tiene una celda?
2175
+ profile.first('enter');
2176
+ process.stdout.write('\x1b[?1049h\x1b[?25l\x1b[2J' + ((EMBED || SIDEBAR) && E.mouse ? mouseModes(true) : '') + (EMBED && process.env.HOPDECK_SIXEL !== '0' ? '\x1b[c\x1b[16t' : '') + (EMBED || SIDEBAR ? '\x1b[?1004h' : '')); // consulta: ¿admite imágenes (Sixel)? ¿qué tamaño tiene una celda?
1934
2177
  process.stdin.setRawMode(true); process.stdin.resume();
1935
2178
  }
1936
- function leave() {
1937
- if (!active) return; active = false;
1938
- process.stdout.write(((EMBED || SIDEBAR) ? mouseModes(false) : '') + '\x1b[?25h\x1b[?1049l' + R);
1939
- try { process.stdin.setRawMode(false); } catch { /* */ }
1940
- process.stdin.pause();
2179
+ function leave() { if (active) restoreTerminal(); }
2180
+ function createShutdown({ restore, cleanup, report, exit }) {
2181
+ let started = false;
2182
+ return (code = 0, ...crash) => {
2183
+ if (started) return;
2184
+ started = true;
2185
+ safely(restore);
2186
+ for (const step of cleanup) safely(step);
2187
+ if (crash.length) safely(() => report(crash[0]));
2188
+ safely(() => exit(code));
2189
+ };
1941
2190
  }
1942
- function quit(code = 0) {
1943
- codexHistory.close();
1944
- cleanExports();
1945
- if (EMBED || SIDEBAR) rememberState();
1946
- if (EMBED) embedKillAll();
1947
- if (SIDEBAR) { try { tmux('kill-server'); } catch { /* ya cerrado */ } }
1948
- leave(); process.exit(code);
2191
+ let shuttingDown = false;
2192
+ const quit = createShutdown({
2193
+ restore: () => { shuttingDown = true; restoreTerminal(true); },
2194
+ cleanup: [
2195
+ cleanExports,
2196
+ () => imageWorker.close(),
2197
+ () => background?.close(),
2198
+ () => { if (EMBED || SIDEBAR) rememberState(); },
2199
+ () => { if (EMBED) embedKillAll(); },
2200
+ closeCodexHistory,
2201
+ closeClaudeHistory,
2202
+ cacheSave,
2203
+ ],
2204
+ report: (error) => fs.writeSync(process.stderr.fd, String(error?.stack || error) + '\n'),
2205
+ exit: (code) => {
2206
+ if (SIDEBAR) safely(() => tmux('kill-session', '-t', '=' + sessionName()));
2207
+ process.exit(code);
2208
+ },
2209
+ });
2210
+ function watchShutdown() {
2211
+ process.on('SIGTERM', () => quit(143));
2212
+ process.on('SIGHUP', () => quit(129));
2213
+ process.on('uncaughtException', (error) => quit(1, error));
2214
+ process.on('unhandledRejection', (error) => quit(1, error));
1949
2215
  }
1950
2216
 
1951
2217
  function load(keepKey) {
1952
- S.projects = scan();
2218
+ replaceProjects(scan());
1953
2219
  if (keepKey) { const i = S.projects.findIndex((p) => p.key === keepKey); if (i >= 0) S.pi = i; }
1954
2220
  }
1955
2221
 
@@ -1973,7 +2239,7 @@ async function launch(project, session) {
1973
2239
  if (!findClaude(provider.id)) {
1974
2240
  if (settingUpProvider) return;
1975
2241
  settingUpProvider = true;
1976
- const wasActive = active; leave(); codexHistory.close();
2242
+ const wasActive = active; leave(); closeCodexHistory();
1977
2243
  let ready = false;
1978
2244
  try { ready = await ensureSelectedProvider(); }
1979
2245
  catch (error) { process.stdout.write(clean(error.message) + '\n'); }
@@ -1985,6 +2251,7 @@ async function launch(project, session) {
1985
2251
  if (!fs.existsSync(project.cwd)) { flash(T.missing + ': ' + shortPath(project.cwd)); return; }
1986
2252
  const bin = findClaude(provider.id);
1987
2253
  if (!bin) { flash(T.noClaude); return; }
2254
+ if (WIN && !/\.(exe|com|cmd|bat)$/i.test(bin)) return flash(T.winUnsupported(shortPath(bin)));
1988
2255
  leave();
1989
2256
  process.stdout.write('\x1b[2J\x1b[H');
1990
2257
  const args = provider.launchArgs(session, extraArgs);
@@ -1992,13 +2259,14 @@ async function launch(project, session) {
1992
2259
  const onInt = () => { /* Ctrl-C es del proceso hijo */ };
1993
2260
  process.on('SIGINT', onInt);
1994
2261
  let res;
1995
- if (WIN && /\.(cmd|bat)$/i.test(bin)) { // los .cmd necesitan shell: una sola cadena evita DEP0190
1996
- const q = (x) => (/^[\w.:\\/=@-]+$/.test(x) ? x : `"${x.replace(/"/g, '\\"')}"`);
1997
- res = cp.spawnSync([`"${bin}"`, ...args.map(q)].join(' '), { ...opts, shell: true });
1998
- } else res = cp.spawnSync(bin, args, opts);
2262
+ try {
2263
+ res = WIN && /\.(cmd|bat)$/i.test(bin)
2264
+ ? cp.spawnSync(process.env.ComSpec || 'cmd.exe', ['/d', '/s', '/c', `"${cmdLine(bin, args)}"`], { windowsVerbatimArguments: true, ...opts })
2265
+ : cp.spawnSync(bin, args, opts);
2266
+ } catch (error) { res = { error }; }
1999
2267
  process.removeListener('SIGINT', onInt);
2000
2268
  if (res.error) {
2001
- process.stdout.write(`\n${C.warn}${res.error.message}${R}\n${C.dim}${T.pressKey}${R}\n`);
2269
+ process.stdout.write(`\n${C.warn}${res.error.code === 'HOPDECK_CMD_LINE' ? T.winBadArgs : res.error.message}${R}\n${C.dim}${T.pressKey}${R}\n`);
2002
2270
  process.stdin.setRawMode(true); process.stdin.resume();
2003
2271
  process.stdin.once('data', () => { process.stdin.setRawMode(false); process.stdin.pause(); back(project.key); });
2004
2272
  return;
@@ -2057,8 +2325,8 @@ function onKey(raw) {
2057
2325
  return launch(cur.p, S.si === 0 ? null : cur.ss[S.si - 1]);
2058
2326
  case 'n': if (cur) return launch(cur.p, null); break;
2059
2327
  case '/': S.searching = true; S.focus = 0; break;
2060
- case 'r': reloadAsync(() => { const i = view().findIndex((x) => cur && x.p.key === cur.p.key); if (i >= 0) S.pi = i; }); break;
2061
- case 'H': S.showHidden = !S.showHidden; break;
2328
+ case 'r': reloadKeep(); break;
2329
+ case 'H': S.showHidden = !S.showHidden; invalidateView(); break;
2062
2330
  case 'p': case 'x':
2063
2331
  if (cur) {
2064
2332
  const pr = cur.p; toggleProject(pr, k === 'p' ? 'pinned' : 'hidden');
@@ -2083,11 +2351,68 @@ function splash(done, total) {
2083
2351
  art.forEach((_, j) => { out += `\x1b[${top + j};1H${mascotRow(art, j, c)}`; });
2084
2352
  lines.forEach(([st, t], i) => { out += `\x1b[${top + art.length + gap + i};${Math.max(1, Math.floor((c - strW(t)) / 2) + 1)}H${st}${t}${R}`; });
2085
2353
  process.stdout.write(out);
2354
+ profile.first('firstRender');
2355
+ }
2356
+
2357
+ const FKEY = {
2358
+ '\x1bOP': 1, '\x1b[11~': 1, '\x1b[1;1P': 1, '\x1bOQ': 2, '\x1b[12~': 2, '\x1b[1;1Q': 2,
2359
+ '\x1bOR': 3, '\x1b[13~': 3, '\x1b[1;1R': 3, '\x1bOS': 4, '\x1b[14~': 4, '\x1b[1;1S': 4,
2360
+ '\x1b[15~': 5, '\x1b[17~': 6, '\x1b[18~': 7, '\x1b[19~': 8, '\x1b[20~': 9,
2361
+ };
2362
+ function consumeTermReply(s) {
2363
+ return /^\x1b\[(?:\?[0-9;]*c|6;\d+;\d+t)$/.test(s) && !parseTermReplies(s, E);
2364
+ }
2365
+ const embeddedMouse = coalesceMouse((...event) => { if (active) onMouse(...event); });
2366
+ function dispatchInput(tokens) {
2367
+ let chat = null, outgoing = [];
2368
+ const flush = () => {
2369
+ if (outgoing.length) { try { chat.p.write(outgoing.join('')); } catch { /* cerrado */ } outgoing = []; }
2370
+ };
2371
+ const write = (sh, s) => { if (sh !== chat) { flush(); chat = sh; } outgoing.push(s); };
2372
+ const listKey = SIDEBAR || EMBED ? onKeyTree : onKey;
2373
+ for (const token of tokens) {
2374
+ if (!active) break;
2375
+ const s = /^\x1b\[\[[A-E]$/.test(token) ? normalizeKeys(token) : token;
2376
+ const f = FKEY[s], right = EMBED && E.focus === 'right' && E.sessions.has(E.shown);
2377
+ if (EMBED && consumeTermReply(s)) continue;
2378
+ const mouse = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(s);
2379
+ if (mouse) { flush(); if (EMBED || SIDEBAR) (EMBED ? embeddedMouse : sidebarMouse)(+mouse[1], +mouse[2], +mouse[3], mouse[4]); continue; }
2380
+ if (s === '\x1b[I' || s === '\x1b[O') {
2381
+ flush();
2382
+ const focused = s === '\x1b[I', caughtUp = background?.focus(focused);
2383
+ if (SIDEBAR && focused && !caughtUp) listKey(s);
2384
+ continue;
2385
+ }
2386
+ if ((EMBED || SIDEBAR) && f === 3) { flush(); CFG.mouse = !E.mouse; saveCfg(); setMouse(!E.mouse); continue; }
2387
+ if (EMBED && E.gallery) { galleryKey(f === 7 ? '\x1b[18~' : s); continue; }
2388
+ if (EMBED && f) {
2389
+ flush();
2390
+ if (f === 1) {
2391
+ if (right) { stopSelScroll(); E.sel = null; E.hover = null; E.focus = 'left'; if (E.hideSide) { E.hideSide = false; embedResize(); } else render(); }
2392
+ } else if (f === 2) listKey('\x1bOQ');
2393
+ else if (f === 4) { E.hideSide = !E.hideSide && E.sessions.has(E.shown); E.focus = E.hideSide ? 'right' : 'left'; embedResize(); }
2394
+ else if (f === 5) { E.focus = 'left'; E.hideSide = false; S.qs = { q: '', pc: 0, i: 0, off: 0 }; embedResize(); }
2395
+ else if (f === 6) listKey('\x1b[17~');
2396
+ else if (f === 7) openGalleryShown();
2397
+ else if (f === 8) toggleGit();
2398
+ else if (f === 9) toggleTheme();
2399
+ continue;
2400
+ }
2401
+ if (right) { embedInput(s, write); continue; }
2402
+ flush();
2403
+ if (s.startsWith(PASTE)) {
2404
+ if (s.endsWith(END) && (S.prompt !== null || S.searching || S.qs || S.fb?.filt)) {
2405
+ for (const ch of s.slice(PASTE.length, -END.length)) if (printable(ch)) listKey(ch);
2406
+ }
2407
+ } else if (!/^\x1b[^\x00-\x1f\x7f]$/u.test(s)) listKey(s); // Alt+tecla no es Esc
2408
+ }
2409
+ flush();
2086
2410
  }
2087
2411
 
2088
2412
  async function run() {
2089
2413
  if (!process.stdin.isTTY || !process.stdout.isTTY) { printList(); return; }
2090
2414
  if (!SIDEBAR && process.env.HOPDECK_INSIDE) { console.log(T.inside); return; }
2415
+ watchShutdown();
2091
2416
  if (!SIDEBAR) {
2092
2417
  if (process.env.HOPDECK_WELCOME_DONE) { CFG.welcomeSeen = true; saveCfg(); }
2093
2418
  await showWelcome({ config: CFG, save: saveCfg, lang: LANG,
@@ -2105,63 +2430,65 @@ async function run() {
2105
2430
  if (!await ensureSelectedProvider()) { if (!providerSetup.canPrompt()) process.exitCode = 1; return; }
2106
2431
  }
2107
2432
  if (!SIDEBAR) await offerShortcut(); // primera vez: ¿quieres que `claude` abra Hopdeck?
2433
+ const nestedTmux = !SIDEBAR && !WIN && !!process.env.HOPDECK_TMUX && !!process.env.TMUX;
2108
2434
  if (!SIDEBAR) {
2109
- // Por defecto se usa el terminal integrado (vista previa al pasar el cursor, imágenes). tmux solo con HOPDECK_TMUX=1,
2110
- // o como alternativa si el terminal integrado no está disponible.
2111
- const tmuxOk = !WIN && !process.env.HOPDECK_NOTMUX && !process.env.HOPDECK_EMBED && hasTmux();
2112
- if (tmuxOk && process.env.HOPDECK_TMUX) return bootstrap();
2113
- if (!process.env.HOPDECK_NOEMBED) { E.deps = loadDeps(); EMBED = !!E.deps; }
2114
- if (!EMBED && tmuxOk) return bootstrap();
2115
- }
2116
- process.on('exit', () => { if (active) { try { process.stdout.write('\x1b[?1000l\x1b[?1003l\x1b[?1006l\x1b[?25h\x1b[?1049l'); } catch { /* */ } } });
2117
- process.on('SIGTERM', () => quit(0));
2435
+ const env = process.env;
2436
+ let tmuxVersion = env.HOPDECK_TMUX && !nestedTmux ? installedTmux() : null;
2437
+ if (env.HOPDECK_TMUX && canUseTmux(env, tmuxVersion)) return bootstrap();
2438
+ if (!env.HOPDECK_NOEMBED) E.deps = loadDeps();
2439
+ if (!E.deps && !env.HOPDECK_TMUX) tmuxVersion = installedTmux(); // sin node-pty, tmux es la alternativa
2440
+ const mode = tmuxMode({ env, tmuxVersion, deps: E.deps });
2441
+ if (mode === 'tmux') return bootstrap();
2442
+ EMBED = mode === 'embedded';
2443
+ }
2444
+ const pollHistory = (catchUp = false) => {
2445
+ if (reloading || (!catchUp && (S.loading || S.searching || S.query || S.prompt !== null || S.help))) return;
2446
+ void reloadAsync(null, true, { incremental: true });
2447
+ };
2448
+ background = createBackground({ reload: pollHistory, reloadMs: profile.reloadMs, poll: EMBED ? pollChats : null,
2449
+ working: () => {
2450
+ const now = Date.now();
2451
+ for (const x of E.sessions.values()) if (x.working || chatWorking(x, now)) return true;
2452
+ return false;
2453
+ },
2454
+ git: EMBED ? () => { if (active && E.git && embedLayout().GW) { const cwd = gitCwd(); if (cwd) gitInfo(cwd, true); } } : null });
2455
+ let inputReady = false;
2456
+ hubInput = createInput({ onFlush: (tokens) => { if (active && inputReady) dispatchInput(tokens); } });
2457
+ process.stdin.on('data', (buf) => {
2458
+ if (!active) return;
2459
+ const tokens = hubInput.feed(buf);
2460
+ if (inputReady) dispatchInput(tokens);
2461
+ else for (const token of tokens) {
2462
+ if (token === '\x1b[I' || token === '\x1b[O') background.focus(token === '\x1b[I');
2463
+ else if (EMBED) consumeTermReply(token);
2464
+ }
2465
+ });
2118
2466
  enter();
2119
- splash(0, 0);
2120
- const tick = setInterval(() => { frameN++; splash(prog[0], prog[1]); }, 90);
2121
- const prog = [0, 0];
2122
- try { S.projects = await scanAsync((d, t) => { prog[0] = d; prog[1] = t; }); }
2123
- finally { clearInterval(tick); invalidate(); }
2467
+ const cached = provider.isCodex ? null : hist.projectsFromCache();
2468
+ const warm = cached !== null;
2469
+ if (warm) { replaceProjects(finishScan(cached)); scanLoading = true; ensureSpin(); }
2470
+ else {
2471
+ splash(0, 0);
2472
+ const prog = [0, 0];
2473
+ const tick = setInterval(() => { frameN++; splash(prog[0], prog[1]); }, 90);
2474
+ try { replaceProjects(await scanAsync((d, t) => { prog[0] = d; prog[1] = t; })); }
2475
+ finally { clearInterval(tick); invalidate(); }
2476
+ }
2124
2477
  if (SIDEBAR || EMBED) {
2125
2478
  S.open = S.projects[0] && S.projects[0].key;
2126
2479
  restoreState();
2127
- if (SIDEBAR) { process.stdout.write('\x1b[?1004h'); setInterval(refreshLive, 2000); }
2480
+ if (SIDEBAR) setInterval(refreshLive, 2000).unref();
2128
2481
  }
2129
2482
  process.stdout.on('resize', EMBED ? embedResize : () => { invalidate(); render(); });
2130
- if (EMBED) setInterval(pollChats, 400);
2131
- if (EMBED) setInterval(() => { if (active && E.git && embedLayout().GW) scheduleRender(); }, 4000); // el panel de git se refresca solo
2132
- setInterval(() => { // lista siempre al día
2133
- if (S.loading || reloading || S.searching || S.query || S.prompt !== null || S.help) return;
2134
- if (SIDEBAR || EMBED) { const e = flatList()[S.c]; reloadAsync(() => { if (!e) return; const i = flatList().findIndex((x) => x.t === e.t && x.p.key === e.p.key && (e.t !== 's' || x.s.id === e.s.id)); if (i >= 0) S.c = i; }, true); }
2135
- else { const cur = view()[S.pi]; reloadAsync(() => { if (!cur) return; const i = view().findIndex((v) => v.p.key === cur.p.key); if (i >= 0) S.pi = i; }, true); }
2136
- }, 20000);
2137
- process.stdin.on('data', (buf) => {
2138
- if (!active) return;
2139
- let s = normalizeKeys(buf.toString('utf8'));
2140
- if (EMBED) { s = parseTermReplies(s, E); if (!s) return; } // respuestas del terminal a las consultas del arranque
2141
- if (EMBED) {
2142
- s = s.replace(/\x1b\[<(\d+);(\d+);(\d+)([Mm])/g, (m, b, x, y, t) => { onMouse(+b, +x, +y, t); return ''; });
2143
- if (!s) return;
2144
- if (s === '\x1bOR' || s === '\x1b[13~') { CFG.mouse = !E.mouse; saveCfg(); return setMouse(!E.mouse); }
2145
- if (E.gallery) { for (const k of parseKeys(s)) galleryKey(k); return; }
2146
- if (s === '\x1b[17~' && E.focus === 'right') return closeChat(E.shown);
2147
- if (s === '\x1b[18~') return openGalleryShown();
2148
- if (s === '\x1b[19~') return toggleGit();
2149
- if (s === '\x1b[20~') return toggleTheme();
2150
- if (s === '\x1b[15~') { E.focus = 'left'; if (E.hideSide) E.hideSide = false; S.qs = { q: '', pc: 0, i: 0, off: 0 }; return embedResize(); }
2151
- if (s === '\x1bOS' || s === '\x1b[14~') {
2152
- E.hideSide = !E.hideSide && E.sessions.has(E.shown);
2153
- E.focus = E.hideSide ? 'right' : 'left'; return embedResize();
2154
- }
2155
- }
2156
- if (SIDEBAR) { // modo tmux: eventos de ratón de la lista y F3 para apagar/encender el ratón
2157
- s = s.replace(/\x1b\[<(\d+);(\d+);(\d+)([Mm])/g, (m, b, x, y, t) => { sidebarMouse(+b, +x, +y, t); return ''; });
2158
- if (!s) return;
2159
- if (s === '\x1bOR' || s === '\x1b[13~') { CFG.mouse = !E.mouse; saveCfg(); return setMouse(!E.mouse); }
2160
- }
2161
- if (EMBED && E.focus === 'right' && E.sessions.has(E.shown)) return embedInput(s);
2162
- for (const k of parseKeys(s)) (SIDEBAR || EMBED ? onKeyTree : onKey)(k);
2163
- });
2164
- render();
2483
+ background.start();
2484
+ inputReady = true;
2485
+ cachePaint = warm;
2486
+ if (nestedTmux) flash(EMBED ? T.tmuxNested : T.tmuxNestedFull);
2487
+ else render();
2488
+ cachePaint = false;
2489
+ profile.baseline();
2490
+ if (warm) void reloadAsync(null, false, { startup: true });
2491
+ if (!provider.isCodex) historyScanner.watchProjects(pollHistory);
2165
2492
  }
2166
2493
 
2167
2494
  function doctor() {
@@ -2170,21 +2497,36 @@ function doctor() {
2170
2497
  console.log(`\n ${C.brand}${C.bold}» Hop${R}${C.text}${C.bold}deck doctor${R} ${C.dim}v${VERSION}${R}\n`);
2171
2498
  if (parseInt(process.versions.node, 10) < 22) bad(T.dcNodeOld(process.version), T.dcNodeOldHint);
2172
2499
  else ok(`Node ${process.version} · ${process.platform} ${process.arch}`);
2173
- const histDir = shortPath(provider.isCodex ? codexHistory.CONFIG_DIR : path.join(CONFIG_DIR, 'projects'));
2500
+ const histDir = shortPath(provider.isCodex ? codexHistory().CONFIG_DIR : path.join(CONFIG_DIR, 'projects'));
2174
2501
  const bin = findClaude(provider.id);
2175
2502
  bin ? ok(T.dcClaude(shortPath(bin))) : bad(T.dcNoClaude, provider.isCodex ? 'npm install -g @openai/codex' : WIN ? T.dcInstallWin : T.dcInstallUnix);
2176
2503
  try {
2177
- const n = provider.isCodex ? (bin ? codexHistory.scanSync().length : 0) : projectDirs().length;
2504
+ const n = provider.isCodex ? (bin ? codexHistory().scanSync().length : 0) : projectDirs().length;
2178
2505
  n ? ok(T.dcHist(n, histDir)) : bad(T.dcNoHist(histDir), T.dcNoHistHint);
2179
2506
  } catch (err) { bad(clean(err.message), 'codex app-server'); }
2180
- const tm = !WIN && hasTmux();
2181
- const deps = loadDeps();
2182
- if (tm) ok(T.dcTmux);
2183
- else if (deps) ok(T.dcEmbed);
2184
- else bad(T.dcNone, WIN ? T.dcNoneWin : T.dcNoneUnix);
2507
+ const env = process.env, tmuxVersion = installedTmux(), deps = loadDeps();
2508
+ const mode = tmuxMode({ env, tmuxVersion, deps });
2509
+ if (mode === 'tmux') ok(T.dcTmux);
2510
+ else if (mode === 'embedded') ok(T.dcEmbed + (canUseTmux(env, tmuxVersion) ? ' · ' + T.dcTmuxOpt : ''));
2511
+ else ok(T.dcNone);
2512
+ if (tmuxVersion && !canUseTmux({}, tmuxVersion)) bad(T.dcTmuxOld);
2513
+ if (!WIN && env.TMUX && env.HOPDECK_TMUX) ok(mode === 'embedded' ? T.tmuxNested : T.tmuxNestedFull);
2514
+ if (deps && UNIX_PTY) {
2515
+ const helper = spawnHelper();
2516
+ if (helper) {
2517
+ try { fs.accessSync(helper, fs.constants.X_OK); ok(T.dcPtyHelper); }
2518
+ catch { bad(T.dcPtyHelperBad, spawnHelperHint(helper)); }
2519
+ } else if (process.platform === 'darwin') bad(T.dcPtyHelperBad, spawnHelperHint(helper));
2520
+ }
2185
2521
  let wrapped = false;
2186
- for (const t of targets()) { try { const txt = fs.readFileSync(t.file, 'utf8'); if (txt.includes(MARK_A) && txt.includes('hopdeck --provider codex')) wrapped = true; } catch { /* */ } }
2522
+ for (const t of targets()) { try { const { text: txt } = readText(t.file); if (txt.includes(MARK_A) && txt.includes('hopdeck --provider codex')) wrapped = true; } catch { /* */ } }
2187
2523
  wrapped ? ok(T.dcShort) : bad(T.dcNoShort, findClaude('hopdeck') ? T.dcNoShortHint : T.dcNoCmdHint); // sin el comando en el PATH, "hopdeck shortcut on" no existe todavía
2524
+ if (WIN) {
2525
+ try {
2526
+ const policy = cp.execFileSync('powershell.exe', ['-NoProfile', '-Command', 'Get-ExecutionPolicy'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 8000 }).trim();
2527
+ if (/^(Restricted|AllSigned)$/i.test(policy)) bad(T.dcPolicy(policy), T.dcPolicyHint);
2528
+ } catch { /* */ }
2529
+ }
2188
2530
  ok(T.dcPrefs(shortPath(CFG_FILE), shortPath(CACHE_FILE)));
2189
2531
  if (process.env.WT_SESSION) { // dentro de Windows Terminal: Ctrl+V solo pega texto y no deja pegar imágenes
2190
2532
  const f = wtSettingsFile(); let st = null;
@@ -2208,6 +2550,8 @@ const MARK_A = '# >>> hopdeck >>>';
2208
2550
  const MARK_B = '# <<< hopdeck <<<';
2209
2551
  const SNIP = {
2210
2552
  posix: `${MARK_A}
2553
+ unalias claude 2>/dev/null || :
2554
+ [ -x "$HOME/.claude/local/claude" ] && case ":$PATH:" in *":$HOME/.claude/local:"*) ;; *) PATH="$PATH:$HOME/.claude/local" ;; esac
2211
2555
  claude() {
2212
2556
  if [ $# -eq 0 ] && [ -t 0 ] && [ -t 1 ] && [ -z "$HOPDECK_SKIP" ] && command -v hopdeck >/dev/null 2>&1; then
2213
2557
  hopdeck
@@ -2229,8 +2573,12 @@ ${MARK_B}
2229
2573
  `,
2230
2574
  pwsh: `${MARK_A}
2231
2575
  function claude {
2232
- if ($args.Count -eq 0 -and -not $env:HOPDECK_SKIP -and (Get-Command hopdeck -ErrorAction SilentlyContinue)) { hopdeck }
2233
- else { & (Get-Command claude -CommandType Application | Select-Object -First 1).Source @args }
2576
+ if ($args.Count -eq 0 -and -not $env:HOPDECK_SKIP -and -not $MyInvocation.ExpectingInput -and -not [Console]::IsInputRedirected -and -not [Console]::IsOutputRedirected -and (Get-Command hopdeck -ErrorAction SilentlyContinue)) { hopdeck }
2577
+ else {
2578
+ $cli = (Get-Command claude -CommandType Application | Select-Object -First 1).Source
2579
+ if ($MyInvocation.ExpectingInput) { $input | & $cli @args }
2580
+ else { & $cli @args }
2581
+ }
2234
2582
  }
2235
2583
  ${MARK_B}
2236
2584
  `,
@@ -2245,31 +2593,42 @@ for (const kind of Object.keys(SNIP)) {
2245
2593
  SNIP[kind] = `${MARK_A}\n${claude}\n${codex}\n${MARK_B}\n`;
2246
2594
  }
2247
2595
 
2248
- function stripBlock(txt) {
2249
- const a = txt.indexOf(MARK_A), b = txt.indexOf(MARK_B);
2250
- if (a < 0 || b < 0) return txt;
2251
- return (txt.slice(0, a) + txt.slice(b + MARK_B.length)).replace(/\n{3,}/g, '\n\n').replace(/^\n+/, '');
2596
+ function stripBlock(txt, onUnclosed) {
2597
+ let from = 0, out = '';
2598
+ for (let a = txt.indexOf(MARK_A); a >= 0; a = txt.indexOf(MARK_A, from)) {
2599
+ const body = a + MARK_A.length, b = txt.indexOf(MARK_B, body), next = txt.indexOf(MARK_A, body);
2600
+ if (b < 0 || (next >= 0 && next < b)) { onUnclosed?.(); return txt; }
2601
+ const start = txt.slice(from, a);
2602
+ out += /^ added newline\r?\n/.test(txt.slice(body)) ? start.replace(/\r?\n$/, '') : start;
2603
+ from = b + MARK_B.length;
2604
+ if (txt.startsWith('\r\n', from)) from += 2;
2605
+ else if (txt[from] === '\n') from++;
2606
+ }
2607
+ return out + txt.slice(from);
2252
2608
  }
2253
2609
 
2254
- function targets() {
2610
+ function targets({ platform = process.platform, env = process.env, home: h = os.homedir(), exists = fs.existsSync } = {}) {
2255
2611
  // HOPDECK_PROFILES (rutas separadas como las del PATH): perfiles a usar en lugar de los detectados. Pensado para las pruebas.
2256
- if (process.env.HOPDECK_PROFILES) return process.env.HOPDECK_PROFILES.split(path.delimiter).filter(Boolean).map((file) => ({ file, kind: /\.ps1$/i.test(file) ? 'pwsh' : /\.fish$/i.test(file) ? 'fish' : 'posix' }));
2257
- const list = []; const h = os.homedir();
2612
+ if (env.HOPDECK_PROFILES) return env.HOPDECK_PROFILES.split(platform === 'win32' ? ';' : ':').filter(Boolean).map((file) => ({ file, kind: /\.ps1$/i.test(file) ? 'pwsh' : /\.fish$/i.test(file) ? 'fish' : 'posix' }));
2613
+ const list = [];
2258
2614
  const add = (file, kind) => { if (!list.some((t) => t.file === file)) list.push({ file, kind }); };
2259
- const sh = process.env.SHELL || '';
2260
- if (WIN) {
2615
+ const sh = env.SHELL || '';
2616
+ if (platform === 'win32') {
2261
2617
  for (const exe of ['pwsh', 'powershell']) {
2262
2618
  try {
2263
- const out = cp.execSync(`${exe} -NoProfile -Command "$PROFILE.CurrentUserCurrentHost"`, { stdio: ['ignore', 'pipe', 'ignore'], timeout: 8000 }).toString().trim();
2619
+ const out = cp.execFileSync(exe + '.exe', ['-NoProfile', '-Command', '[Console]::OutputEncoding=[Text.Encoding]::UTF8; $PROFILE.CurrentUserCurrentHost'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 8000 }).trim();
2264
2620
  if (out) add(out, 'pwsh');
2265
2621
  } catch { /* no instalado */ }
2266
2622
  }
2267
- if (fs.existsSync(path.join(h, '.bashrc'))) add(path.join(h, '.bashrc'), 'posix'); // Git Bash
2623
+ if (exists(path.join(h, '.bashrc'))) add(path.join(h, '.bashrc'), 'posix'); // Git Bash
2268
2624
  } else {
2269
- if (/zsh/.test(sh) || fs.existsSync(path.join(h, '.zshrc'))) add(path.join(h, '.zshrc'), 'posix');
2270
- if (/bash/.test(sh) || fs.existsSync(path.join(h, '.bashrc'))) add(path.join(h, '.bashrc'), 'posix');
2271
- if (/fish/.test(sh)) add(path.join(h, '.config', 'fish', 'conf.d', 'hopdeck.fish'), 'fish');
2272
- if (!list.length) add(path.join(h, '.bashrc'), 'posix');
2625
+ const zshrc = path.join(env.ZDOTDIR || h, '.zshrc');
2626
+ const bashrc = path.join(h, '.bashrc'), bashProfile = path.join(h, '.bash_profile');
2627
+ const bash = platform === 'darwin' && (exists(bashProfile) || !exists(bashrc)) ? bashProfile : bashrc;
2628
+ if (/zsh/.test(sh) || exists(zshrc)) add(zshrc, 'posix');
2629
+ if (/bash/.test(sh) || exists(bash)) add(bash, 'posix');
2630
+ if (/fish/.test(sh)) add(path.join(env.XDG_CONFIG_HOME || path.join(h, '.config'), 'fish', 'conf.d', 'hopdeck.fish'), 'fish');
2631
+ if (!list.length) add(bash, 'posix');
2273
2632
  }
2274
2633
  return list;
2275
2634
  }
@@ -2291,15 +2650,26 @@ function install(remove, list = targets(), quiet = false) {
2291
2650
  const done = [], baks = [];
2292
2651
  for (const t of list) {
2293
2652
  try {
2294
- let txt = null; try { txt = fs.readFileSync(t.file, 'utf8'); } catch { /* nuevo */ }
2295
- if (remove && (txt === null || !txt.includes(MARK_A))) continue; // no hay nada que quitar: el archivo no se toca
2296
- const before = txt || '';
2297
- let out = stripBlock(before);
2298
- if (!remove) out = (out && !out.endsWith('\n') ? out + '\n' : out) + (out ? '\n' : '') + SNIP[t.kind];
2653
+ let meta;
2654
+ try { meta = readText(t.file); }
2655
+ catch (e) {
2656
+ if (e.code !== 'ENOENT') throw e;
2657
+ meta = { text: '', eol: WIN && t.kind === 'pwsh' ? '\r\n' : '\n', bom: WIN && t.kind === 'pwsh' };
2658
+ }
2659
+ const before = meta.text;
2660
+ if (remove && !before.includes(MARK_A)) continue;
2661
+ let unclosed = false, out = stripBlock(before, () => { unclosed = true; });
2662
+ if (unclosed) { log(`${C.warn}✗ ${T.shortcutUnclosed(t.file)}${R}`); continue; }
2663
+ if (!remove) {
2664
+ // Registra solo el salto añadido para poder quitarlo sin tocar los saltos del perfil.
2665
+ const addEol = out && !out.endsWith('\n');
2666
+ const snippet = addEol ? SNIP[t.kind].replace(MARK_A, MARK_A + ' added newline') : SNIP[t.kind];
2667
+ out += (addEol ? meta.eol : '') + snippet.replace(/\n/g, meta.eol);
2668
+ }
2299
2669
  if (out !== before) {
2300
2670
  const bak = backupProfile(t.file); if (bak) baks.push(bak);
2301
2671
  fs.mkdirSync(path.dirname(t.file), { recursive: true });
2302
- fs.writeFileSync(t.file, out);
2672
+ writeText(t.file, out, meta);
2303
2673
  }
2304
2674
  done.push(t.file);
2305
2675
  } catch (e) { log(`${C.warn}✗ ${t.file}: ${e.message}${R}`); }
@@ -2347,15 +2717,17 @@ async function uninstallAll({ yes = false, list = targets() } = {}) {
2347
2717
 
2348
2718
  // ── Primer arranque: ofrecer que escribir `claude` abra Hopdeck ──
2349
2719
  const markAsked = () => { CFG.shortcutAsked = true; saveCfg(); };
2350
- const hasShortcut = (list) => list.some((t) => { try { return fs.readFileSync(t.file, 'utf8').includes(MARK_A); } catch { return false; } });
2720
+ const hasShortcut = (list) => list.some((t) => { try { return readText(t.file).text.includes(MARK_A); } catch { return false; } });
2351
2721
 
2352
2722
  /** Espera una tecla; `accept(k)` devuelve el valor a entregar, o undefined para seguir esperando. Ctrl+C sale. */
2353
2723
  function readKey(accept) {
2724
+ profile.first('firstRender');
2354
2725
  return new Promise((resolve) => {
2726
+ const decoder = new StringDecoder('utf8');
2355
2727
  const wasRaw = process.stdin.isRaw;
2356
2728
  process.stdin.setRawMode(true); process.stdin.resume();
2357
2729
  const on = (buf) => {
2358
- const k = buf.toString('utf8');
2730
+ const k = decoder.write(buf); if (!k) return;
2359
2731
  if (k === '\x03') { try { process.stdin.setRawMode(false); } catch { /* */ } process.stdout.write('\n'); process.exit(130); }
2360
2732
  const v = accept(k);
2361
2733
  if (v === undefined) return;
@@ -2503,21 +2875,23 @@ function main() {
2503
2875
  else console.log(frame(c, r).join('\n'));
2504
2876
  } else {
2505
2877
  extraArgs.push(...[cmd, ...rest].filter((a) => a && a !== '--sidebar'));
2506
- run().catch((e) => { codexHistory.close(); try { leave(); } catch { /* */ } console.error(e.message); process.exit(1); });
2878
+ run().catch((e) => quit(1, e));
2507
2879
  }
2508
2880
  }
2509
2881
 
2510
2882
  if (require.main === module) {
2511
- process.on('exit', () => codexHistory.close());
2512
- try { main(); } catch (err) { console.error(err.message); process.exitCode = 1; }
2883
+ if (profile.enabled) profile.start(() => ({ IMG: IMG.size, PREV: PREV.size, GITC: GITC.size, BRANCH: BRANCH.size, STATS: STATS.size }));
2884
+ process.on('exit', () => { if (!shuttingDown) { if (active || idleCursor || process.stdin.isRaw) restoreTerminal(true); safely(closeCodexHistory); safely(closeClaudeHistory); safely(cacheSave); } });
2885
+ try { main(); } catch (err) { if (idleCursor) quit(1, err); else { console.error(err.message); process.exitCode = 1; } }
2513
2886
  }
2514
2887
  else {
2515
2888
  // al hacer require() (pruebas automáticas) no se ejecuta nada: solo se exponen las piezas puras
2516
2889
  module.exports = {
2517
- cw, strW, fit, clean, hl, gitRows, gitInfo, toggleGit, imageExt, exportImages, safeId, findClaude, install, backupProfile, ago, tidy, fuzzy, wrapText, parseKeys, KEYMAP, isType, T, S, CFG, E,
2890
+ cw, strW, fit, clean, hl, gitRows, gitInfo, toggleGit, imageExt, exportImages, safeId, findClaude, install, backupProfile, loadCfg, createShutdown, ago, tidy, fuzzy, wrapText, parseKeys, KEYMAP, isType, T, S, CFG, E,
2518
2891
  readSession, buildProject, scan, scanAsync, finishScan, sortProjects, projectDirs,
2519
- view, flatList, stripBlock, offerShortcut, uninstallAll, commandName, suggestCommand, parseTermReplies, sixelOn, SNIP, MARK_A, MARK_B, toggleProject, cacheLoad, selNorm,
2892
+ view, flatList, computeView, computeFlatList, qsItems, replaceProjects, invalidateView, embedLive, toggleArchive, archived, spinTick, scheduleRender, termRow, stripBlock, targets, offerShortcut, uninstallAll, commandName, suggestCommand, parseTermReplies, sixelOn, SNIP, MARK_A, MARK_B, toggleProject, cacheLoad, selNorm,
2520
2893
  decodePNG, decodeImage, scaleBox, fitSize, halfBlocks, collectImages, extractImages,
2521
- onMouse, dragPanel, panelLimits, embedLayout, sessTag, editBuf, normalizeKeys, stripJsonc, wtCtrlV, fbNames, fbOpen, fbRows, sidebarMouse, toggleTheme, gitBranch, imageMarkerAt, codexMarkerOffset, shownSession, linkChats, findImageByNumber: images.findImageByNumber,
2894
+ pruneGallery, IMG, PREV, GITC, BRANCH, STATS,
2895
+ onMouse, dragPanel, panelLimits, embedLayout, sessTag, editBuf, normalizeKeys, stripJsonc, wtCtrlV, openExternal, listDrives, fbNames, fbOpen, fbRows, sidebarMouse, toggleTheme, gitBranch, imageMarkerAt, codexMarkerOffset, shownSession, linkChats, findImageByNumber: images.findImageByNumber,
2522
2896
  };
2523
2897
  }