hopdeck 1.5.6 → 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/lib/history.js CHANGED
@@ -3,9 +3,19 @@
3
3
  const fs = require('fs');
4
4
  const os = require('os');
5
5
  const path = require('path');
6
+ const profile = require('./profile');
7
+ const { readJsonSafe, writeJsonAtomic } = require('./atomic');
6
8
  const { baseName, tidy } = require('./text');
9
+ const { isWSL } = require('./wsl');
10
+ const { setImmediate: yieldLoop } = require('timers/promises');
11
+
12
+ const HOT_MS = 48 * 3600000, SWEEP_MS = 5 * 60000, SAVE_MS = 60000, WATCH_MS = 300;
13
+ const SCAN_CONCURRENCY = 32;
14
+ const WATCH_SEPARATORS = process.platform === 'win32' ? /[\\/]/ : /\//;
7
15
 
8
16
  const CONFIG_DIR = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude');
17
+ const PROJECTS_ROOT = path.join(CONFIG_DIR, 'projects');
18
+ const HEAD_CHUNK = 128 * 1024, HEAD_MAX = 4 * 1024 * 1024;
9
19
 
10
20
  function textOf(content) {
11
21
  if (typeof content === 'string') return content;
@@ -20,22 +30,29 @@ function textOf(content) {
20
30
  const CACHE_FILE = process.env.HOPDECK_CACHE || path.join(os.homedir(), '.hopdeck-cache.json');
21
31
  // Sube la versión cuando cambie cómo se lee una sesión: así las cachés ya guardadas se reconstruyen en vez de repetir resultados antiguos.
22
32
  const CACHE_VERSION = 3;
23
- let CACHE = null, cacheDirty = false, cacheSeen = null;
33
+ let CACHE = null, cacheDirty = false, cacheSeen = null, lastSave = -Infinity;
24
34
  /** Empieza un escaneo: las entradas de la caché que no se vean se descartan al terminar. */
25
35
  const beginScan = () => { cacheSeen = new Set(); };
26
- const endScan = () => { cacheSave(); cacheSeen = null; };
36
+ function endScan() {
37
+ if (cacheSeen) for (const f of Object.keys(cacheLoad().files)) if (!cacheSeen.has(f)) { delete CACHE.files[f]; cacheDirty = true; }
38
+ cacheSeen = null; cacheSave();
39
+ }
27
40
  function cacheLoad() {
28
41
  if (CACHE) return CACHE;
29
- try { const j = JSON.parse(fs.readFileSync(CACHE_FILE, 'utf8')); CACHE = j && j.v === CACHE_VERSION && j.files ? j : { v: CACHE_VERSION, files: {} }; } catch { CACHE = { v: CACHE_VERSION, files: {} }; }
42
+ const { value: j } = readJsonSafe(CACHE_FILE);
43
+ CACHE = j?.v === CACHE_VERSION && j.files && typeof j.files === 'object' && !Array.isArray(j.files) ? j : { v: CACHE_VERSION, files: {} };
30
44
  return CACHE;
31
45
  }
32
- function cacheSave() {
33
- if (!CACHE) return;
34
- if (cacheSeen) for (const f of Object.keys(CACHE.files)) if (!cacheSeen.has(f)) { delete CACHE.files[f]; cacheDirty = true; }
35
- if (!cacheDirty) return;
46
+ function cacheSave({ force = true, now = Date.now() } = {}) {
47
+ if (!cacheDirty || (!force && now - lastSave < SAVE_MS)) return;
48
+ lastSave = now;
36
49
  // la caché contiene títulos y primeros mensajes: permisos solo para el usuario
37
- try { fs.writeFileSync(CACHE_FILE + '.tmp', JSON.stringify(CACHE), { mode: 0o600 }); fs.renameSync(CACHE_FILE + '.tmp', CACHE_FILE); } catch { /* sin permisos */ }
38
- cacheDirty = false;
50
+ const started = profile.now();
51
+ try {
52
+ const bytes = writeJsonAtomic(CACHE_FILE, CACHE);
53
+ if (profile.enabled) profile.duration('cacheSave', started, { bytes });
54
+ cacheDirty = false;
55
+ } catch { /* sin permisos */ }
39
56
  }
40
57
 
41
58
  /** ¿La línea JSON es de ese tipo? (tolera espacios; Claude escribe JSON compacto) */
@@ -44,26 +61,29 @@ const isType = (line, t) => line.includes(`"type":"${t}"`) || new RegExp(`"type"
44
61
  function readSession(file) {
45
62
  let st;
46
63
  try { st = fs.statSync(file); } catch { return null; }
64
+ if (!st.isFile()) return null;
47
65
  const cache = cacheLoad(); if (cacheSeen) cacheSeen.add(file);
48
66
  const hit = cache.files[file];
49
- if (hit && hit.m === st.mtimeMs && hit.z === st.size) return hit.d ? { ...hit.d, file, mtime: st.mtimeMs } : null;
67
+ if (matches(hit, st)) return cachedSession(file, hit);
50
68
  const d = parseSession(file, st);
51
- cache.files[file] = { m: st.mtimeMs, z: st.size, d: d ? { id: d.id, title: d.title, first: d.first, cwd: d.cwd, root: d.root, last: d.last } : null };
52
- cacheDirty = true;
69
+ cache.files[file] = cacheEntry(st, d); cacheDirty = true;
53
70
  return d;
54
71
  }
55
72
 
73
+ const matches = (hit, st) => hit && hit.m === st.mtimeMs && hit.z === st.size;
74
+ const cachedSession = (file, hit) => hit?.d ? { ...hit.d, file, mtime: hit.m } : null;
75
+ const cacheEntry = (st, d) => ({ m: st.mtimeMs, z: st.size, d: d ? { id: d.id, title: d.title, first: d.first, cwd: d.cwd, root: d.root, last: d.last } : null });
76
+
56
77
  /**
57
78
  * Recorre el principio del archivo por bloques, línea a línea, hasta que `onLine` devuelva true (ya tiene lo que busca)
58
79
  * o se llegue a HEAD_MAX bytes. Antes solo se leían los primeros 64 KB: si el primer mensaje llevaba una imagen
59
80
  * (una línea de cientos de KB) caía fuera y la conversación se descartaba por no tener título.
60
81
  */
61
- function scanHead(fd, size, onLine) {
62
- const CHUNK = 128 * 1024, HEAD_MAX = 4 * 1024 * 1024;
82
+ function* scanHead(size, onLine, whole) {
63
83
  let pos = 0, carry = Buffer.alloc(0);
64
84
  while (pos < size && pos < HEAD_MAX) {
65
- const buf = Buffer.alloc(Math.min(CHUNK, size - pos));
66
- const n = fs.readSync(fd, buf, 0, buf.length, pos);
85
+ const buf = whole || Buffer.alloc(Math.min(HEAD_CHUNK, size - pos));
86
+ const n = whole ? whole.length : yield [buf, pos];
67
87
  if (!n) break;
68
88
  pos += n;
69
89
  const data = carry.length ? Buffer.concat([carry, buf.subarray(0, n)]) : buf.subarray(0, n);
@@ -79,57 +99,89 @@ function scanHead(fd, size, onLine) {
79
99
 
80
100
  function parseSession(file, st) {
81
101
  let fd;
82
- try { fd = fs.openSync(file, 'r'); } catch { return null; }
83
102
  try {
84
- const TAIL = 160 * 1024;
85
- let cwd = '', first = '', custom = '', ai = '', root = '';
86
- scanHead(fd, st.size, (line) => {
87
- if (!line) return false;
88
- const wantCwd = !cwd && line.includes('"cwd"');
89
- const wantUser = !first && isType(line, 'user');
90
- const wantTitle = line.includes('-title"');
91
- const wantRoot = !root && !first && line.includes('"uuid"'); // el primer mensaje del archivo; el primer "user" ya lo trae si antes no hubo otro
92
- if (wantCwd || wantUser || wantTitle || wantRoot) {
93
- let j; try { j = JSON.parse(line); } catch { j = null; }
94
- if (j) {
95
- // Al reanudar o continuar una conversación, Claude Code crea un archivo nuevo que copia el historial desde el principio:
96
- // todos comparten el uuid del primer mensaje, y eso permite saber que son la misma conversación.
97
- if (!root && typeof j.uuid === 'string') root = j.uuid;
98
- if (wantCwd && j.cwd) cwd = j.cwd;
99
- if (j.type === 'custom-title' && j.customTitle) custom = j.customTitle;
100
- if (j.type === 'ai-title' && j.aiTitle) ai = j.aiTitle;
101
- if (wantUser && j.type === 'user' && !j.isMeta && !j.isSidechain) {
102
- const t = tidy(textOf(j.message && j.message.content));
103
- if (t && !t.startsWith('<') && !t.startsWith('[Request interrupted')) first = t.slice(0, 300);
104
- }
103
+ fd = fs.openSync(file, 'r');
104
+ const parser = sessionParser(file, st);
105
+ let step = parser.next();
106
+ while (!step.done) {
107
+ const [buf, pos] = step.value;
108
+ step = parser.next(fs.readSync(fd, buf, 0, buf.length, pos));
109
+ }
110
+ return step.value;
111
+ } catch { return null; } finally { if (fd !== undefined) try { fs.closeSync(fd); } catch { /* */ } }
112
+ }
113
+
114
+ async function parseSessionAsync(file, st, io) {
115
+ let fd;
116
+ try {
117
+ fd = await io.open(file, 'r');
118
+ const parser = sessionParser(file, st);
119
+ let step = parser.next();
120
+ while (!step.done) {
121
+ const [buf, pos] = step.value;
122
+ const { bytesRead } = await fd.read(buf, 0, buf.length, pos);
123
+ step = parser.next(bytesRead);
124
+ }
125
+ return step.value;
126
+ } catch { return null; } finally { if (fd) try { await fd.close(); } catch { /* */ } }
127
+ }
128
+
129
+ // El lector síncrono y el paralelo ejecutan el mismo analizador.
130
+ function* sessionParser(file, st) {
131
+ const TAIL = 160 * 1024;
132
+ // Los archivos pequeños caben en una sola lectura para cabecera y cola.
133
+ let whole;
134
+ if (st.size > 0 && st.size <= HEAD_CHUNK) {
135
+ const buf = Buffer.alloc(st.size);
136
+ if ((yield [buf, 0]) === st.size) whole = buf;
137
+ }
138
+ let cwd = '', first = '', custom = '', ai = '', root = '';
139
+ yield* scanHead(st.size, (line) => {
140
+ if (!line) return false;
141
+ const wantCwd = !cwd && line.includes('"cwd"');
142
+ const wantUser = !first && isType(line, 'user');
143
+ const wantTitle = line.includes('-title"');
144
+ const wantRoot = !root && !first && line.includes('"uuid"'); // el primer mensaje del archivo; el primer "user" ya lo trae si antes no hubo otro
145
+ if (wantCwd || wantUser || wantTitle || wantRoot) {
146
+ let j; try { j = JSON.parse(line); } catch { j = null; }
147
+ if (j) {
148
+ // Al reanudar o continuar una conversación, Claude Code crea un archivo nuevo que copia el historial desde el principio:
149
+ // todos comparten el uuid del primer mensaje, y eso permite saber que son la misma conversación.
150
+ if (!root && typeof j.uuid === 'string') root = j.uuid;
151
+ if (wantCwd && typeof j.cwd === 'string') cwd = j.cwd;
152
+ if (j.type === 'custom-title' && j.customTitle) custom = j.customTitle;
153
+ if (j.type === 'ai-title' && j.aiTitle) ai = j.aiTitle;
154
+ if (wantUser && j.type === 'user' && !j.isMeta && !j.isSidechain) {
155
+ const t = tidy(textOf(j.message && j.message.content));
156
+ if (t && !t.startsWith('<') && !t.startsWith('[Request interrupted')) first = t.slice(0, 300);
105
157
  }
106
158
  }
107
- return !!(cwd && first); // con la carpeta y el primer mensaje ya no hace falta leer más del principio
108
- });
109
- // los títulos más recientes están al final del archivo
110
- const len = Math.min(st.size, TAIL), tb = Buffer.alloc(len);
111
- fs.readSync(fd, tb, 0, len, st.size - len);
112
- const tail = tb.toString('utf8').split('\n');
113
- if (st.size > len) tail.shift(); // primera línea cortada
114
- let tCustom = '', tAi = '';
115
- for (let i = tail.length - 1; i >= 0; i--) {
116
- const line = tail[i];
117
- if (!line.includes('-title"')) continue;
118
- let j; try { j = JSON.parse(line); } catch { continue; }
119
- if (!tCustom && j.type === 'custom-title' && j.customTitle) tCustom = j.customTitle;
120
- if (!tAi && j.type === 'ai-title' && j.aiTitle) tAi = j.aiTitle;
121
- if (tCustom) break;
122
- }
123
- const title = tidy(tCustom || custom || tAi || ai || first || '');
124
- if (!title) return null; // sesión vacía
125
- // fecha del último mensaje real: la fecha del archivo cambia también al abrir la conversación o al renombrarla
126
- let last = 0;
127
- for (let i = tail.length - 1; i >= 0 && !last; i--) {
128
- if (!isType(tail[i], 'user') && !isType(tail[i], 'assistant')) continue;
129
- try { const j = JSON.parse(tail[i]); if (j.type === 'user' || j.type === 'assistant') last = Date.parse(j.timestamp) || 0; } catch { /* línea cortada */ }
130
159
  }
131
- return { id: path.basename(file, '.jsonl'), file, title, first, cwd, root, last, mtime: st.mtimeMs };
132
- } catch { return null; } finally { try { fs.closeSync(fd); } catch { /* */ } }
160
+ return !!(cwd && first); // con la carpeta y el primer mensaje ya no hace falta leer más del principio
161
+ }, whole);
162
+ // los títulos más recientes están al final del archivo
163
+ const len = Math.min(st.size, TAIL), tb = whole || Buffer.alloc(len);
164
+ if (len && !whole) yield [tb, st.size - len];
165
+ const tail = tb.toString('utf8').split('\n');
166
+ if (st.size > len) tail.shift(); // primera línea cortada
167
+ let tCustom = '', tAi = '';
168
+ for (let i = tail.length - 1; i >= 0; i--) {
169
+ const line = tail[i];
170
+ if (!line.includes('-title"')) continue;
171
+ let j; try { j = JSON.parse(line); } catch { continue; }
172
+ if (!tCustom && j.type === 'custom-title' && j.customTitle) tCustom = j.customTitle;
173
+ if (!tAi && j.type === 'ai-title' && j.aiTitle) tAi = j.aiTitle;
174
+ if (tCustom) break;
175
+ }
176
+ const title = tidy(tCustom || custom || tAi || ai || first || '');
177
+ if (!title) return null; // sesión vacía
178
+ // fecha del último mensaje real: la fecha del archivo cambia también al abrir la conversación o al renombrarla
179
+ let last = 0;
180
+ for (let i = tail.length - 1; i >= 0 && !last; i--) {
181
+ if (!isType(tail[i], 'user') && !isType(tail[i], 'assistant')) continue;
182
+ try { const j = JSON.parse(tail[i]); if (j.type === 'user' || j.type === 'assistant') last = Date.parse(j.timestamp) || 0; } catch { /* línea cortada */ }
183
+ }
184
+ return { id: path.basename(file, '.jsonl'), file, title, first, cwd, root, last, mtime: st.mtimeMs };
133
185
  }
134
186
 
135
187
  function decodeDir(name) { // mejor esfuerzo si ninguna sesión trae cwd
@@ -138,8 +190,7 @@ function decodeDir(name) { // mejor esfuerzo si ninguna sesión trae cwd
138
190
  }
139
191
 
140
192
  function projectDirs() {
141
- const root = path.join(CONFIG_DIR, 'projects');
142
- try { return fs.readdirSync(root, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => path.join(root, d.name)); } catch { return []; }
193
+ try { return fs.readdirSync(PROJECTS_ROOT, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => path.join(PROJECTS_ROOT, d.name)); } catch { return []; }
143
194
  }
144
195
 
145
196
  /**
@@ -167,7 +218,10 @@ function foldContinuations(sessions) {
167
218
  function buildProject(dir) {
168
219
  let files = [];
169
220
  try { files = fs.readdirSync(dir).filter((f) => f.endsWith('.jsonl')); } catch { return null; }
170
- const all = files.map((f) => readSession(path.join(dir, f))).filter(Boolean);
221
+ return groupProject(dir, files.map((f) => readSession(path.join(dir, f))).filter(Boolean));
222
+ }
223
+
224
+ function groupProject(dir, all) {
171
225
  if (!all.length) return null;
172
226
  all.sort((a, b) => b.mtime - a.mtime);
173
227
  const sessions = foldContinuations(all);
@@ -175,8 +229,159 @@ function buildProject(dir) {
175
229
  for (const x of sessions) { const k = x.title + '|' + x.first; seen[k] = (seen[k] || 0) + 1; }
176
230
  for (const x of sessions) x.dup = seen[x.title + '|' + x.first] > 1;
177
231
  const key = path.basename(dir);
178
- const cwd = (sessions.find((s) => s.cwd) || {}).cwd || decodeDir(key);
232
+ const cwd = (sessions.find((s) => typeof s.cwd === 'string' && s.cwd) || {}).cwd || decodeDir(key);
179
233
  return { key, cwd, name: baseName(cwd), sessions, mtime: sessions[0].mtime };
180
234
  }
181
235
 
182
- module.exports = { CONFIG_DIR, CACHE_FILE, textOf, isType, cacheLoad, cacheSave, beginScan, endScan, readSession, parseSession, foldContinuations, decodeDir, projectDirs, buildProject };
236
+
237
+ const byTime = (a, b) => b.mtime - a.mtime;
238
+ const fsList = async (io, dir, options) => { try { return await io.readdir(dir, options); } catch { return null; } };
239
+ const fsStat = async (io, file) => { try { return await io.stat(file); } catch { return null; } };
240
+
241
+ function projectsFromCache(root = PROJECTS_ROOT) {
242
+ const groups = new Map(); let found = false;
243
+ const files = Object.keys(cacheLoad().files);
244
+ // El orden de readdir desempata las fechas iguales. UTF-16 solo difiere de UTF-8
245
+ // si hay caracteres suplementarios y caracteres BMP superiores a los sustitutos.
246
+ const byPath = files.some((f) => /[\ud800-\udfff]/.test(f)) ? (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)) : undefined;
247
+ files.sort(byPath);
248
+ for (const file of files) {
249
+ const dir = path.dirname(file);
250
+ if (path.dirname(dir) !== root || !file.endsWith('.jsonl')) continue;
251
+ found = true;
252
+ const session = cachedSession(file, CACHE.files[file]);
253
+ if (!session) continue;
254
+ if (!groups.has(dir)) groups.set(dir, []);
255
+ groups.get(dir).push(session);
256
+ }
257
+ return found ? [...groups.keys()].sort(byPath).map((dir) => groupProject(dir, groups.get(dir))).sort(byTime) : null;
258
+ }
259
+
260
+ function scanConcurrency() {
261
+ const n = Number(process.env.HOPDECK_SCAN_CONCURRENCY);
262
+ return Number.isSafeInteger(n) && n > 0 ? Math.min(n, 256) : SCAN_CONCURRENCY;
263
+ }
264
+
265
+ async function parallel(items, limit, signal, work) {
266
+ let next = 0, failure;
267
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
268
+ try {
269
+ while (!failure && next < items.length) {
270
+ signal?.throwIfAborted();
271
+ await work(items[next++]);
272
+ }
273
+ } catch (err) { failure = err; }
274
+ }));
275
+ if (failure) throw failure;
276
+ signal?.throwIfAborted();
277
+ }
278
+
279
+ function createProjectScanner({ root = PROJECTS_ROOT, io = fs.promises, watch = fs.watch, platform = process.platform,
280
+ wsl, now = Date.now, reloadMs = 20000, sweepMs = SWEEP_MS } = {}) {
281
+ let dirs = new Map(), initialized = false, pending, coldCursor = '', watcher, timer, dirty = new Set();
282
+ async function scan({ concurrency = scanConcurrency(), onProgress, signal, full = false } = {}) {
283
+ signal?.throwIfAborted();
284
+ concurrency = Number.isSafeInteger(concurrency) && concurrency > 0 ? Math.min(concurrency, 256) : SCAN_CONCURRENCY;
285
+ const all = full || !initialized, touched = dirty; dirty = new Set();
286
+ try {
287
+ const entries = await fsList(io, root, { withFileTypes: true });
288
+ signal?.throwIfAborted();
289
+ const names = (entries || []).filter((d) => d.isDirectory()).map((d) => path.join(root, d.name));
290
+ const next = new Map(), jobs = [], cold = [], updates = new Map(), stale = new Set();
291
+ const time = now(), cache = cacheLoad().files;
292
+ await parallel(names, concurrency, signal, async (dir) => {
293
+ const previous = dirs.get(dir);
294
+ const stamp = await fsStat(io, dir);
295
+ const relist = all || touched.has(root) || touched.has(dir) || !previous || previous.m !== stamp?.mtimeMs;
296
+ const listed = relist && stamp ? await fsList(io, dir) : null;
297
+ const files = relist ? (listed || []).filter((f) => f.endsWith('.jsonl')).map((f) => path.join(dir, f)) : previous.files;
298
+ if (listed || !relist) next.set(dir, { m: stamp.mtimeMs, files });
299
+ if (previous && relist) {
300
+ const kept = new Set(files);
301
+ for (const file of previous.files) if (!kept.has(file)) stale.add(file);
302
+ }
303
+ for (const file of files) {
304
+ const hit = cache[file];
305
+ if (relist || !hit || hit.m >= time - HOT_MS) jobs.push(file);
306
+ else cold.push(file);
307
+ }
308
+ });
309
+ cold.sort();
310
+ let start = cold.findIndex((file) => file > coldCursor);
311
+ if (start < 0) start = 0;
312
+ const count = Math.min(cold.length, Math.ceil(cold.length / Math.max(1, Math.floor(sweepMs / reloadMs))));
313
+ for (let i = 0; i < count; i++) jobs.push(cold[(start + i) % cold.length]);
314
+ if (touched.size) {
315
+ const scheduled = new Set(jobs);
316
+ for (const file of touched) if (file.endsWith('.jsonl') && !scheduled.has(file) && next.get(path.dirname(file))?.files.includes(file)) jobs.push(file);
317
+ }
318
+ let done = 0, lastYield = performance.now();
319
+ onProgress?.(0, jobs.length);
320
+ await parallel(jobs, concurrency, signal, async (file) => {
321
+ const st = await fsStat(io, file), hit = cache[file];
322
+ if (!st?.isFile()) stale.add(file);
323
+ else if (!matches(hit, st)) updates.set(file, cacheEntry(st, st.size ? await parseSessionAsync(file, st, io) : null));
324
+ onProgress?.(++done, jobs.length);
325
+ });
326
+ const projects = [];
327
+ for (const dir of names) {
328
+ const sessions = [];
329
+ for (const file of next.get(dir)?.files || []) {
330
+ const session = !stale.has(file) && cachedSession(file, updates.get(file) || cache[file]);
331
+ if (session) sessions.push(session);
332
+ if (performance.now() - lastYield > 4) { await yieldLoop(); signal?.throwIfAborted(); lastYield = performance.now(); }
333
+ }
334
+ const project = groupProject(dir, sessions);
335
+ if (project) projects.push(project);
336
+ }
337
+ if (all) {
338
+ const seen = new Set([...next.values()].flatMap((d) => d.files));
339
+ for (const file of Object.keys(cache)) if (!seen.has(file)) stale.add(file);
340
+ } else {
341
+ for (const [dir, state] of dirs) if (!next.has(dir)) for (const file of state.files) stale.add(file);
342
+ }
343
+ for (const file of stale) if (Object.hasOwn(cache, file)) { delete cache[file]; cacheDirty = true; }
344
+ for (const [file, entry] of updates) { cache[file] = entry; cacheDirty = true; }
345
+ dirs = next;
346
+ if (count) coldCursor = cold[(start + count - 1) % cold.length];
347
+ cacheSave({ force: !initialized, now: now() });
348
+ initialized = true;
349
+ return projects.sort(byTime);
350
+ } catch (err) {
351
+ for (const item of touched) dirty.add(item);
352
+ throw err;
353
+ }
354
+ }
355
+
356
+ function scanProjectsAsync(options) {
357
+ if (pending) return pending;
358
+ pending = scan(options).finally(() => { pending = null; });
359
+ return pending;
360
+ }
361
+
362
+ function closeWatcher() {
363
+ clearTimeout(timer); watcher?.close(); watcher = null;
364
+ }
365
+
366
+ function watchProjects(onChange) {
367
+ if (watcher || !['darwin', 'win32', 'linux'].includes(platform) ||
368
+ (platform === 'linux' && /^\/mnt\/[a-z](?:\/|$)/i.test(path.resolve(root)) && (wsl ?? isWSL()))) return;
369
+ try {
370
+ watcher = watch(root, { recursive: true, persistent: false }, (event, filename) => {
371
+ const parts = filename ? filename.split(WATCH_SEPARATORS) : [];
372
+ const dir = parts[0] && path.join(root, parts[0]);
373
+ if (!dir) dirty.add(root);
374
+ else if (parts.length === 1 || (parts.length === 2 && event === 'rename')) dirty.add(dir);
375
+ else if (parts.length === 2 && parts[1].endsWith('.jsonl')) dirty.add(path.join(dir, parts[1]));
376
+ else return;
377
+ clearTimeout(timer);
378
+ timer = setTimeout(onChange, WATCH_MS).unref();
379
+ });
380
+ watcher.on('error', closeWatcher);
381
+ } catch { closeWatcher(); }
382
+ }
383
+
384
+ return { scanProjectsAsync, watchProjects, closeWatcher };
385
+ }
386
+
387
+ module.exports = { CONFIG_DIR, CACHE_FILE, textOf, isType, cacheLoad, cacheSave, beginScan, endScan, readSession, parseSession, foldContinuations, decodeDir, projectDirs, buildProject, projectsFromCache, createProjectScanner };
package/lib/i18n.js CHANGED
@@ -16,8 +16,13 @@ const T = {
16
16
  exited: (c) => `La conversación terminó (código ${c})`, closed: (t) => `Conversación cerrada: ${t}`, confirmClose: 'Está trabajando. Pulsa c otra vez para cerrarla', notOpen: 'No hay ninguna conversación abierta que cerrar',
17
17
  noImages: 'Esta conversación no tiene imágenes', findImgs: 'Buscando imágenes…', decoding: 'Preparando imagen…',
18
18
  linkOpened: 'Enlace abierto en el navegador',
19
+ linkFailed: (missing) => 'No se pudo abrir el enlace' + (missing ? ' · instala xdg-utils' : ''),
20
+ imgOpenFailed: (missing) => 'No se pudo abrir la imagen en el visor' + (missing ? ' · instala xdg-utils' : ''),
21
+ shortcutUnclosed: (file) => `Bloque de Hopdeck sin cerrar en ${file}`,
19
22
  imgNoPrev: 'No se puede previsualizar este formato', imgHint: '← → navegar o abrir en el visor esc cerrar', imgFolder: 'Imágenes abiertas en el visor',
20
23
  more: (n) => `mostrar ${n} más…`, busyRename: 'Cierra la conversación antes de renombrarla', renameLbl: 'nombre',
24
+ copyNoTool: (wayland) => `No se pudo copiar. Prueba con sudo apt install ${wayland ? 'wl-clipboard' : 'xclip'}`,
25
+ copyFailed: 'No se pudo copiar al portapapeles.',
21
26
  copied: (n) => `Copiado (${n} caracteres)`, archMsg: 'Archivada (H para verlas)', unarchMsg: 'Desarchivada', qsHint: 'saltar a cualquier conversación',
22
27
  prevHint: '⏎ reanudar esta conversación', bar8: 'git', gitNone: 'Elige un proyecto', gitNoRepo: 'Esta carpeta no es un repositorio git', gitMissing: 'git no está instalado', gitErr: 'No se pudo leer el repositorio', gitClean: 'sin cambios', gitDirty: (n) => (n === 1 ? '1 cambio sin guardar' : `${n} cambios sin guardar`), gitMore: (n) => `… y ${n} más`, gitBranches: 'Ramas recientes', gitActivity: 'Actividad de ramas', gitNoActivity: 'Sin cambios de rama', gitFrom: 'desde', gitNarrow: (n) => `Terminal estrecha: el panel de git necesita ${n} columnas`, gitOnlyEmbed: 'El panel de git solo está en el terminal integrado', prevInfo: (a, n) => `${a === 'ahora' ? 'ahora mismo' : 'hace ' + a} · últimos ${n} mensajes`, kUnfold: 'desplegar', kRename: 'renombrar', kPin: 'fijar', kHelp: 'ayuda', kArchive: 'archivar', kHide: 'ocultar', noPrev: 'Sin mensajes para mostrar',
23
28
  bar6: 'ocultar lista', bar7: 'mostrar lista', deep: 'contenido', pathPrompt: 'nombre de la nueva carpeta', mkIn: 'se crea en', fbTitle: 'Elegir carpeta', fbHere: 'Abrir chat aquí', fbNew: 'Nueva carpeta aquí…', fbUp: 'Subir un nivel', fbProj: 'proyecto', fbHint: '⏎ entrar · ␣ abrir · / buscar · . ocultas', fbDrives: 'Este equipo', fbRecent: 'reciente', hoverMiss: (n) => `[Image #${n}]: aún no está en el historial`, fbEmpty: 'Sin subcarpetas', badId: 'Identificador de sesión no válido',
@@ -34,8 +39,19 @@ const T = {
34
39
  dcNodeOld: (v) => `Node ${v}: se necesita Node 22 o superior`, dcNodeOldHint: 'Con versiones anteriores el ratón no funciona en Windows. Actualiza Node: https://nodejs.org',
35
40
  dcHist: (n, p) => `Historial de Claude: ${n} proyectos en ${p}`, dcNoHist: (p) => `No hay historial en ${p}`, dcNoHistHint: 'Usa Claude Code una vez, o define CLAUDE_CONFIG_DIR.',
36
41
  dcClaude: (p) => `claude encontrado: ${p}`, dcNoClaude: 'No se encuentra "claude" en el PATH', dcInstallWin: 'Instálalo: irm https://claude.ai/install.ps1 | iex', dcInstallUnix: 'Instálalo: curl -fsSL https://claude.ai/install.sh | bash',
37
- dcTmux: 'tmux disponible → vista dividida con tmux', dcEmbed: 'Terminal embebido disponible (node-pty + xterm) → vista dividida',
38
- dcNone: 'Sin tmux ni terminal embebido → vista a pantalla completa', dcNoneWin: 'Ejecuta npm install dentro de la carpeta del paquete.', dcNoneUnix: 'Instala tmux (brew install tmux / sudo apt install tmux).',
42
+ dcTmux: 'Vista dividida con tmux', dcEmbed: 'Vista dividida con terminal embebido (node-pty + xterm)',
43
+ dcTmuxOpt: 'tmux disponible con HOPDECK_TMUX=1', dcTmuxOld: 'La vista dividida con tmux requiere tmux 3.1 o superior.',
44
+ dcNone: 'Vista a pantalla completa',
45
+ tmuxNested: 'Hopdeck ya está dentro de tmux. Se usará la vista embebida.',
46
+ tmuxNestedFull: 'Hopdeck ya está dentro de tmux. Se usará la vista a pantalla completa.',
47
+ tmuxStartFailed: (err) => `No se pudo iniciar la sesión tmux (${err}).`,
48
+ tmuxAttachFailed: (err) => `No se pudo conectar a la sesión tmux (${err}).`,
49
+ dcPtyHelper: 'spawn-helper de node-pty ejecutable', dcPtyHelperBad: 'spawn-helper de node-pty no disponible o sin permiso de ejecución',
50
+ ptyChmod: (file) => `Comprueba los permisos de spawn-helper de node-pty. Ejecuta chmod +x ${file}`,
51
+ ptyGeneric: 'Comprueba que spawn-helper de node-pty existe y tiene permiso de ejecución (chmod +x).',
52
+ winBadArgs: 'La línea de comandos incluye caracteres que cmd.exe no admite.',
53
+ winUnsupported: (bin) => `Windows no puede abrir este archivo de la CLI: ${bin}. Usa un archivo .exe, .com, .cmd o .bat.`,
54
+ dcPolicy: (policy) => `La política de ejecución de PowerShell es ${policy}. Es posible que no se cargue el atajo de Hopdeck del perfil.`, dcPolicyHint: 'Set-ExecutionPolicy -Scope CurrentUser RemoteSigned',
39
55
  dcShort: 'Atajo instalado: escribir "claude" abre Hopdeck', dcNoShort: 'Atajo no instalado', dcNoShortHint: 'Ejecuta: hopdeck shortcut on', dcNoCmdHint: 'Primero crea el comando (npm install -g hopdeck, o npm link si clonaste el repositorio) y luego ejecuta: hopdeck shortcut on', dcPrefs: (a, b) => `Preferencias: ${a} · caché: ${b}`, bakMsg: (f) => `Copia de seguridad de tu perfil: ${f}`,
40
56
  wtOk: 'Windows Terminal: Ctrl+V está reasignado (se pueden pegar imágenes)', wtBad: 'Windows Terminal: Ctrl+V solo pega texto, no imágenes', wtUnknown: 'Windows Terminal: no pude leer su settings.json para revisar Ctrl+V',
41
57
  wtHint: 'Para pegar imágenes con Ctrl+V añade en "actions" de settings.json:\n { "command": { "action": "sendInput", "input": "\\u001bv" }, "keys": "ctrl+v" }\n (el texto se sigue pegando con Ctrl+Shift+V). Alternativa sin tocar nada: Alt+V.',
@@ -51,6 +67,17 @@ const T = {
51
67
  searchPh: 'buscar conversación o proyecto…', found: (n) => `${n} ${n === 1 ? 'resultado' : 'resultados'}`, noRes: (q) => `Sin resultados para «${q}»`,
52
68
  searchingContent: 'Buscando dentro de las conversaciones…', tryContent: 'Pulsa Tab para buscar también dentro del contenido', inContent: 'en el contenido', kClear: 'limpiar', kEdit: 'editar', kEsc: 'salir',
53
69
  inside: 'Ya estás dentro de Hopdeck (F1 para ir a la lista de proyectos).',
70
+ setupChoose: '¿Qué quieres usar con Hopdeck?', setupChoices: '[1] Claude Code [2] Codex [Esc] salir',
71
+ setupMissing: (name) => `${name} todavía no está instalado.`,
72
+ setupInstallInfo: 'Hopdeck puede descargar y ejecutar el instalador oficial para tu cuenta. Requiere internet.',
73
+ setupSource: (url) => `Origen: ${url}`, setupInstallKeys: '[Enter] Instalar ahora [Esc] salir',
74
+ setupInstalling: (name) => `Instalando ${name}…`, setupInstalled: (name) => `${name} instalado y listo.`,
75
+ setupFailed: (name) => `No se pudo preparar ${name}.`, setupRetryKeys: '[r] Reintentar [Enter/Esc] salir',
76
+ setupCancelled: 'Instalación cancelada. Puedes volver a abrir Hopdeck para intentarlo más tarde.',
77
+ setupUnavailable: (name, id) => `${name} no está disponible. Abre hopdeck --provider ${id} en una terminal interactiva para instalarlo.`,
78
+ setupLoginInfo: (name) => `Inicia sesión con ${name}. La CLI oficial gestiona tu cuenta y la autenticación.`,
79
+ setupLoginKeys: '[Enter] Iniciar sesión [m] Más tarde [Esc] salir', setupLoginDone: 'Sesión iniciada. Continuando a tus proyectos…',
80
+ setupLoginFailed: 'No se completó el inicio de sesión. Puedes reintentarlo o continuar más tarde.',
54
81
  },
55
82
  en: {
56
83
  projects: 'PROJECTS', sessions: 'SESSIONS', newChat: 'New conversation',
@@ -65,8 +92,13 @@ const T = {
65
92
  exited: (c) => `The conversation ended (code ${c})`, closed: (t) => `Conversation closed: ${t}`, confirmClose: 'It is working. Press c again to close it', notOpen: 'There is no open conversation to close',
66
93
  noImages: 'This conversation has no images', findImgs: 'Looking for images…', decoding: 'Preparing image…',
67
94
  linkOpened: 'Link opened in the browser',
95
+ linkFailed: (missing) => 'Could not open the link' + (missing ? ' · install xdg-utils' : ''),
96
+ imgOpenFailed: (missing) => 'Could not open the image in the viewer' + (missing ? ' · install xdg-utils' : ''),
97
+ shortcutUnclosed: (file) => `Unclosed Hopdeck block in ${file}`,
68
98
  imgNoPrev: 'This format cannot be previewed', imgHint: '← → browse o open in viewer esc close', imgFolder: 'Images opened in the viewer',
69
99
  more: (n) => `show ${n} more…`, busyRename: 'Close the conversation before renaming it', renameLbl: 'name',
100
+ copyNoTool: (wayland) => `Could not copy. Try running sudo apt install ${wayland ? 'wl-clipboard' : 'xclip'}`,
101
+ copyFailed: 'Could not copy to the clipboard.',
70
102
  copied: (n) => `Copied (${n} chars)`, archMsg: 'Archived (H to show)', unarchMsg: 'Unarchived', qsHint: 'jump to any conversation',
71
103
  prevHint: '⏎ resume this conversation', bar8: 'git', gitNone: 'Pick a project', gitNoRepo: 'This folder is not a git repository', gitMissing: 'git is not installed', gitErr: 'Could not read the repository', gitClean: 'clean', gitDirty: (n) => (n === 1 ? '1 uncommitted change' : `${n} uncommitted changes`), gitMore: (n) => `… and ${n} more`, gitBranches: 'Recent branches', gitActivity: 'Branch activity', gitNoActivity: 'No branch changes', gitFrom: 'from', gitNarrow: (n) => `Terminal too narrow: the git panel needs ${n} columns`, gitOnlyEmbed: 'The git panel is only in the built-in terminal', prevInfo: (a, n) => `${a === 'now' ? 'just now' : a + ' ago'} · last ${n} messages`, kUnfold: 'unfold', kRename: 'rename', kPin: 'pin', kHelp: 'help', kArchive: 'archive', kHide: 'hide', noPrev: 'No messages to show',
72
104
  bar6: 'hide list', bar7: 'show list', deep: 'content', pathPrompt: 'new folder name', mkIn: 'created in', fbTitle: 'Pick a folder', fbHere: 'Open chat here', fbNew: 'New folder here…', fbUp: 'Go up', fbProj: 'project', fbHint: '⏎ enter · ␣ open · / find · . hidden', fbDrives: 'This PC', fbRecent: 'recent', hoverMiss: (n) => `[Image #${n}]: not in the history yet`, fbEmpty: 'No subfolders', badId: 'Invalid session id',
@@ -83,8 +115,19 @@ const T = {
83
115
  dcNodeOld: (v) => `Node ${v}: Node 22 or newer is required`, dcNodeOldHint: 'With older versions the mouse does not work on Windows. Update Node: https://nodejs.org',
84
116
  dcHist: (n, p) => `Claude history: ${n} projects in ${p}`, dcNoHist: (p) => `No history found in ${p}`, dcNoHistHint: 'Use Claude Code once, or set CLAUDE_CONFIG_DIR.',
85
117
  dcClaude: (p) => `claude found: ${p}`, dcNoClaude: '"claude" not found in PATH', dcInstallWin: 'Install it: irm https://claude.ai/install.ps1 | iex', dcInstallUnix: 'Install it: curl -fsSL https://claude.ai/install.sh | bash',
86
- dcTmux: 'tmux available → split view with tmux', dcEmbed: 'Embedded terminal available (node-pty + xterm) → split view',
87
- dcNone: 'No tmux or embedded terminal → full-screen view', dcNoneWin: 'Run npm install inside the package folder.', dcNoneUnix: 'Install tmux (brew install tmux / sudo apt install tmux).',
118
+ dcTmux: 'Split view with tmux', dcEmbed: 'Embedded split view (node-pty + xterm)',
119
+ dcTmuxOpt: 'tmux available with HOPDECK_TMUX=1', dcTmuxOld: 'The tmux split view requires tmux 3.1 or newer.',
120
+ dcNone: 'Full-screen view',
121
+ tmuxNested: 'Hopdeck is already inside tmux. Using the embedded view.',
122
+ tmuxNestedFull: 'Hopdeck is already inside tmux. Using the full-screen view.',
123
+ tmuxStartFailed: (err) => `Could not start the tmux session (${err}).`,
124
+ tmuxAttachFailed: (err) => `Could not attach to the tmux session (${err}).`,
125
+ dcPtyHelper: 'node-pty spawn-helper is executable', dcPtyHelperBad: 'node-pty spawn-helper is missing or lacks execute permission',
126
+ ptyChmod: (file) => `Check node-pty spawn-helper permissions. Run chmod +x ${file}`,
127
+ ptyGeneric: 'Check that node-pty spawn-helper exists and has execute permission (chmod +x).',
128
+ winBadArgs: 'The command line contains characters cmd.exe cannot handle.',
129
+ winUnsupported: (bin) => `Windows cannot launch this CLI file: ${bin}. Use an .exe, .com, .cmd, or .bat file.`,
130
+ dcPolicy: (policy) => `PowerShell execution policy is ${policy}. The Hopdeck profile shortcut may fail to load.`, dcPolicyHint: 'Set-ExecutionPolicy -Scope CurrentUser RemoteSigned',
88
131
  dcShort: 'Shortcut installed: typing "claude" opens Hopdeck', dcNoShort: 'Shortcut not installed', dcNoShortHint: 'Run: hopdeck shortcut on', dcNoCmdHint: 'First create the command (npm install -g hopdeck, or npm link if you cloned the repo), then run: hopdeck shortcut on', dcPrefs: (a, b) => `Preferences: ${a} · cache: ${b}`, bakMsg: (f) => `Backup of your profile: ${f}`,
89
132
  wtOk: 'Windows Terminal: Ctrl+V is remapped (images can be pasted)', wtBad: 'Windows Terminal: Ctrl+V only pastes text, not images', wtUnknown: 'Windows Terminal: could not read its settings.json to check Ctrl+V',
90
133
  wtHint: 'To paste images with Ctrl+V add to "actions" in settings.json:\n { "command": { "action": "sendInput", "input": "\\u001bv" }, "keys": "ctrl+v" }\n (text can still be pasted with Ctrl+Shift+V). No-config alternative: Alt+V.',
@@ -100,12 +143,24 @@ const T = {
100
143
  searchPh: 'search conversation or project…', found: (n) => `${n} ${n === 1 ? 'result' : 'results'}`, noRes: (q) => `No results for “${q}”`,
101
144
  searchingContent: 'Searching inside the conversations…', tryContent: 'Press Tab to also search inside the content', inContent: 'in content', kClear: 'clear', kEdit: 'edit', kEsc: 'exit',
102
145
  inside: 'You are already inside Hopdeck (F1 jumps to the project list).',
146
+ setupChoose: 'What would you like to use with Hopdeck?', setupChoices: '[1] Claude Code [2] Codex [Esc] quit',
147
+ setupMissing: (name) => `${name} is not installed yet.`,
148
+ setupInstallInfo: 'Hopdeck can download and run the official installer for your account. Internet access is required.',
149
+ setupSource: (url) => `Source: ${url}`, setupInstallKeys: '[Enter] Install now [Esc] quit',
150
+ setupInstalling: (name) => `Installing ${name}…`, setupInstalled: (name) => `${name} is installed and ready.`,
151
+ setupFailed: (name) => `Could not set up ${name}.`, setupRetryKeys: '[r] Retry [Enter/Esc] quit',
152
+ setupCancelled: 'Installation cancelled. Open Hopdeck again to try later.',
153
+ setupUnavailable: (name, id) => `${name} is unavailable. Open hopdeck --provider ${id} in an interactive terminal to install it.`,
154
+ setupLoginInfo: (name) => `Sign in with ${name}. The official CLI manages your account and authentication.`,
155
+ setupLoginKeys: '[Enter] Sign in [m] Later [Esc] quit', setupLoginDone: 'Signed in. Continuing to your projects…',
156
+ setupLoginFailed: 'Sign-in did not finish. You can retry or continue later.',
103
157
  },
104
158
  }[LANG];
105
159
 
106
160
  // Product-specific copy follows the selected CLI; interface text remains shared.
107
161
  if (require('./provider').isCodex) {
108
162
  for (const [key, value] of Object.entries(T)) {
163
+ if (key.startsWith('setup')) continue;
109
164
  const adapt = (text) => typeof text === 'string' ? text.replace(/Claude Code/g, 'Codex CLI').replace(/Claude/g, 'Codex').replace(/claude/g, 'codex') : text;
110
165
  if (typeof value === 'string') T[key] = adapt(value);
111
166
  else if (typeof value === 'function') T[key] = (...args) => adapt(value(...args));
@@ -0,0 +1,76 @@
1
+ 'use strict';
2
+
3
+ const { Worker, isMainThread, parentPort, workerData } = require('node:worker_threads');
4
+ const { decodeImageAsync, fitSize, scaleBox, halfBlocks } = require('./images');
5
+ const { encodeSixel } = require('./sixel');
6
+
7
+ async function prepare({ img, decoded, layout }) {
8
+ const d = decoded || await decodeImageAsync(img);
9
+ if (!d || !layout) return d ? { decoded: d } : null;
10
+ const { maxW, maxH, cw, ch } = layout;
11
+ let tw, th, iw, ih;
12
+ if (cw && ch) {
13
+ const k = Math.min(maxW * cw / d.w, maxH * ch / d.h, 3);
14
+ iw = Math.max(1, Math.min(maxW, Math.round(d.w * k / cw)));
15
+ ih = Math.max(1, Math.min(maxH, Math.round(d.h * k / ch)));
16
+ tw = iw * cw; th = ih * ch;
17
+ } else ({ tw, th } = fitSize(d.w, d.h, maxW, maxH));
18
+ const rgb = scaleBox(d.rgba, d.w, d.h, tw, th);
19
+ return { decoded: d, tw, iw, ih, display: iw ? encodeSixel(rgb, tw, th) : halfBlocks(rgb, tw, th) };
20
+ }
21
+
22
+ if (!isMainThread && workerData?.imageWorker) {
23
+ parentPort.on('message', async (input) => {
24
+ const result = await prepare(input).catch(() => null);
25
+ parentPort.postMessage(result, result ? [result.decoded.rgba.buffer] : []);
26
+ });
27
+ }
28
+
29
+ function createImageWorker({ makeWorker = () => new Worker(__filename, { workerData: { imageWorker: true } }) } = {}) {
30
+ const queue = [];
31
+ let worker, running, fallback = false, closed = false;
32
+ function finish(job, result) {
33
+ if (running !== job) return;
34
+ running = null; job.resolve(!closed && job.current() ? result : null); pump();
35
+ }
36
+ function runInThread(job) {
37
+ setImmediate(async () => finish(job, !closed && job.current() && job.input.decoded?.rgba.byteLength !== 0 ? await prepare(job.input).catch(() => null) : null));
38
+ }
39
+ function pump() {
40
+ if (running || closed) return;
41
+ while (queue.length && !queue[0].current()) queue.shift().resolve(null);
42
+ if (!queue.length) { worker?.unref(); return; }
43
+ const job = running = queue.shift();
44
+ if (!worker && !fallback) {
45
+ try {
46
+ const w = worker = makeWorker();
47
+ const failed = () => {
48
+ if (worker !== w) return;
49
+ worker = null; fallback = true; void w.terminate();
50
+ if (running) runInThread(running);
51
+ };
52
+ w.on('message', (result) => { if (worker === w && running) finish(running, result); });
53
+ w.on('error', failed); w.on('exit', failed);
54
+ } catch { fallback = true; }
55
+ }
56
+ if (worker) {
57
+ worker.ref();
58
+ try { worker.postMessage(job.input, job.input.decoded ? [job.input.decoded.rgba.buffer] : []); }
59
+ catch { finish(job, null); }
60
+ } else runInThread(job);
61
+ }
62
+ return {
63
+ request: (input, current = () => true) => new Promise((resolve) => {
64
+ if (closed) return resolve(null);
65
+ queue.push({ input, current, resolve }); pump();
66
+ }),
67
+ close: () => {
68
+ closed = true;
69
+ for (const job of queue.splice(0)) job.resolve(null);
70
+ if (running) finish(running, null);
71
+ if (worker) { const w = worker; worker = null; return w.terminate(); }
72
+ },
73
+ };
74
+ }
75
+
76
+ module.exports = { createImageWorker };