hopdeck 0.0.0-stage → 1.2.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/CHANGELOG.md +37 -0
- package/LICENSE +21 -0
- package/README.en.md +223 -0
- package/README.md +222 -2
- package/SECURITY.md +22 -0
- package/THIRD_PARTY_NOTICES.md +17 -0
- package/bin/hopdeck.js +1903 -0
- package/lib/history.js +127 -0
- package/lib/i18n.js +78 -0
- package/lib/images.js +166 -0
- package/lib/keys.js +47 -0
- package/lib/style.js +62 -0
- package/lib/text.js +43 -0
- package/lib/windows-terminal.js +41 -0
- package/package.json +52 -4
package/bin/hopdeck.js
ADDED
|
@@ -0,0 +1,1903 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
/**
|
|
4
|
+
* Hopdeck
|
|
5
|
+
* Selector visual de proyectos y sesiones para Claude Code.
|
|
6
|
+
* Cero dependencias · arranque instantáneo.
|
|
7
|
+
*/
|
|
8
|
+
const fs = require('fs');
|
|
9
|
+
const os = require('os');
|
|
10
|
+
const path = require('path');
|
|
11
|
+
const cp = require('child_process');
|
|
12
|
+
const readline = require('readline');
|
|
13
|
+
|
|
14
|
+
const { LANG, T } = require('../lib/i18n');
|
|
15
|
+
const { TRUE, NOCOL, LIGHT, fg, bg, R, C, cw, strW, fit, clean } = require('../lib/style');
|
|
16
|
+
const { baseName, tidy, home, shortPath, fuzzy, wrapText } = require('../lib/text');
|
|
17
|
+
const hist = require('../lib/history');
|
|
18
|
+
const { CONFIG_DIR, CACHE_FILE, textOf, isType, cacheLoad, cacheSave, readSession, decodeDir, projectDirs, buildProject, beginScan, endScan } = hist;
|
|
19
|
+
const images = require('../lib/images');
|
|
20
|
+
const { collectImages, decodePNG, decodeImage, scaleBox, fitSize, halfBlocks } = images;
|
|
21
|
+
const { parseKeys, KEYMAP, printable, editBuf, normalizeKeys } = require('../lib/keys');
|
|
22
|
+
const { stripJsonc, wtCtrlV, wtSettingsFile } = require('../lib/windows-terminal');
|
|
23
|
+
|
|
24
|
+
let VERSION = '0.0.0';
|
|
25
|
+
try { VERSION = require('../package.json').version; } catch { /* sin package.json */ }
|
|
26
|
+
const WIN = process.platform === 'win32';
|
|
27
|
+
// Preferencias propias: proyectos fijados/ocultos, ancho del panel, ratón.
|
|
28
|
+
const CFG_FILE = process.env.HOPDECK_CONFIG || path.join(os.homedir(), '.hopdeck.json');
|
|
29
|
+
const CFG = { pinned: [], hidden: [], archived: [], sidebar: 0, mouse: true, notify: true, last: null };
|
|
30
|
+
const saveCfg = () => { try { fs.writeFileSync(CFG_FILE, JSON.stringify(CFG, null, 2), { mode: 0o600 }); } catch { /* solo lectura */ } };
|
|
31
|
+
try { Object.assign(CFG, JSON.parse(fs.readFileSync(CFG_FILE, 'utf8'))); } catch { /* primera vez */ }
|
|
32
|
+
|
|
33
|
+
// ───────────────────────── i18n ─────────────────────────
|
|
34
|
+
|
|
35
|
+
// ───────────────────────── estilo ─────────────────────────
|
|
36
|
+
// ───────────────────────── datos ─────────────────────────
|
|
37
|
+
|
|
38
|
+
function sortProjects(list) {
|
|
39
|
+
return list.sort((a, b) => (b.pinned - a.pinned) || (b.isCwd - a.isCwd) || (b.mtime - a.mtime));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function finishScan(projects) {
|
|
43
|
+
endScan();
|
|
44
|
+
const cur = process.cwd();
|
|
45
|
+
const have = (d) => projects.some((p) => p.cwd === d);
|
|
46
|
+
if (!have(cur)) projects.push({ key: '__cwd', cwd: cur, name: baseName(cur), sessions: [], mtime: Date.now() });
|
|
47
|
+
// carpetas abiertas desde el selector y chats vivos que aún no tienen historial: se muestran igualmente
|
|
48
|
+
for (const x of Array.isArray(CFG.recent) ? CFG.recent : []) {
|
|
49
|
+
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 });
|
|
50
|
+
}
|
|
51
|
+
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() });
|
|
52
|
+
linkChats(projects);
|
|
53
|
+
for (const p of projects) {
|
|
54
|
+
p.isCwd = p.cwd === cur;
|
|
55
|
+
p.pinned = CFG.pinned.includes(p.cwd) ? 1 : 0;
|
|
56
|
+
p.hidden = CFG.hidden.includes(p.cwd) && !p.isCwd;
|
|
57
|
+
p.isCwd = p.isCwd ? 1 : 0;
|
|
58
|
+
}
|
|
59
|
+
return sortProjects(projects);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** Un chat nuevo ya escribió su historial: se enlaza con su archivo para que la lista lo muestre como la conversación real. */
|
|
63
|
+
function linkChats(projects) {
|
|
64
|
+
const all = [...E.sessions.values()], pend = all.filter((x) => !x.sid);
|
|
65
|
+
if (!pend.length) return;
|
|
66
|
+
const taken = new Set(all.map((x) => x.sid).filter(Boolean));
|
|
67
|
+
for (const x of pend) {
|
|
68
|
+
if (pend.filter((y) => y.cwd === x.cwd).length !== 1) continue; // varios chats nuevos en la misma carpeta: ambiguo
|
|
69
|
+
const p = projects.find((q) => q.cwd === x.cwd); if (!p) continue;
|
|
70
|
+
const c = p.sessions.filter((q) => q.mtime >= x.t0 - 2000 && !taken.has(q.id) && !E.sessions.has(q.id)).sort((a, b) => b.mtime - a.mtime)[0];
|
|
71
|
+
if (c) { x.sid = c.id; x.title = c.title; taken.add(c.id); }
|
|
72
|
+
}
|
|
73
|
+
embedLive();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function toggleProject(p, field) {
|
|
77
|
+
const list = CFG[field];
|
|
78
|
+
const i = list.indexOf(p.cwd);
|
|
79
|
+
if (i >= 0) list.splice(i, 1); else list.push(p.cwd);
|
|
80
|
+
p[field] = field === 'pinned' ? (i < 0 ? 1 : 0) : i < 0;
|
|
81
|
+
saveCfg(); sortProjects(S.projects);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// 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.
|
|
85
|
+
const BRANCH = new Map();
|
|
86
|
+
function gitBranch(cwd) {
|
|
87
|
+
const now = Date.now(), hit = BRANCH.get(cwd);
|
|
88
|
+
if (hit && now - hit.t < 3000) return hit.v;
|
|
89
|
+
let v = '';
|
|
90
|
+
try {
|
|
91
|
+
const h = fs.readFileSync(path.join(cwd, '.git', 'HEAD'), 'utf8').trim();
|
|
92
|
+
const m = h.match(/^ref: refs\/heads\/(.+)$/);
|
|
93
|
+
v = m ? m[1] : h.slice(0, 7);
|
|
94
|
+
} catch { /* sin git */ }
|
|
95
|
+
BRANCH.set(cwd, { t: now, v });
|
|
96
|
+
return v;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function scan() {
|
|
100
|
+
beginScan();
|
|
101
|
+
return finishScan(projectDirs().map(buildProject).filter(Boolean));
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Igual que scan() pero cede el control al bucle de eventos para poder animar el loader. */
|
|
105
|
+
async function scanAsync(onProgress) {
|
|
106
|
+
const dirs = projectDirs(); const projects = [];
|
|
107
|
+
beginScan();
|
|
108
|
+
for (let i = 0; i < dirs.length; i++) {
|
|
109
|
+
const p = buildProject(dirs[i]); if (p) projects.push(p);
|
|
110
|
+
if (i % 3 === 2) { if (onProgress) onProgress(i + 1, dirs.length); await new Promise((r) => setImmediate(r)); }
|
|
111
|
+
}
|
|
112
|
+
return finishScan(projects);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function ago(ms) {
|
|
116
|
+
const s = Math.max(0, (Date.now() - ms) / 1000);
|
|
117
|
+
if (s < 60) return T.now;
|
|
118
|
+
if (s < 3600) return Math.floor(s / 60) + ' ' + T.min;
|
|
119
|
+
if (s < 86400) return Math.floor(s / 3600) + ' ' + T.h;
|
|
120
|
+
if (s < 86400 * 14) return Math.floor(s / 86400) + ' ' + T.d;
|
|
121
|
+
if (s < 86400 * 60) return Math.floor(s / 604800) + ' ' + T.w;
|
|
122
|
+
return Math.floor(s / 2592000) + ' ' + T.mo;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// ───────────────────────── estado ─────────────────────────
|
|
126
|
+
const S = { 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: '' };
|
|
127
|
+
const SIDEBAR = process.argv.includes('--sidebar');
|
|
128
|
+
let EMBED = false; // vista dividida con terminal embebido (Windows / sin tmux)
|
|
129
|
+
const E = { sessions: new Map(), shown: null, focus: 'left', pend: null, deps: null, mouse: CFG.mouse !== false, hideSide: false, note: null, sel: null, gallery: null, hover: null };
|
|
130
|
+
const SPIN = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
|
131
|
+
let spinT = null, frameN = 0, reloading = false;
|
|
132
|
+
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)));
|
|
133
|
+
function ensureSpin() {
|
|
134
|
+
if (spinT) return;
|
|
135
|
+
spinT = setInterval(() => {
|
|
136
|
+
if (!needsSpin()) { clearInterval(spinT); spinT = null; if (active) render(); return; }
|
|
137
|
+
frameN++; if (active) render();
|
|
138
|
+
}, 90);
|
|
139
|
+
}
|
|
140
|
+
const spin = () => SPIN[frameN % SPIN.length];
|
|
141
|
+
|
|
142
|
+
/** Recarga la lista sin congelar la pantalla; `after` restaura la selección. */
|
|
143
|
+
async function reloadAsync(after, silent) {
|
|
144
|
+
if (reloading) return;
|
|
145
|
+
reloading = true; if (!silent) { S.loading = true; ensureSpin(); if (active) render(); }
|
|
146
|
+
deepPrev = null;
|
|
147
|
+
try { S.projects = await scanAsync(); } finally { reloading = false; if (!silent) S.loading = false; }
|
|
148
|
+
if (after) after();
|
|
149
|
+
if (active) render();
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const clamp = (n, a, b) => Math.max(a, Math.min(b, n));
|
|
153
|
+
|
|
154
|
+
function view() {
|
|
155
|
+
const q = S.query.trim().toLowerCase();
|
|
156
|
+
const base = S.projects.filter((p) => S.showHidden || !p.hidden);
|
|
157
|
+
const vis = (x) => S.showHidden || !CFG.archived.includes(x.id);
|
|
158
|
+
if (!q) return base.map((p) => ({ p, ss: p.sessions.filter(vis) }));
|
|
159
|
+
const hitS = (x) => (x.title + ' ' + x.first).toLowerCase().includes(q) || !!(S.deepHits && S.deepHits.has(x.id));
|
|
160
|
+
const out = [];
|
|
161
|
+
for (const p of base) {
|
|
162
|
+
const hit = (p.name + ' ' + p.cwd).toLowerCase().includes(q);
|
|
163
|
+
const ss = (hit ? p.sessions : p.sessions.filter(hitS)).filter(vis);
|
|
164
|
+
if (hit || ss.length) out.push({ p, ss });
|
|
165
|
+
}
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// búsqueda dentro del texto de las conversaciones (Tab en el modo búsqueda)
|
|
170
|
+
let deepT = null, deepTok = 0, deepPrev = null;
|
|
171
|
+
async function fileHas(file, q) {
|
|
172
|
+
let fh; try { fh = await fs.promises.open(file, 'r'); } catch { return false; }
|
|
173
|
+
try {
|
|
174
|
+
const st = await fh.stat(); if (st.size > 40 * 1024 * 1024) return false;
|
|
175
|
+
const buf = Buffer.alloc(256 * 1024); let pos = 0, carry = '';
|
|
176
|
+
while (pos < st.size) {
|
|
177
|
+
const { bytesRead } = await fh.read(buf, 0, buf.length, pos); if (!bytesRead) break;
|
|
178
|
+
const text = carry + buf.toString('utf8', 0, bytesRead).toLowerCase();
|
|
179
|
+
if (text.includes(q)) return true;
|
|
180
|
+
carry = text.slice(-q.length); pos += bytesRead;
|
|
181
|
+
}
|
|
182
|
+
return false;
|
|
183
|
+
} finally { await fh.close(); }
|
|
184
|
+
}
|
|
185
|
+
function queryChanged() {
|
|
186
|
+
clearTimeout(deepT); deepTok++; S.deepHits = null;
|
|
187
|
+
if (!S.deep || !S.query.trim()) deepPrev = null;
|
|
188
|
+
if (!S.deep || S.query.trim().length < 3) { if (!reloading) S.loading = false; return; }
|
|
189
|
+
const tok = deepTok; S.loading = true; ensureSpin();
|
|
190
|
+
deepT = setTimeout(async () => {
|
|
191
|
+
const q = S.query.trim().toLowerCase(), hits = new Set();
|
|
192
|
+
const all = S.projects.flatMap((p) => p.sessions);
|
|
193
|
+
// si la búsqueda anterior era un prefijo de esta, solo hay que mirar sus aciertos
|
|
194
|
+
const list = deepPrev && q.startsWith(deepPrev.q) ? all.filter((x) => deepPrev.hits.has(x.id)) : all;
|
|
195
|
+
let idx = 0;
|
|
196
|
+
await Promise.all(Array.from({ length: 6 }, async () => {
|
|
197
|
+
while (idx < list.length) {
|
|
198
|
+
if (tok !== deepTok) return;
|
|
199
|
+
const x = list[idx++]; if (x.file && await fileHas(x.file, q)) hits.add(x.id);
|
|
200
|
+
}
|
|
201
|
+
}));
|
|
202
|
+
if (tok === deepTok) { S.deepHits = hits; deepPrev = { q, hits }; S.loading = false; if (active) render(); }
|
|
203
|
+
}, 250);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const scroll = (off, sel, h) => clamp(off, sel - h + 1, sel);
|
|
207
|
+
|
|
208
|
+
// ───────────────────────── render ─────────────────────────
|
|
209
|
+
function frame(cols, rows) {
|
|
210
|
+
const W = cols, H = rows;
|
|
211
|
+
if (W < 60 || H < 12) return [fit([[T.small, C.warn]], W)];
|
|
212
|
+
const V = view();
|
|
213
|
+
S.pi = clamp(S.pi, 0, Math.max(0, V.length - 1));
|
|
214
|
+
const cur = V[S.pi];
|
|
215
|
+
const ents = cur ? [{ neu: true }, ...cur.ss] : [];
|
|
216
|
+
S.si = clamp(S.si, 0, Math.max(0, ents.length - 1));
|
|
217
|
+
|
|
218
|
+
const inner = W - 2;
|
|
219
|
+
const lw = clamp(Math.floor(inner * 0.4), 26, 46);
|
|
220
|
+
const rw = inner - lw - 1;
|
|
221
|
+
const bodyH = H - 6;
|
|
222
|
+
const listH = bodyH - 3;
|
|
223
|
+
const B = (s) => C.faint + s + R;
|
|
224
|
+
const lines = [];
|
|
225
|
+
|
|
226
|
+
// borde superior
|
|
227
|
+
const title = ' » Hopdeck ';
|
|
228
|
+
const ver = ` v${VERSION} `;
|
|
229
|
+
const fill = Math.max(0, inner - 1 - strW(title) - strW(ver));
|
|
230
|
+
lines.push(B('╭─') + C.brand + C.bold + ' » Hop' + R + C.text + C.bold + 'deck ' + R + B('─'.repeat(fill)) + C.dim + ver + R + B('╮'));
|
|
231
|
+
|
|
232
|
+
// cabeceras
|
|
233
|
+
const hl = S.focus === 0 ? C.accent + C.bold : C.dim;
|
|
234
|
+
const hr = S.focus === 1 ? C.accent + C.bold : C.dim;
|
|
235
|
+
lines.push(B('│') + fit([[' ' + T.projects, hl], [' ' + V.length, C.dim], [S.loading ? ' ' + spin() : '', C.accent]], lw) + B('│') +
|
|
236
|
+
fit([[' ' + T.sessions, hr], [cur ? ' · ' + cur.p.name : '', C.dim]], rw) + B('│'));
|
|
237
|
+
lines.push(B('├' + '─'.repeat(lw) + '┼' + '─'.repeat(rw) + '┤'));
|
|
238
|
+
|
|
239
|
+
// cuerpo
|
|
240
|
+
S.poff = scroll(S.poff, S.pi, bodyH);
|
|
241
|
+
S.soff = scroll(S.soff, S.si, listH);
|
|
242
|
+
for (let r = 0; r < bodyH; r++) {
|
|
243
|
+
// izquierda: proyectos
|
|
244
|
+
let left;
|
|
245
|
+
const pv = V[S.poff + r];
|
|
246
|
+
if (pv) {
|
|
247
|
+
const sel = S.poff + r === S.pi;
|
|
248
|
+
const base = sel ? (S.focus === 0 ? C.selOn : C.selOff) : '';
|
|
249
|
+
const mark = sel ? (S.focus === 0 ? '▌' : '▎') : ' ';
|
|
250
|
+
const nameW = lw - 14;
|
|
251
|
+
const cnt = String(pv.p.sessions.length || '·').padStart(3);
|
|
252
|
+
const when = pv.p.sessions.length ? ago(pv.p.mtime).padStart(7) : ' '.repeat(7);
|
|
253
|
+
left = fit([
|
|
254
|
+
[mark + ' ', C.accent],
|
|
255
|
+
[(pv.p.pinned ? '★ ' : '') + (pv.p.isCwd ? '● ' : '') + pv.p.name, sel ? C.text + C.bold : pv.p.hidden ? C.dim : (pv.p.isCwd ? C.ok : C.text)],
|
|
256
|
+
], nameW + 2, base) + fit([[' ' + cnt, sel ? C.accent : C.dim], [' ' + when, C.dim]], lw - nameW - 2, base);
|
|
257
|
+
} else if (r === 0 && !V.length) {
|
|
258
|
+
left = fit([[' ' + T.noMatch, C.dim]], lw);
|
|
259
|
+
} else left = ' '.repeat(lw);
|
|
260
|
+
|
|
261
|
+
// derecha: sesiones (y detalle en las últimas 3 filas)
|
|
262
|
+
let right;
|
|
263
|
+
if (r < listH) {
|
|
264
|
+
const e = ents[S.soff + r];
|
|
265
|
+
if (e) {
|
|
266
|
+
const sel = S.soff + r === S.si && S.focus === 1;
|
|
267
|
+
const base = sel ? C.selOn : '';
|
|
268
|
+
const mark = sel ? '▌ ' : ' ';
|
|
269
|
+
if (e.neu) {
|
|
270
|
+
right = fit([[mark, C.accent], ['+ ', C.accent], [T.newChat, sel ? C.accent + C.bold : C.accent]], rw, base);
|
|
271
|
+
} else {
|
|
272
|
+
const when = ago(e.mtime);
|
|
273
|
+
const tw = rw - 2 - when.length - 2;
|
|
274
|
+
right = fit([[mark, C.accent], [e.title, sel ? C.text + C.bold : C.text],
|
|
275
|
+
[e.first && e.first !== e.title ? ' ' + e.first : '', C.dim],
|
|
276
|
+
[e.dup ? ' #' + e.id.slice(0, 4) : '', C.accent]], tw + 2, base) +
|
|
277
|
+
fit([[' ' + when, C.dim]], rw - tw - 2, base);
|
|
278
|
+
}
|
|
279
|
+
} else right = ' '.repeat(rw);
|
|
280
|
+
} else if (r === listH) {
|
|
281
|
+
right = C.faint + '┄'.repeat(rw) + R;
|
|
282
|
+
} else if (r === listH + 1) {
|
|
283
|
+
const missing = cur && !fs.existsSync(cur.p.cwd);
|
|
284
|
+
right = fit([[' ⌂ ', C.dim], [shortPath(cur ? cur.p.cwd : ''), missing ? C.warn : C.dim],
|
|
285
|
+
[cur && cur.p.isCwd ? ' · ' + T.current : '', C.ok]], rw);
|
|
286
|
+
} else {
|
|
287
|
+
const e = ents[S.si];
|
|
288
|
+
if (e && !e.neu) {
|
|
289
|
+
right = fit([[' ' + (e.first && e.first !== e.title ? '“' + e.first + '”' : e.id.slice(0, 8)), C.ital + C.dim]], rw);
|
|
290
|
+
} else right = fit([[cur ? ' ' + T.sess(cur.p.sessions.length) : '', C.dim]], rw);
|
|
291
|
+
}
|
|
292
|
+
lines.push(B('│') + left + B('│') + right + B('│'));
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// pie
|
|
296
|
+
lines.push(B('├' + '─'.repeat(lw) + '┴' + '─'.repeat(rw) + '┤'));
|
|
297
|
+
let foot;
|
|
298
|
+
if (S.flash) foot = fit([[' ' + S.flash, C.warn]], inner);
|
|
299
|
+
else if (S.searching || S.query) {
|
|
300
|
+
foot = fit([[' / ', C.accent], [S.query, C.text], [S.searching ? '▏' : '', C.accent],
|
|
301
|
+
[' Tab ' + (S.deep ? '◉ ' : '○ ') + T.deep, S.deep ? C.ok : C.dim], [' ' + T.searchHint, C.dim]], inner);
|
|
302
|
+
} else {
|
|
303
|
+
const k = T.k;
|
|
304
|
+
const hints = S.focus === 0
|
|
305
|
+
? [['↑↓', k.move], ['→', k.open], ['n', k.neu], ['/', k.find], ['q', k.quit]]
|
|
306
|
+
: [['↑↓', k.move], ['⏎', k.resume], ['←', k.back], ['n', k.neu], ['/', k.find], ['q', k.quit]];
|
|
307
|
+
const segs = [[' ', '']];
|
|
308
|
+
for (const [key, desc] of hints) segs.push([key, C.accent], [' ' + desc + ' ', C.dim]);
|
|
309
|
+
foot = fit(segs, inner);
|
|
310
|
+
}
|
|
311
|
+
lines.push(B('│') + foot + B('│'));
|
|
312
|
+
lines.push(B('╰' + '─'.repeat(inner) + '╯'));
|
|
313
|
+
return lines;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
// ───────────────────────── utilidades de interfaz ─────────────────────────
|
|
318
|
+
// ───────────────────────── modo panel lateral (tmux) ─────────────────────────
|
|
319
|
+
const LIMIT = 8; // sesiones visibles por proyecto antes de "mostrar N más…"
|
|
320
|
+
function flatList() {
|
|
321
|
+
const q = S.query.trim(); const out = [];
|
|
322
|
+
for (const { p, ss } of view()) {
|
|
323
|
+
const open = p.key === S.open || (!!q && ss.length < p.sessions.length);
|
|
324
|
+
out.push({ t: 'p', p, open });
|
|
325
|
+
if (open) {
|
|
326
|
+
out.push({ t: 'n', p });
|
|
327
|
+
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
|
|
328
|
+
const lim = q || S.more.has(p.key) ? ss.length : LIMIT;
|
|
329
|
+
for (const s of ss.slice(0, lim)) out.push({ t: 's', p, s });
|
|
330
|
+
if (ss.length > lim) out.push({ t: 'm', p, n: ss.length - lim });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
return out;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const chatByKey = (id) => E.sessions.get(id) || [...E.sessions.values()].find((x) => x.sid === id);
|
|
337
|
+
const chatKeyOf = (id) => (E.sessions.has(id) ? id : ([...E.sessions].find(([, x]) => x.sid === id) || [])[0]);
|
|
338
|
+
|
|
339
|
+
function chatMark(id) {
|
|
340
|
+
if (!S.live.has(id)) return [' ', ''];
|
|
341
|
+
const x = EMBED && chatByKey(id);
|
|
342
|
+
if (x && x.working) return [spin() + ' ', C.accent];
|
|
343
|
+
if (x && x.unseen) return ['✔ ', C.warn];
|
|
344
|
+
return ['● ', C.ok];
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const tailFit = (t, n) => (strW(t) > n && n > 3 ? '…' + t.slice(t.length - (n - 1)) : t);
|
|
348
|
+
|
|
349
|
+
function frameTree(W, H) {
|
|
350
|
+
if (H < 8 || W < 24) return [fit([[T.small, C.warn]], W)];
|
|
351
|
+
const L = flatList();
|
|
352
|
+
S.c = clamp(S.c, 0, Math.max(0, L.length - 1));
|
|
353
|
+
const bodyH = H - 5;
|
|
354
|
+
S.coff = scroll(S.coff, S.c, bodyH);
|
|
355
|
+
const lines = [];
|
|
356
|
+
lines.push(fit([[' » ', C.brand], ['Hop', C.brand + C.bold], ['deck', C.text + C.bold], [' ' + S.projects.length, C.dim], [S.loading ? ' ' + spin() : '', C.accent]], W));
|
|
357
|
+
lines.push(C.faint + '─'.repeat(W) + R);
|
|
358
|
+
const qsList = S.qs ? qsItems() : null;
|
|
359
|
+
const fbList = S.fb && !S.qs ? fbRows() : null;
|
|
360
|
+
if (fbList) { S.fb.i = clamp(S.fb.i, 0, Math.max(0, fbList.length - 1)); S.fb.off = scroll(S.fb.off, S.fb.i, bodyH); lines[0] = fit([[' » ' + T.fbTitle, C.accent + C.bold]], W); }
|
|
361
|
+
if (qsList) { S.qs.i = clamp(S.qs.i, 0, Math.max(0, qsList.length - 1)); S.qs.off = scroll(S.qs.off || 0, S.qs.i, bodyH); }
|
|
362
|
+
for (let r = 0; r < bodyH; r++) {
|
|
363
|
+
if (qsList) {
|
|
364
|
+
const it = qsList[S.qs.off + r];
|
|
365
|
+
if (!it) { lines.push(' '.repeat(W)); continue; }
|
|
366
|
+
const sel = S.qs.off + r === S.qs.i, base = sel ? C.selOn : '';
|
|
367
|
+
lines.push(fit([[sel ? '▌ ' : ' ', C.accent], [it.s.title, sel ? C.text + C.bold : C.text], [' ' + it.p.name, C.dim]], W - 8, base) +
|
|
368
|
+
fit([[' ' + ago(it.s.mtime).padStart(6), C.dim], [' ', '']], 8, base)); // el espacio evita que el nombre del proyecto se pegue a la hora
|
|
369
|
+
continue;
|
|
370
|
+
}
|
|
371
|
+
if (fbList) {
|
|
372
|
+
const it = fbList[S.fb.off + r];
|
|
373
|
+
if (!it) { lines.push(' '.repeat(W)); continue; }
|
|
374
|
+
const sel = S.fb.off + r === S.fb.i, base = sel ? C.selOn : '', mark = [sel ? '▌' : ' ', C.accent];
|
|
375
|
+
if (it.k === 'dir') {
|
|
376
|
+
const full = fbPath(S.fb, it.n), has = S.projects.some((p) => p.cwd === full && p.sessions.length);
|
|
377
|
+
lines.push(fit([mark, [S.fb.dir === '' ? ' ▪ ' : ' ▸ ', C.dim], [it.n, sel ? C.text + C.bold : C.text]], W - 11, base) + fit([[has ? T.fbProj : '', C.dim], [' ', '']], 11, base));
|
|
378
|
+
} else if (it.k === 'recent') {
|
|
379
|
+
lines.push(fit([mark, [' ↻ ', C.accent], [baseName(it.dir), sel ? C.text + C.bold : C.text]], W - 11, base) + fit([[T.fbRecent, C.dim], [' ', '']], 11, base));
|
|
380
|
+
} else if (it.k === 'none') {
|
|
381
|
+
lines.push(fit([mark, [' ', ''], [T.fbEmpty, C.dim]], W, base));
|
|
382
|
+
} else {
|
|
383
|
+
const lab = it.k === 'here' ? ['✔ ', T.fbHere] : it.k === 'new' ? ['+ ', T.fbNew] : ['↑ ', T.fbUp];
|
|
384
|
+
lines.push(fit([mark, [' ' + lab[0], C.accent], [lab[1], sel ? C.accent + C.bold : C.accent]], W, base));
|
|
385
|
+
}
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
if (S.help) { const t = T.help[r]; lines.push(fit([[t ? ' ' + t : '', r === 0 ? C.accent + C.bold : C.dim]], W)); continue; }
|
|
389
|
+
const e = L[S.coff + r];
|
|
390
|
+
if (!e) { lines.push(' '.repeat(W)); continue; }
|
|
391
|
+
const sel = S.coff + r === S.c;
|
|
392
|
+
const base = sel ? (EMBED && E.focus === 'right' ? C.selOff : C.selOn) : '';
|
|
393
|
+
const mark = [sel ? '▌' : ' ', C.accent];
|
|
394
|
+
if (e.t === 'p') {
|
|
395
|
+
const right = (e.p.sessions.length ? String(e.p.sessions.length).padStart(3) + ' ' + ago(e.p.mtime).padStart(6) : '');
|
|
396
|
+
lines.push(fit([mark, [e.open ? ' ▾ ' : ' ▸ ', C.dim],
|
|
397
|
+
[(e.p.pinned ? '★ ' : '') + (e.p.isCwd ? '● ' : '') + e.p.name, sel ? C.text + C.bold : e.p.hidden ? C.dim : (e.p.isCwd ? C.ok : C.text)]], W - 11, base) +
|
|
398
|
+
fit([[right, C.dim]], 11, base));
|
|
399
|
+
} else if (e.t === 'm') {
|
|
400
|
+
lines.push(fit([mark, [' ', ''], [T.more(e.n), sel ? C.text : C.dim]], W, base));
|
|
401
|
+
} else if (e.t === 'l') {
|
|
402
|
+
const [mk, mc] = chatMark(e.key);
|
|
403
|
+
lines.push(fit([mark, [' ', ''], [mk, mc], [T.newChat + ' …', sel ? C.text + C.bold : C.text]], W - 13, base) +
|
|
404
|
+
fit([[''.padEnd(6), ''], [ago(e.x.t0).padStart(6), C.dim], [' ', '']], 13, base));
|
|
405
|
+
} else if (e.t === 'n') {
|
|
406
|
+
lines.push(fit([mark, [' + ', C.accent], [T.newChat, sel ? C.accent + C.bold : C.accent]], W, base));
|
|
407
|
+
} else {
|
|
408
|
+
const [mk, mc] = chatMark(e.s.id);
|
|
409
|
+
const arch = CFG.archived.includes(e.s.id), tag = e.s.dup ? '#' + e.s.id.slice(0, 4) : '';
|
|
410
|
+
lines.push(fit([mark, [' ', ''], [mk, mc], [e.s.title, sel ? C.text + C.bold : arch ? C.dim : C.text]], W - 13, base) +
|
|
411
|
+
fit([[tag.padEnd(6), C.accent], [ago(e.s.mtime).padStart(6), C.dim], [' ', '']], 13, base));
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
const cur = L[S.c];
|
|
415
|
+
lines.push(C.faint + '─'.repeat(W) + R);
|
|
416
|
+
const br = cur && !S.flash ? gitBranch(cur.p.cwd) : '';
|
|
417
|
+
const note = EMBED && E.note;
|
|
418
|
+
lines.push(fit(S.flash ? [[' ' + S.flash, C.warn]] : 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]]
|
|
419
|
+
: [[br ? ' ⎇ ' + br + ' ' : '', C.accent], [cur ? (br ? '' : ' ⌂ ') + shortPath(cur.p.cwd) : '', C.dim]], W));
|
|
420
|
+
if (S.qs) {
|
|
421
|
+
lines.push(fit([[' ⌕ ', C.accent], ...withCursor(S.qs.q, S.qs.pc), [S.qs.q ? '' : ' ' + T.qsHint, C.dim]], W));
|
|
422
|
+
} else if (S.prompt !== null) {
|
|
423
|
+
const rn = S.promptKind === 'rename';
|
|
424
|
+
lines.push(fit([[rn ? ' ✎ ' : ' ⌂ ', C.accent], ...withCursor(S.prompt, S.pc), [S.prompt ? '' : ' ' + (rn ? T.renameLbl : T.pathPrompt) + '…', C.dim]], W));
|
|
425
|
+
} else if (S.fb) {
|
|
426
|
+
lines.push(fit(S.fb.filt || S.fb.q ? [[' / ', C.accent], ...withCursor(S.fb.q, S.fb.qp, S.fb.filt)] : [[' ' + T.fbHint, C.dim]], W));
|
|
427
|
+
} else if (S.searching || S.query) {
|
|
428
|
+
lines.push(fit([[' / ', C.accent], ...withCursor(S.query, S.searching ? S.qpos : [...S.query].length, S.searching),
|
|
429
|
+
[' Tab ' + (S.deep ? '◉ ' : '○ ') + T.deep, S.deep ? C.ok : C.dim]], W));
|
|
430
|
+
} else {
|
|
431
|
+
const k = T.k, segs = [[' ', '']];
|
|
432
|
+
for (const [key, desc] of [['⏎', k.open], ['n', k.neu], ['/', k.find], ['?', LANG === 'es' ? 'ayuda' : 'help']]) segs.push([key, C.accent], [' ' + desc + ' ', C.dim]);
|
|
433
|
+
lines.push(fit(segs, W));
|
|
434
|
+
}
|
|
435
|
+
return lines;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
const tmux = (...a) => cp.execFileSync('tmux', a, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
|
|
439
|
+
const sq = (x) => `'${String(x).replace(/'/g, "'\\''")}'`;
|
|
440
|
+
|
|
441
|
+
function chatCmd(bin, args, left) {
|
|
442
|
+
const run = ['env', 'HOPDECK_SKIP=1', 'HOPDECK_INSIDE=1', bin, ...args].map(sq).join(' ');
|
|
443
|
+
const self = [process.execPath, __filename, '--idle'].map(sq).join(' ');
|
|
444
|
+
const win = (t) => `"$(tmux display -p -t ${t} '#{window_id}')"`;
|
|
445
|
+
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; ` +
|
|
446
|
+
`[ ${win('"$TMUX_PANE"')} = ${win(sq(left))} ] && tmux select-pane -t ${sq(left)}; exec env HOPDECK_INSIDE=1 ${self}`;
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
function tmuxPanes() {
|
|
450
|
+
return tmux('list-panes', '-a', '-F', '#{pane_id}\t#{@hopdeck_key}').split('\n').filter(Boolean)
|
|
451
|
+
.map((l) => { const [id, key = ''] = l.split('\t'); return { id, key }; });
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
/** Abre (o trae al frente) una conversación en el panel derecho sin matar las demás. */
|
|
455
|
+
function launchSlot(project, session) {
|
|
456
|
+
if (!fs.existsSync(project.cwd)) { flash(T.missing + ': ' + shortPath(project.cwd)); return; }
|
|
457
|
+
const bin = findClaude();
|
|
458
|
+
if (!bin) { flash(T.noClaude); return; }
|
|
459
|
+
const mine = process.env.TMUX_PANE;
|
|
460
|
+
const key = session ? session.id : 'new-' + Date.now();
|
|
461
|
+
try {
|
|
462
|
+
const panes = tmuxPanes();
|
|
463
|
+
const slot = tmux('list-panes', '-t', mine, '-F', '#{pane_id}').split('\n').find((id) => id && id !== mine);
|
|
464
|
+
let target = session && (panes.find((x) => x.key === key) || {}).id;
|
|
465
|
+
if (!target) {
|
|
466
|
+
const cmd = chatCmd(bin, [...(session ? ['--resume', session.id] : []), ...extraArgs], mine);
|
|
467
|
+
const slotInfo = panes.find((x) => x.id === slot);
|
|
468
|
+
if (slotInfo && !slotInfo.key) { tmux('respawn-pane', '-k', '-t', slot, '-c', project.cwd, cmd); target = slot; }
|
|
469
|
+
else target = tmux('new-window', '-d', '-P', '-F', '#{pane_id}', '-c', project.cwd, cmd);
|
|
470
|
+
tmux('set-option', '-p', '-t', target, '@hopdeck_key', key);
|
|
471
|
+
tmux('set-option', '-p', '-t', target, '@hopdeck_title', project.name + ' › ' + (session ? session.title : T.newChat));
|
|
472
|
+
}
|
|
473
|
+
if (target !== slot) tmux('swap-pane', '-d', '-s', target, '-t', slot);
|
|
474
|
+
tmux('select-pane', '-t', target);
|
|
475
|
+
} catch (e) { flash(String(e.message).split('\n').filter(Boolean).pop() || 'tmux error'); }
|
|
476
|
+
refreshLive();
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function refreshLive() {
|
|
480
|
+
try {
|
|
481
|
+
const live = new Set(tmuxPanes().map((x) => x.key).filter(Boolean));
|
|
482
|
+
const k = [...live].sort().join();
|
|
483
|
+
if (k !== S.liveKey) { S.live = live; S.liveKey = k; render(); }
|
|
484
|
+
} catch { /* sin tmux */ }
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
function reloadKeep() {
|
|
488
|
+
const e = flatList()[S.c];
|
|
489
|
+
return reloadAsync(() => {
|
|
490
|
+
if (!e) return;
|
|
491
|
+
const same = (x) => x.t === e.t && x.p.key === e.p.key && (e.t !== 's' || x.s.id === e.s.id);
|
|
492
|
+
const i = flatList().findIndex(same);
|
|
493
|
+
if (i >= 0) S.c = i;
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
function qsItems() {
|
|
498
|
+
const q = S.qs.q.trim(); const items = [];
|
|
499
|
+
for (const p of S.projects) {
|
|
500
|
+
if (p.hidden && !S.showHidden) continue;
|
|
501
|
+
for (const x of p.sessions) { if (CFG.archived.includes(x.id) && !S.showHidden) continue; items.push({ p, s: x }); }
|
|
502
|
+
}
|
|
503
|
+
if (!q) return items.sort((a, b) => b.s.mtime - a.s.mtime).slice(0, 200);
|
|
504
|
+
return items.map((it) => ({ it, sc: fuzzy(q, it.p.name + ' ' + it.s.title + ' ' + it.s.first) })).filter((x) => x.sc >= 0)
|
|
505
|
+
.sort((a, b) => b.sc - a.sc || b.it.s.mtime - a.it.s.mtime).slice(0, 200).map((x) => x.it);
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function doRename(x, name) {
|
|
509
|
+
name = (name || '').trim();
|
|
510
|
+
if (!x || !name) return;
|
|
511
|
+
if (S.live.has(x.id)) { flash(T.busyRename); return; }
|
|
512
|
+
// Claude Code guarda el título como una línea más del historial
|
|
513
|
+
try { fs.appendFileSync(x.file, JSON.stringify({ type: 'custom-title', customTitle: name, sessionId: x.id }) + '\n'); } catch (e) { flash(String(e.message).split('\n')[0]); return; }
|
|
514
|
+
reloadKeep();
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
function adjustSidebar(d) {
|
|
518
|
+
const cur = EMBED ? embedLayout().SW || 36 : process.stdout.columns || 40;
|
|
519
|
+
CFG.sidebar = clamp(cur + d, 24, 80); saveCfg();
|
|
520
|
+
if (EMBED) return embedResize();
|
|
521
|
+
if (SIDEBAR) { try { tmux('resize-pane', '-t', process.env.TMUX_PANE, '-x', String(CFG.sidebar)); } catch { /* */ } render(); }
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function rememberState() {
|
|
525
|
+
try {
|
|
526
|
+
const e = flatList()[S.c];
|
|
527
|
+
CFG.last = { open: S.open, e: e ? { t: e.t, pk: e.p.key, sid: e.s && e.s.id } : null };
|
|
528
|
+
saveCfg();
|
|
529
|
+
} catch { /* */ }
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
function restoreState() {
|
|
533
|
+
const l = CFG.last; if (!l || !S.projects.some((p) => p.key === l.open)) return;
|
|
534
|
+
S.open = l.open;
|
|
535
|
+
if (l.e) {
|
|
536
|
+
const i = flatList().findIndex((x) => x.t === l.e.t && x.p.key === l.e.pk && (l.e.t !== 's' || x.s.id === l.e.sid));
|
|
537
|
+
if (i >= 0) S.c = i;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
/** Abre una conversación nueva en una carpeta cualquiera (acepta ~ y rutas relativas). */
|
|
542
|
+
/** Abre la caja de texto inferior (nombre de carpeta / renombrar) con el cursor al final. */
|
|
543
|
+
function setPrompt(text, kind) { S.prompt = text; S.promptKind = kind; S.pc = [...text].length; }
|
|
544
|
+
/** Texto con el cursor dibujado en `pos` (para las cajas de entrada). */
|
|
545
|
+
const withCursor = (str, pos, on = true) => { const a = [...str], i = clamp(Number.isFinite(pos) ? pos : a.length, 0, a.length); return [[a.slice(0, i).join(''), C.text], [on ? '▏' : '', C.accent], [a.slice(i).join(''), C.text]]; };
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
/** Carpeta base para nombres sueltos: la que se está viendo en el selector (por defecto ~). */
|
|
549
|
+
const newFolderBase = () => (S.fb && S.fb.dir ? S.fb.dir : os.homedir());
|
|
550
|
+
|
|
551
|
+
// ── Selector de carpetas: se navega con flechas desde ~ y se elige dónde abrir el chat ──
|
|
552
|
+
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']);
|
|
553
|
+
function listDrives() { // Windows: letras de unidad disponibles
|
|
554
|
+
const out = [];
|
|
555
|
+
for (let c = 65; c <= 90; c++) { const r = String.fromCharCode(c) + ':\\'; try { if (fs.existsSync(r)) out.push(r); } catch { /* */ } }
|
|
556
|
+
return out;
|
|
557
|
+
}
|
|
558
|
+
/** Subcarpetas visibles de `dir` (ocultas y carpetas de sistema solo si `hid`). dir === '' → unidades de Windows. */
|
|
559
|
+
function fbNames(dir, hid) {
|
|
560
|
+
if (dir === '') return listDrives();
|
|
561
|
+
try {
|
|
562
|
+
return fs.readdirSync(dir, { withFileTypes: true })
|
|
563
|
+
.filter((d) => {
|
|
564
|
+
if (hid ? false : (d.name.startsWith('.') || FB_SKIP.has(d.name))) return false;
|
|
565
|
+
if (d.isDirectory()) return true;
|
|
566
|
+
if (d.isSymbolicLink()) { try { return fs.statSync(path.join(dir, d.name)).isDirectory(); } catch { return false; } }
|
|
567
|
+
return false;
|
|
568
|
+
})
|
|
569
|
+
.map((d) => d.name).sort((x, y) => x.localeCompare(y));
|
|
570
|
+
} catch { return []; /* sin permiso */ }
|
|
571
|
+
}
|
|
572
|
+
const fbPath = (f, n) => (f.dir === '' ? n : path.join(f.dir, n));
|
|
573
|
+
const fbCanUp = (f) => f.dir !== '' && (path.dirname(f.dir) !== f.dir || WIN);
|
|
574
|
+
function fbOpen(dir, sel) {
|
|
575
|
+
const hid = S.fb ? S.fb.hid : false;
|
|
576
|
+
S.fb = { dir, names: fbNames(dir, hid), i: 0, off: 0, hid, q: '', qp: 0, filt: false };
|
|
577
|
+
const rows = fbRows(), j = sel ? rows.findIndex((r) => r.k === 'dir' && r.n === sel) : -1;
|
|
578
|
+
S.fb.i = j >= 0 ? j : 0;
|
|
579
|
+
}
|
|
580
|
+
function fbRows() {
|
|
581
|
+
const f = S.fb, r = [];
|
|
582
|
+
if (f.dir !== '') r.push({ k: 'here' }, { k: 'new' });
|
|
583
|
+
if (fbCanUp(f)) r.push({ k: 'up' });
|
|
584
|
+
if (f.dir === os.homedir() && !f.q) {
|
|
585
|
+
for (const x of (Array.isArray(CFG.recent) ? CFG.recent : [])) {
|
|
586
|
+
if (r.filter((y) => y.k === 'recent').length >= 5) break;
|
|
587
|
+
if (x && x.dir && x.dir !== f.dir && fs.existsSync(x.dir)) r.push({ k: 'recent', dir: x.dir });
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
const q = f.q.toLowerCase(), ds = f.names.filter((n) => !q || n.toLowerCase().includes(q));
|
|
591
|
+
for (const n of ds) r.push({ k: 'dir', n });
|
|
592
|
+
if (!ds.length && f.dir !== '') r.push({ k: 'none' });
|
|
593
|
+
return r;
|
|
594
|
+
}
|
|
595
|
+
function fbActivate() {
|
|
596
|
+
const f = S.fb, r = fbRows()[f.i]; if (!r || r.k === 'none') return;
|
|
597
|
+
if (r.k === 'here') return openFolder(f.dir);
|
|
598
|
+
if (r.k === 'new') { setPrompt('', 'folder'); return render(); }
|
|
599
|
+
if (r.k === 'recent') return openFolder(r.dir);
|
|
600
|
+
if (r.k === 'up') { const par = path.dirname(f.dir); if (par === f.dir) fbOpen('', f.dir); else fbOpen(par, path.basename(f.dir)); }
|
|
601
|
+
else fbOpen(fbPath(f, r.n));
|
|
602
|
+
render();
|
|
603
|
+
}
|
|
604
|
+
/** Espacio: abrir el chat en la carpeta resaltada (sin entrar en ella). */
|
|
605
|
+
function fbChoose() {
|
|
606
|
+
const f = S.fb, r = fbRows()[f.i]; if (!r || r.k === 'none') return;
|
|
607
|
+
if (r.k === 'dir') return openFolder(fbPath(f, r.n));
|
|
608
|
+
if (r.k === 'up') return openFolder(path.dirname(f.dir));
|
|
609
|
+
return fbActivate();
|
|
610
|
+
}
|
|
611
|
+
function fbUp() { const f = S.fb; if (!fbCanUp(f)) return; const par = path.dirname(f.dir); if (par === f.dir) fbOpen('', f.dir); else fbOpen(par, path.basename(f.dir)); }
|
|
612
|
+
function fbKey(k, raw) {
|
|
613
|
+
const f = S.fb;
|
|
614
|
+
if (f.filt) { // escribiendo un filtro
|
|
615
|
+
const n = fbRows().length;
|
|
616
|
+
if (k === 'esc') { f.filt = false; f.q = ''; f.i = 0; }
|
|
617
|
+
else if (k === 'enter') { f.filt = false; f.i = clamp(f.i, 0, n - 1); }
|
|
618
|
+
else if (k === 'up') f.i = Math.max(0, f.i - 1);
|
|
619
|
+
else if (k === 'down') f.i = Math.min(n - 1, f.i + 1);
|
|
620
|
+
else { const r = editBuf(f.q, f.qp, k, raw); if (r) { const ch = r.s !== f.q; f.q = r.s; f.qp = r.pos; if (ch) { const j = fbRows().findIndex((x) => x.k === 'dir'); f.i = f.q && j >= 0 ? j : 0; } } } // al filtrar, la selección salta a la primera coincidencia
|
|
621
|
+
return render();
|
|
622
|
+
}
|
|
623
|
+
const n = fbRows().length;
|
|
624
|
+
if (k === 'esc') { if (f.q) { f.q = ''; f.i = 0; } else S.fb = null; }
|
|
625
|
+
else if (k === 'q') S.fb = null;
|
|
626
|
+
else if (k === 'up' || k === 'k') f.i = Math.max(0, f.i - 1);
|
|
627
|
+
else if (k === 'down' || k === 'j') f.i = Math.min(n - 1, f.i + 1);
|
|
628
|
+
else if (k === 'pgup') f.i = Math.max(0, f.i - 8);
|
|
629
|
+
else if (k === 'pgdn') f.i = Math.min(n - 1, f.i + 8);
|
|
630
|
+
else if (k === 'home' || k === 'g') f.i = 0;
|
|
631
|
+
else if (k === 'end' || k === 'G') f.i = n - 1;
|
|
632
|
+
else if (k === 'left' || k === 'h' || k === 'bs') fbUp();
|
|
633
|
+
else if (k === 'enter' || k === 'right' || k === 'l') return fbActivate();
|
|
634
|
+
else if (k === ' ') return fbChoose();
|
|
635
|
+
else if (k === 'n' && f.dir !== '') setPrompt('', 'folder');
|
|
636
|
+
else if (k === '/') { f.filt = true; f.qp = [...f.q].length; }
|
|
637
|
+
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; }
|
|
638
|
+
else if (k === '~') fbOpen(os.homedir());
|
|
639
|
+
render();
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
function recordFolder(d) {
|
|
643
|
+
CFG.recent = [{ dir: d, t: Date.now() }, ...(Array.isArray(CFG.recent) ? CFG.recent : []).filter((x) => x && x.dir !== d)].slice(0, 12);
|
|
644
|
+
saveCfg();
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function openFolder(txt) {
|
|
648
|
+
const t = txt.trim().replace(/^~(?=$|[\\/])/, os.homedir());
|
|
649
|
+
// un nombre suelto ("mi-app") o ruta relativa se crea junto a tus otros proyectos; rutas completas, "~" y "./" funcionan igual que antes
|
|
650
|
+
const d = path.isAbsolute(t) || /^\.\.?([\\/]|$)/.test(t) ? path.resolve(t) : path.resolve(newFolderBase(), t);
|
|
651
|
+
let ok = false; try { ok = fs.statSync(d).isDirectory(); } catch { /* no existe */ }
|
|
652
|
+
if (!txt.trim()) { flash(T.missing + ': ' + shortPath(d)); return; }
|
|
653
|
+
if (!ok) { // carpeta nueva: Enter otra vez la crea (con confirmación para no crear carpetas por un error de tecleo)
|
|
654
|
+
if (S.confirmMk !== d) { S.confirmMk = d; setPrompt(txt, 'folder'); flash(T.mkAsk + ': ' + baseName(d)); return; }
|
|
655
|
+
S.confirmMk = null;
|
|
656
|
+
try { fs.mkdirSync(d, { recursive: true }); } catch (e) { flash(T.mkFail + ': ' + String(e.message).split('\n')[0]); return; }
|
|
657
|
+
}
|
|
658
|
+
S.fb = null; recordFolder(d);
|
|
659
|
+
const proj = S.projects.find((p) => p.cwd === d) || { key: '__open', cwd: d, name: baseName(d), sessions: [], mtime: Date.now() };
|
|
660
|
+
launch(proj, null);
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
function onKeyTree(raw) {
|
|
664
|
+
const k = KEYMAP[raw] || raw;
|
|
665
|
+
const L = flatList(); const e = L[S.c];
|
|
666
|
+
const top = () => { const i = flatList().findIndex((x) => x.t === 'p' && x.p === e.p); if (i >= 0) S.c = i; };
|
|
667
|
+
if (k === 'ctrlc') return quit();
|
|
668
|
+
if (k === 'focus') return reloadKeep();
|
|
669
|
+
if (k === 'f6') { const key = EMBED ? E.shown : null; return key ? closeChat(key) : flash(T.notOpen); }
|
|
670
|
+
if (k === 'f2') { if (EMBED && E.sessions.has(E.shown)) { E.focus = 'right'; render(); } return; }
|
|
671
|
+
if (k === 'f1') return;
|
|
672
|
+
if (S.help) { S.help = false; return render(); }
|
|
673
|
+
if (k === 'ctrlp' || k === 'f5') { S.qs = S.qs ? null : { q: '', pc: 0, i: 0, off: 0 }; return render(); }
|
|
674
|
+
if (S.qs) {
|
|
675
|
+
const items = qsItems();
|
|
676
|
+
if (k === 'esc') S.qs = null;
|
|
677
|
+
else if (k === 'enter') {
|
|
678
|
+
const it = items[S.qs.i]; S.qs = null;
|
|
679
|
+
if (it) {
|
|
680
|
+
S.open = it.p.key; S.query = ''; queryChanged();
|
|
681
|
+
const i = flatList().findIndex((x) => x.t === 's' && x.s.id === it.s.id); if (i >= 0) S.c = i;
|
|
682
|
+
render(); return launch(it.p, it.s);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
else if (k === 'up') S.qs.i = Math.max(0, S.qs.i - 1);
|
|
686
|
+
else if (k === 'down') S.qs.i = Math.min(items.length - 1, S.qs.i + 1);
|
|
687
|
+
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; } }
|
|
688
|
+
return render();
|
|
689
|
+
}
|
|
690
|
+
if (S.prompt !== null) {
|
|
691
|
+
if (k === 'esc') S.prompt = null;
|
|
692
|
+
else if (k === 'enter') {
|
|
693
|
+
const t = S.prompt, kind = S.promptKind, tgt = S.renameTarget; S.prompt = null; render();
|
|
694
|
+
return kind === 'rename' ? doRename(tgt, t) : openFolder(t);
|
|
695
|
+
}
|
|
696
|
+
else { const r = editBuf(S.prompt, S.pc, k, raw); if (r) { S.prompt = r.s; S.pc = r.pos; } }
|
|
697
|
+
return render();
|
|
698
|
+
}
|
|
699
|
+
if (S.fb) return fbKey(k, raw);
|
|
700
|
+
if (S.searching) {
|
|
701
|
+
if (k === 'esc') { S.query = ''; S.searching = false; S.c = 0; queryChanged(); }
|
|
702
|
+
else if (k === 'enter') S.searching = false;
|
|
703
|
+
else if (k === '\t') { S.deep = !S.deep; queryChanged(); }
|
|
704
|
+
else if (k === 'up') S.c = Math.max(0, S.c - 1);
|
|
705
|
+
else if (k === 'down') S.c = Math.min(L.length - 1, S.c + 1);
|
|
706
|
+
else { const r = editBuf(S.query, S.qpos, k, raw); if (r) { const ch = r.s !== S.query; S.query = r.s; S.qpos = r.pos; if (ch) { S.c = 0; queryChanged(); } } }
|
|
707
|
+
return render();
|
|
708
|
+
}
|
|
709
|
+
S.flash = '';
|
|
710
|
+
switch (k) {
|
|
711
|
+
case 'q': return quit();
|
|
712
|
+
case 'up': case 'k': S.c = Math.max(0, S.c - 1); break;
|
|
713
|
+
case 'down': case 'j': S.c = Math.min(L.length - 1, S.c + 1); break;
|
|
714
|
+
case 'pgup': S.c = Math.max(0, S.c - 8); break;
|
|
715
|
+
case 'pgdn': S.c = Math.min(L.length - 1, S.c + 8); break;
|
|
716
|
+
case 'home': case 'g': S.c = 0; break;
|
|
717
|
+
case 'end': case 'G': S.c = Math.max(0, L.length - 1); break;
|
|
718
|
+
case 'enter': case 'right': case 'l':
|
|
719
|
+
if (!e) break;
|
|
720
|
+
if (e.t === 'p') { S.open = (e.open && k === 'enter') ? null : e.p.key; top(); }
|
|
721
|
+
else if (e.t === 'm') { S.more.add(e.p.key); }
|
|
722
|
+
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(); }
|
|
723
|
+
else return launch(e.p, e.t === 's' ? e.s : null);
|
|
724
|
+
break;
|
|
725
|
+
case 'left': case 'h':
|
|
726
|
+
if (!e) break;
|
|
727
|
+
if (e.t !== 'p') top(); else { S.open = null; top(); }
|
|
728
|
+
break;
|
|
729
|
+
case 'n': if (e) return launch(e.p, null); break;
|
|
730
|
+
case '/': S.searching = true; S.qpos = [...S.query].length; break;
|
|
731
|
+
case 'r': reloadKeep(); return;
|
|
732
|
+
case '?': S.help = true; break;
|
|
733
|
+
case 'o': fbOpen(os.homedir()); break;
|
|
734
|
+
case 'R': if (e && e.t === 's') { setPrompt(e.s.title, 'rename'); S.renameTarget = e.s; } break;
|
|
735
|
+
case 'a':
|
|
736
|
+
if (e && e.t === 's') {
|
|
737
|
+
const i = CFG.archived.indexOf(e.s.id);
|
|
738
|
+
if (i >= 0) CFG.archived.splice(i, 1); else CFG.archived.push(e.s.id);
|
|
739
|
+
saveCfg(); S.flash = i >= 0 ? T.unarchMsg : T.archMsg;
|
|
740
|
+
}
|
|
741
|
+
break;
|
|
742
|
+
case 'c': {
|
|
743
|
+
const key = e && e.t === 's' && S.live.has(e.s.id) ? (chatKeyOf(e.s.id) || e.s.id) : e && e.t === 'l' ? e.key : EMBED ? E.shown : null;
|
|
744
|
+
return key ? closeChat(key) : flash(T.notOpen);
|
|
745
|
+
}
|
|
746
|
+
case 'i': case 'f7':
|
|
747
|
+
if (e && e.t === 's') {
|
|
748
|
+
if (EMBED) return openGallery(e.p.name, e.s);
|
|
749
|
+
imagesOf(e.s).then((imgs) => { // con tmux no hay panel propio: se abren en el visor del sistema
|
|
750
|
+
if (!imgs.length) return flash(T.noImages);
|
|
751
|
+
openExternal(exportImages(imgs).dir); flash(T.imgFolder);
|
|
752
|
+
});
|
|
753
|
+
} else if (EMBED) return openGalleryShown();
|
|
754
|
+
break;
|
|
755
|
+
case '[': return adjustSidebar(-4);
|
|
756
|
+
case ']': return adjustSidebar(4);
|
|
757
|
+
case 'H': S.showHidden = !S.showHidden; break;
|
|
758
|
+
case 'p': case 'x':
|
|
759
|
+
if (e) {
|
|
760
|
+
const pr = e.p, f = k === 'p' ? 'pinned' : 'hidden';
|
|
761
|
+
toggleProject(pr, f);
|
|
762
|
+
const i = flatList().findIndex((x) => x.t === 'p' && x.p === pr);
|
|
763
|
+
if (i >= 0) S.c = i;
|
|
764
|
+
S.flash = f === 'hidden' ? (pr.hidden ? T.hiddenMsg : '') : (pr.pinned ? T.pinMsg : '');
|
|
765
|
+
}
|
|
766
|
+
break;
|
|
767
|
+
case 'esc': if (S.query) { S.query = ''; S.c = 0; queryChanged(); } break;
|
|
768
|
+
default: break;
|
|
769
|
+
}
|
|
770
|
+
render();
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
function idle() {
|
|
774
|
+
const draw = () => {
|
|
775
|
+
const c = process.stdout.columns || 80, r = process.stdout.rows || 24;
|
|
776
|
+
const rows = [[C.brand + C.bold, '» Hop\u0001deck'], [C.text, T.idle1], [C.dim, T.idle2], ['', ''], [C.dim, T.idle3]];
|
|
777
|
+
let out = '\x1b[2J\x1b[?25l';
|
|
778
|
+
rows.forEach(([st, t], i) => { out += `\x1b[${Math.max(1, Math.floor(r / 2) - 2 + i)};${Math.max(1, Math.floor((c - strW(t.replace('\u0001', ''))) / 2) + 1)}H${st}${paintMark(t)}${R}`; });
|
|
779
|
+
process.stdout.write(out);
|
|
780
|
+
};
|
|
781
|
+
draw(); process.stdout.on('resize', draw);
|
|
782
|
+
const bye = () => { process.stdout.write('\x1b[?25h'); process.exit(0); };
|
|
783
|
+
process.on('SIGTERM', bye); process.on('SIGHUP', bye);
|
|
784
|
+
setInterval(() => { /* mantiene vivo el panel */ }, 1 << 30);
|
|
785
|
+
}
|
|
786
|
+
|
|
787
|
+
function hasTmux() { try { return cp.spawnSync('tmux', ['-V'], { stdio: 'ignore' }).status === 0; } catch { return false; } }
|
|
788
|
+
|
|
789
|
+
/** Crea (o reabre) la sesión tmux: panel lateral con el hub + panel derecho para los chats. */
|
|
790
|
+
function bootstrap() {
|
|
791
|
+
const cols = process.stdout.columns || 120, rows = process.stdout.rows || 32;
|
|
792
|
+
const sock = ['-L', 'hopdeck'];
|
|
793
|
+
let confDir = null; // carpeta privada y aleatoria: un nombre fijo en /tmp permitiría que otro usuario del equipo colara su configuración
|
|
794
|
+
const has = cp.spawnSync('tmux', [...sock, 'has-session', '-t', 'hopdeck'], { stdio: 'ignore' }).status === 0;
|
|
795
|
+
if (!has) {
|
|
796
|
+
confDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hopdeck-tmux-'));
|
|
797
|
+
const conf = path.join(confDir, 'tmux.conf');
|
|
798
|
+
fs.writeFileSync(conf, [
|
|
799
|
+
'set -g default-shell /bin/sh', 'set -g mouse on', 'set -g escape-time 10', 'set -g history-limit 50000',
|
|
800
|
+
'set -g focus-events on', 'set -g default-terminal "screen-256color"', 'set -ga terminal-overrides ",*:Tc"',
|
|
801
|
+
'set -g status on', 'set -g status-style "bg=default,fg=colour244"', 'set -g status-left ""', 'set -g status-right-length 120',
|
|
802
|
+
`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} "`,
|
|
803
|
+
'setw -g window-status-format ""', 'setw -g window-status-current-format ""',
|
|
804
|
+
'set -g pane-border-status top',
|
|
805
|
+
'set -g pane-border-format "#{?@hopdeck_title, #[fg=colour105#,bold]#{@hopdeck_title}#[default] ,}"',
|
|
806
|
+
'set -g pane-border-style "fg=colour239"', 'set -g pane-active-border-style "fg=colour105"',
|
|
807
|
+
'bind -n F1 select-pane -L', 'bind -n F2 select-pane -R', '',
|
|
808
|
+
].join('\n'));
|
|
809
|
+
const me = [process.execPath, __filename];
|
|
810
|
+
const t = (...a) => cp.execFileSync('tmux', [...sock, ...a], { encoding: 'utf8' }).trim();
|
|
811
|
+
const right = t('-f', conf, 'new-session', '-d', '-s', 'hopdeck', '-x', String(cols), '-y', String(rows), '-P', '-F', '#{pane_id}',
|
|
812
|
+
['env', 'HOPDECK_INSIDE=1', ...me, '--idle'].map(sq).join(' '));
|
|
813
|
+
try { fs.rmSync(confDir, { recursive: true, force: true }); } catch { /* */ } // tmux ya leyó la configuración
|
|
814
|
+
const sw = CFG.sidebar ? clamp(CFG.sidebar, 24, 80) : clamp(Math.floor(cols * 0.3), 38, 46);
|
|
815
|
+
const left = t('split-window', '-hb', '-t', right, '-l', String(sw), '-P', '-F', '#{pane_id}',
|
|
816
|
+
['env', 'HOPDECK_INSIDE=1', ...me, '--sidebar', ...extraArgs].map(sq).join(' '));
|
|
817
|
+
t('select-pane', '-t', left);
|
|
818
|
+
}
|
|
819
|
+
cp.spawnSync('tmux', [...sock, 'attach', '-t', 'hopdeck'], { stdio: 'inherit' });
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
// ───────────────────────── modo embebido (PowerShell / sin tmux) ─────────────────────────
|
|
823
|
+
// Un terminal virtual (xterm headless + PTY) dibujado dentro del panel derecho.
|
|
824
|
+
function loadDeps() {
|
|
825
|
+
try { return { pty: require('@lydell/node-pty'), Terminal: require('@xterm/headless').Terminal }; } catch { return null; }
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
function embedLayout() {
|
|
829
|
+
const W = process.stdout.columns || 100, H = process.stdout.rows || 30;
|
|
830
|
+
const SW = E.hideSide ? 0 : CFG.sidebar ? clamp(CFG.sidebar, 24, 80) : clamp(Math.floor(W * 0.3), 36, 46);
|
|
831
|
+
return { W, H, SW, rw: Math.max(10, W - SW - (SW ? 1 : 0)), rh: Math.max(3, H - 1), th: Math.max(3, H - 3) };
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
function sgr(c, fgMode) {
|
|
835
|
+
const base = fgMode ? 30 : 40;
|
|
836
|
+
const isDef = fgMode ? c.isFgDefault() : c.isBgDefault();
|
|
837
|
+
if (isDef) return '';
|
|
838
|
+
const v = fgMode ? c.getFgColor() : c.getBgColor();
|
|
839
|
+
if (fgMode ? c.isFgRGB() : c.isBgRGB()) return `;${base + 8};2;${(v >> 16) & 255};${(v >> 8) & 255};${v & 255}`;
|
|
840
|
+
if (v < 8) return `;${base + v}`;
|
|
841
|
+
if (v < 16) return `;${base + 60 + v - 8}`;
|
|
842
|
+
return `;${base + 8};5;${v}`;
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
function termRow(term, y, width, sel, from = 0) {
|
|
846
|
+
const buf = term.buffer.active;
|
|
847
|
+
const line = buf.getLine(buf.viewportY + y);
|
|
848
|
+
let out = '', used = 0, last = null;
|
|
849
|
+
if (line) {
|
|
850
|
+
const cell = buf.getNullCell();
|
|
851
|
+
for (let x = from; x < from + width && x < term.cols; x++) {
|
|
852
|
+
const c = line.getCell(x, cell);
|
|
853
|
+
if (!c) break;
|
|
854
|
+
const w = c.getWidth();
|
|
855
|
+
if (w === 0) continue;
|
|
856
|
+
const ch = c.getChars() || ' ';
|
|
857
|
+
if (used + w > width) break;
|
|
858
|
+
const inSel = sel && x >= sel[0] && x <= sel[1];
|
|
859
|
+
const st = (inSel && !c.isInverse() ? ';7' : '') + (c.isBold() ? ';1' : '') + (c.isDim() ? ';2' : '') + (c.isItalic() ? ';3' : '') + (c.isUnderline() ? ';4' : '') +
|
|
860
|
+
(c.isInverse() ? ';7' : '') + (c.isInvisible() ? ';8' : '') + (c.isStrikethrough() ? ';9' : '') + sgr(c, true) + sgr(c, false);
|
|
861
|
+
if (st !== last) { out += '\x1b[0m' + (st ? '\x1b[' + st.slice(1) + 'm' : ''); last = st; }
|
|
862
|
+
out += ch; used += w;
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
return out + '\x1b[0m' + ' '.repeat(Math.max(0, width - used));
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
/** Texto con la marca en dos colores: \u0001 separa "Hop" (color de marca) de "deck" (color del texto). */
|
|
869
|
+
const paintMark = (t) => t.replace('\u0001', R + C.text + C.bold);
|
|
870
|
+
|
|
871
|
+
function idleRow(y, width, height) {
|
|
872
|
+
const rows = [[C.brand + C.bold, '» Hop\u0001deck'], [C.text, T.idle1], [C.dim, T.idle2], ['', ''], [C.dim, T.idle3]];
|
|
873
|
+
const i = y - (Math.floor(height / 2) - 2);
|
|
874
|
+
if (i < 0 || i >= rows.length) return ' '.repeat(width);
|
|
875
|
+
const [st, t] = rows[i];
|
|
876
|
+
const vis = t.replace('\u0001', ''), pad = Math.max(0, Math.floor((width - strW(vis)) / 2));
|
|
877
|
+
return ' '.repeat(pad) + st + paintMark(t) + R + ' '.repeat(Math.max(0, width - pad - strW(vis)));
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
function loaderRow(y, width, height, title) {
|
|
881
|
+
const rows = [[C.accent + C.bold, spin() + ' ' + T.opening + '…'], [C.dim, title]];
|
|
882
|
+
const i = y - (Math.floor(height / 2) - 1);
|
|
883
|
+
if (i < 0 || i >= rows.length) return ' '.repeat(width);
|
|
884
|
+
const [st, t0] = rows[i];
|
|
885
|
+
const t = strW(t0) > width - 2 ? t0.slice(0, Math.max(0, width - 3)) + '…' : t0;
|
|
886
|
+
const pad = Math.max(0, Math.floor((width - strW(t)) / 2));
|
|
887
|
+
return ' '.repeat(pad) + st + t + R + ' '.repeat(Math.max(0, width - pad - strW(t)));
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
// ───────────────────────── imágenes de las conversaciones ─────────────────────────
|
|
891
|
+
// Claude Code guarda las imágenes adjuntas como bloques base64 dentro del historial. Se muestran con
|
|
892
|
+
// "medios bloques" (▀: dos píxeles por celda), que funciona en cualquier terminal con color.
|
|
893
|
+
const IMG = new Map(); // archivo → { m, images }
|
|
894
|
+
|
|
895
|
+
const maxImages = () => (CFG.maxImages > 0 ? CFG.maxImages : 200); // configurable en ~/.hopdeck.json
|
|
896
|
+
const previewMsgs = () => (CFG.previewMsgs > 0 ? CFG.previewMsgs : 12);
|
|
897
|
+
const extractImages = (file) => images.extractImages(file, maxImages());
|
|
898
|
+
|
|
899
|
+
async function imagesOf(x) {
|
|
900
|
+
const hit = IMG.get(x.file);
|
|
901
|
+
if (hit && hit.m === x.mtime) return hit.images;
|
|
902
|
+
const images = await extractImages(x.file);
|
|
903
|
+
IMG.set(x.file, { m: x.mtime, images });
|
|
904
|
+
return images;
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
/** Abre un archivo o carpeta con el programa por defecto del sistema. */
|
|
908
|
+
function openExternal(target) {
|
|
909
|
+
const quiet = (cmd, args) => { try { const c = cp.spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true }); c.on('error', () => {}); c.unref(); } catch { /* */ } };
|
|
910
|
+
if (WIN) quiet('cmd', ['/c', 'start', '', target]);
|
|
911
|
+
else if (process.platform === 'darwin') quiet('open', [target]);
|
|
912
|
+
else if (process.env.WSL_DISTRO_NAME) { try { quiet('explorer.exe', [cp.execFileSync('wslpath', ['-w', target], { encoding: 'utf8' }).trim()]); } catch { quiet('xdg-open', [target]); } }
|
|
913
|
+
else quiet('xdg-open', [target]);
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
/**
|
|
917
|
+
* Extensión de una imagen según sus primeros bytes (no según el "media_type" del historial, que no es de fiar:
|
|
918
|
+
* un resultado de herramienta podría declarar "image/exe" y acabaría guardado y abierto como programa).
|
|
919
|
+
* Devuelve null si no es un formato de imagen conocido.
|
|
920
|
+
*/
|
|
921
|
+
function imageExt(im) {
|
|
922
|
+
const b = Buffer.from(String(im.data).slice(0, 64), 'base64');
|
|
923
|
+
if (b.length >= 4 && b.readUInt32BE(0) === 0x89504e47) return 'png';
|
|
924
|
+
if (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return 'jpg';
|
|
925
|
+
if (b.toString('latin1', 0, 4) === 'GIF8') return 'gif';
|
|
926
|
+
if (b.toString('latin1', 0, 4) === 'RIFF' && b.toString('latin1', 8, 12) === 'WEBP') return 'webp';
|
|
927
|
+
if (b[0] === 0x42 && b[1] === 0x4d) return 'bmp';
|
|
928
|
+
return null;
|
|
929
|
+
}
|
|
930
|
+
|
|
931
|
+
const EXPORT_DIRS = new Set();
|
|
932
|
+
/** Guarda las imágenes en una carpeta temporal privada (aleatoria, solo del usuario) y devuelve sus rutas. */
|
|
933
|
+
function exportImages(images) {
|
|
934
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hopdeck-images-')); EXPORT_DIRS.add(dir);
|
|
935
|
+
return { dir, files: images.map((im, i) => {
|
|
936
|
+
const ext = imageExt(im), f = path.join(dir, `imagen-${i + 1}.${ext || 'bin'}`);
|
|
937
|
+
fs.writeFileSync(f, Buffer.from(im.data, 'base64'), { mode: 0o600 });
|
|
938
|
+
return ext ? f : null; // lo que no es una imagen reconocible se guarda como .bin y no se abre
|
|
939
|
+
}) };
|
|
940
|
+
}
|
|
941
|
+
function cleanExports() { for (const d of EXPORT_DIRS) { try { fs.rmSync(d, { recursive: true, force: true }); } catch { /* */ } } EXPORT_DIRS.clear(); }
|
|
942
|
+
|
|
943
|
+
async function openGallery(project, x) {
|
|
944
|
+
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() };
|
|
945
|
+
E.gallery = g; ensureSpin(); render();
|
|
946
|
+
try { g.images = await imagesOf(x); } catch { g.images = []; }
|
|
947
|
+
g.loading = false; render();
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
/** Galería del chat abierto: si es nuevo, su archivo es la sesión más reciente del proyecto. */
|
|
951
|
+
async function shownSession(x) {
|
|
952
|
+
let sess = x.sid && S.projects.flatMap((p) => p.sessions).find((q) => q.id === x.sid);
|
|
953
|
+
if (!sess) {
|
|
954
|
+
await reloadAsync(null, true);
|
|
955
|
+
const p = S.projects.find((q) => q.cwd === x.cwd);
|
|
956
|
+
sess = p && p.sessions[0];
|
|
957
|
+
}
|
|
958
|
+
return sess;
|
|
959
|
+
}
|
|
960
|
+
|
|
961
|
+
async function openGalleryShown() {
|
|
962
|
+
const x = E.sessions.get(E.shown); if (!x) return flash(T.notOpen);
|
|
963
|
+
const sess = await shownSession(x);
|
|
964
|
+
if (!sess) return flash(T.noImages);
|
|
965
|
+
openGallery(x.project, sess);
|
|
966
|
+
}
|
|
967
|
+
|
|
968
|
+
/** Hover sobre un "[Image #N]" del chat: muestra esa imagen (si ya está en el historial) mientras el cursor siga encima. */
|
|
969
|
+
/** Cuadro flotante con la imagen del hover: se dibuja sobre el chat, pegado a la marca [Image #N], sin tapar el resto. */
|
|
970
|
+
function hoverPopup(hv, rw, th) {
|
|
971
|
+
const g = hv.g, img = g.images[0]; if (!img) return null;
|
|
972
|
+
if (!g.dec.has(0) && !g.pending) {
|
|
973
|
+
g.pending = true; ensureSpin();
|
|
974
|
+
setImmediate(() => { let d = false; try { d = decodeImage(img) || false; } catch { d = false; } g.dec.set(0, d); g.pending = false; if (active) render(); });
|
|
975
|
+
}
|
|
976
|
+
const d = g.dec.get(0), lab = ` [Image #${hv.n}] `;
|
|
977
|
+
let rows, tw;
|
|
978
|
+
if (d && d.rgba) {
|
|
979
|
+
const sz = fitSize(d.w, d.h, Math.max(8, Math.min(rw - 4, 48)), Math.max(2, Math.min(th - 4, 16)) * 2), key = `${sz.tw}x${sz.th}`;
|
|
980
|
+
let hb = g.cache.get(key);
|
|
981
|
+
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); }
|
|
982
|
+
rows = hb; tw = sz.tw;
|
|
983
|
+
} else {
|
|
984
|
+
const txt = d === undefined ? spin() + ' …' : T.imgNoPrev;
|
|
985
|
+
tw = Math.max(strW(lab) + 1, Math.min(strW(txt) + 2, Math.max(8, rw - 4)));
|
|
986
|
+
rows = [fit([[' ' + txt, d === false ? C.warn : C.accent]], tw)];
|
|
987
|
+
}
|
|
988
|
+
const label = strW(lab) <= tw - 1 ? lab : '', b = C.accent;
|
|
989
|
+
const box = [b + '╭─' + label + '─'.repeat(Math.max(0, tw - 1 - strW(label))) + '╮' + R,
|
|
990
|
+
...rows.map((r) => b + '│' + R + r + b + '│' + R), b + '╰' + '─'.repeat(tw) + '╯' + R];
|
|
991
|
+
const bw = tw + 2, bh = box.length, left = clamp(hv.at.x, 0, Math.max(0, rw - bw));
|
|
992
|
+
let top = hv.at.y + 1; // debajo de la marca; si no cabe, encima; si tampoco, pegado al borde
|
|
993
|
+
if (top + bh > th) top = hv.at.y - bh;
|
|
994
|
+
if (top < 0) top = Math.max(0, th - bh);
|
|
995
|
+
return { left, top, bw, rows: box };
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
function hoverChat(sh, x, y) {
|
|
999
|
+
const { SW, rw } = embedLayout(), x0 = SW ? SW + 2 : 1;
|
|
1000
|
+
let n = 0, at = null;
|
|
1001
|
+
if (sh.ready && x >= x0 && y >= 3) {
|
|
1002
|
+
const b = sh.term.buffer.active, l = b.getLine(b.viewportY + (y - 3));
|
|
1003
|
+
const txt = l ? l.translateToString(true) : '', col = x - x0;
|
|
1004
|
+
for (const m of txt.matchAll(/\[Image #(\d+)\]/g)) if (col >= m.index && col < m.index + m[0].length) { n = +m[1]; at = { x: m.index, y: y - 3 }; break; }
|
|
1005
|
+
}
|
|
1006
|
+
if (!n) { if (E.hover) { E.hover = null; scheduleRender(); } return; }
|
|
1007
|
+
const k = `${n}:${at.x}:${at.y}`;
|
|
1008
|
+
if (E.hover && E.hover.k === k) return;
|
|
1009
|
+
const hv = { n, k, at, g: { project: sh.project, title: sh.title, images: [], i: 0, loading: true, pending: false, dec: new Map(), cache: new Map() } };
|
|
1010
|
+
E.hover = hv; scheduleRender();
|
|
1011
|
+
(async () => {
|
|
1012
|
+
let img = null;
|
|
1013
|
+
try {
|
|
1014
|
+
const sess = await shownSession(sh);
|
|
1015
|
+
if (sess) {
|
|
1016
|
+
const imgs = await imagesOf(sess);
|
|
1017
|
+
img = imgs.find((im) => im.n === n) || (imgs.some((im) => im.n) ? null : imgs[n - 1]) || null;
|
|
1018
|
+
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
|
|
1019
|
+
}
|
|
1020
|
+
} catch { img = null; }
|
|
1021
|
+
if (E.hover !== hv) return; // el cursor ya se fue
|
|
1022
|
+
if (!img) { hv.g.loading = false; E.note = { t: T.hoverMiss(n), until: Date.now() + 2000 }; return scheduleRender(); }
|
|
1023
|
+
hv.g.images = [img]; hv.g.loading = false; scheduleRender();
|
|
1024
|
+
})();
|
|
1025
|
+
}
|
|
1026
|
+
|
|
1027
|
+
function galleryRows(rw, th, g = E.gallery) {
|
|
1028
|
+
const rows = [], blank = ' '.repeat(rw);
|
|
1029
|
+
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)); };
|
|
1030
|
+
const body = th - 1; let content = [];
|
|
1031
|
+
if (g.loading) content = [center([[spin() + ' ' + T.findImgs, C.accent]])];
|
|
1032
|
+
else if (!g.images.length) content = [center([[T.noImages, C.dim]])];
|
|
1033
|
+
else {
|
|
1034
|
+
const img = g.images[g.i];
|
|
1035
|
+
if (!g.dec.has(g.i) && !g.pending) {
|
|
1036
|
+
g.pending = true; ensureSpin();
|
|
1037
|
+
setImmediate(() => { let d = false; try { d = decodeImage(img) || false; } catch { d = false; } g.dec.set(g.i, d); g.pending = false; if (active) render(); });
|
|
1038
|
+
}
|
|
1039
|
+
const d = g.dec.get(g.i);
|
|
1040
|
+
if (d === undefined) content = [center([[spin() + ' ' + T.decoding, C.accent]])];
|
|
1041
|
+
else if (d === false) content = [center([[T.imgNoPrev, C.warn]]), center([[img.media + ' · o', C.dim]])];
|
|
1042
|
+
else {
|
|
1043
|
+
const { tw, th: th2 } = fitSize(d.w, d.h, rw, body * 2), key = `${g.i}:${tw}x${th2}`;
|
|
1044
|
+
let img2 = g.cache.get(key);
|
|
1045
|
+
if (!img2) { img2 = halfBlocks(scaleBox(d.rgba, d.w, d.h, tw, th2), tw, th2); g.cache.clear(); g.cache.set(key, img2); }
|
|
1046
|
+
const pad = Math.floor((rw - tw) / 2);
|
|
1047
|
+
content = img2.map((l) => ' '.repeat(pad) + l + ' '.repeat(Math.max(0, rw - pad - tw)));
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
const top = Math.max(0, Math.floor((body - content.length) / 2));
|
|
1051
|
+
for (let i = 0; i < body; i++) rows.push(content[i - top] !== undefined && i >= top ? content[i - top] : blank);
|
|
1052
|
+
rows.push(fit([[' ' + T.imgHint, C.accent]], rw));
|
|
1053
|
+
return rows;
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
function galleryKey(raw) {
|
|
1057
|
+
const g = E.gallery, k = KEYMAP[raw] || raw, n = g.images.length;
|
|
1058
|
+
if (k === 'esc' || k === 'q' || k === 'i' || k === 'f7' || k === 'ctrlc') E.gallery = null;
|
|
1059
|
+
else if (k === 'left' || k === 'h' || k === 'p') g.i = Math.max(0, g.i - 1);
|
|
1060
|
+
else if (k === 'right' || k === 'l' || k === 'n') g.i = Math.min(Math.max(0, n - 1), g.i + 1);
|
|
1061
|
+
else if (k === 'home') g.i = 0;
|
|
1062
|
+
else if (k === 'end') g.i = Math.max(0, n - 1);
|
|
1063
|
+
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 }; }
|
|
1064
|
+
render();
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
// Vista previa de los últimos mensajes de la conversación seleccionada (cuando no hay un chat abierto).
|
|
1068
|
+
const PREV = new Map();
|
|
1069
|
+
function previewFor(x) {
|
|
1070
|
+
const hit = PREV.get(x.file);
|
|
1071
|
+
if (hit && hit.m === x.mtime) return hit.msgs;
|
|
1072
|
+
PREV.set(x.file, { m: x.mtime, msgs: null });
|
|
1073
|
+
(async () => {
|
|
1074
|
+
let msgs = [];
|
|
1075
|
+
try {
|
|
1076
|
+
const fh = await fs.promises.open(x.file, 'r');
|
|
1077
|
+
try {
|
|
1078
|
+
const st = await fh.stat(); const len = Math.min(st.size, 512 * 1024);
|
|
1079
|
+
const buf = Buffer.alloc(len); await fh.read(buf, 0, len, st.size - len);
|
|
1080
|
+
const lines = buf.toString('utf8').split('\n'); if (st.size > len) lines.shift();
|
|
1081
|
+
for (let i = lines.length - 1; i >= 0 && msgs.length < previewMsgs(); i--) {
|
|
1082
|
+
const l = lines[i]; if (!isType(l, 'user') && !isType(l, 'assistant')) continue;
|
|
1083
|
+
let j; try { j = JSON.parse(l); } catch { continue; }
|
|
1084
|
+
if (j.isMeta || j.isSidechain || !j.message) continue;
|
|
1085
|
+
const text = tidy(textOf(j.message.content)).slice(0, 700);
|
|
1086
|
+
if (!text || text.startsWith('<') || text.startsWith('[Request interrupted')) continue;
|
|
1087
|
+
msgs.unshift({ role: j.type, text });
|
|
1088
|
+
}
|
|
1089
|
+
} finally { await fh.close(); }
|
|
1090
|
+
} catch { msgs = []; }
|
|
1091
|
+
PREV.set(x.file, { m: x.mtime, msgs });
|
|
1092
|
+
if (active) render();
|
|
1093
|
+
})();
|
|
1094
|
+
return null;
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
function previewRows(msgs, width, height) {
|
|
1098
|
+
const lines = [];
|
|
1099
|
+
for (const m of msgs) {
|
|
1100
|
+
const user = m.role === 'user';
|
|
1101
|
+
wrapText(m.text, Math.max(10, width - 4)).forEach((t, i) => lines.push([i === 0 ? (user ? ' › ' : ' ') : ' ', user ? C.accent : '', t, user ? C.text : C.dim]));
|
|
1102
|
+
lines.push(null);
|
|
1103
|
+
}
|
|
1104
|
+
while (lines.length && lines[lines.length - 1] === null) lines.pop();
|
|
1105
|
+
const shown = lines.slice(-Math.max(1, height - 2)), rows = [];
|
|
1106
|
+
for (let i = 0; i < height; i++) {
|
|
1107
|
+
if (i === height - 1) { rows.push(fit([[' ' + T.prevHint, C.accent]], width)); continue; }
|
|
1108
|
+
const l = shown[i];
|
|
1109
|
+
rows.push(l ? fit([[l[0], l[1]], [' ' + (l[2] || ''), l[3]]], width) : ' '.repeat(width));
|
|
1110
|
+
}
|
|
1111
|
+
return rows;
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
/** Título del panel del chat: proyecto › conversación ⎇ rama */
|
|
1115
|
+
function headerRow(sh, width) {
|
|
1116
|
+
if (!sh) return ' '.repeat(width);
|
|
1117
|
+
return fit([[' ' + sh.project, C.accent + C.bold], [' › ' + sh.title, C.text], [sh.branch ? ' ⎇ ' + sh.branch : '', C.dim]], width);
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
function renderEmbed() {
|
|
1121
|
+
const { W, H, SW, rw, rh, th } = embedLayout();
|
|
1122
|
+
if (W < 70 || H < 12) { process.stdout.write('\x1b[2J\x1b[H' + T.small); invalidate(); return; }
|
|
1123
|
+
const left = SW ? frameTree(SW, rh) : null;
|
|
1124
|
+
const sh = E.sessions.get(E.shown);
|
|
1125
|
+
const rowsOut = [];
|
|
1126
|
+
// sin chat abierto: vista previa de la conversación seleccionada en la lista
|
|
1127
|
+
const selEnt = !sh && !S.help && !S.qs ? flatList()[S.c] : null;
|
|
1128
|
+
const pvMsgs = selEnt && selEnt.t === 's' ? previewFor(selEnt.s) : null;
|
|
1129
|
+
const pvRows = pvMsgs && pvMsgs.length ? previewRows(pvMsgs, rw, th) : null;
|
|
1130
|
+
const hdr = sh || (selEnt && selEnt.t === 's' ? { project: selEnt.p.name, title: selEnt.s.title, branch: gitBranch(selEnt.p.cwd) } : null);
|
|
1131
|
+
const gRows = E.gallery ? galleryRows(rw, th) : null;
|
|
1132
|
+
const hv = !E.gallery && sh && sh.ready && E.hover && !E.hover.g.loading && E.hover.g.images.length ? E.hover : null;
|
|
1133
|
+
const pop = hv ? hoverPopup(hv, rw, th) : null;
|
|
1134
|
+
const popRow = (ty) => (pop && ty >= pop.top && ty < pop.top + pop.rows.length
|
|
1135
|
+
? 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)
|
|
1136
|
+
: null);
|
|
1137
|
+
const div = (E.focus === 'right' ? C.accent : C.faint) + '│' + R;
|
|
1138
|
+
for (let y = 0; y < rh; y++) {
|
|
1139
|
+
const ty = y - 2; // las 2 primeras filas del panel derecho son el título y su línea
|
|
1140
|
+
const gd = E.gallery && E.gallery.dec.get(E.gallery.i);
|
|
1141
|
+
const right = gRows ? (y === 0 ? fit([[' ' + E.gallery.project, C.accent + C.bold], [' › ' + E.gallery.title, C.text],
|
|
1142
|
+
[E.gallery.images.length ? ` ▣ ${E.gallery.i + 1}/${E.gallery.images.length}` + (gd ? ` · ${gd.w}×${gd.h}` : '') : '', C.dim]], rw)
|
|
1143
|
+
: y === 1 ? C.faint + '─'.repeat(rw) + R : gRows[ty])
|
|
1144
|
+
: y === 0 ? headerRow(hdr, rw) : y === 1 ? C.faint + '─'.repeat(rw) + R
|
|
1145
|
+
: 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);
|
|
1146
|
+
rowsOut.push((left ? (left[y] || ' '.repeat(SW)) + div : '') + right);
|
|
1147
|
+
}
|
|
1148
|
+
const live = E.sessions.size;
|
|
1149
|
+
const k = (key, d) => [[key, C.accent], [' ' + d + ' ', C.dim]];
|
|
1150
|
+
const sb = sh && sh.ready ? sh.term.buffer.active : null;
|
|
1151
|
+
const back = sb ? sb.baseY - sb.viewportY : 0;
|
|
1152
|
+
rowsOut.push(fit([[' ', ''], [E.note ? E.note.t + ' ' : '', C.ok], [back > 0 ? T.up(back, sb && sb.baseY ? Math.round((100 * sb.viewportY) / sb.baseY) : -1) + ' ' : '', C.warn],
|
|
1153
|
+
...k('F1', T.bar1), ...k('F2', T.bar2), ...k('F3', E.mouse ? T.bar4 : T.bar5), ...k('F4', E.hideSide ? T.bar7 : T.bar6),
|
|
1154
|
+
[live ? '● ' + live : '', C.ok]], W));
|
|
1155
|
+
const changes = diffRows(rowsOut);
|
|
1156
|
+
let cur = '';
|
|
1157
|
+
if (sh && sh.ready && E.focus === 'right' && !sh.cursorHidden && back === 0) {
|
|
1158
|
+
const b = sh.term.buffer.active;
|
|
1159
|
+
cur = `\x1b[${Math.min(th, b.cursorY + 1) + 2};${(SW ? SW + 1 : 0) + 1 + Math.min(rw - 1, b.cursorX)}H\x1b[?25h`;
|
|
1160
|
+
}
|
|
1161
|
+
process.stdout.write((changes ? '\x1b[?2026h\x1b[?25l' + changes : '\x1b[?25l') + cur + (changes ? '\x1b[?2026l' : ''));
|
|
1162
|
+
}
|
|
1163
|
+
|
|
1164
|
+
function scheduleRender() {
|
|
1165
|
+
if (E.pend) return;
|
|
1166
|
+
E.pend = setTimeout(() => { E.pend = null; render(); }, 16);
|
|
1167
|
+
}
|
|
1168
|
+
|
|
1169
|
+
function embedLive() { S.live = new Set([...E.sessions.keys(), ...[...E.sessions.values()].map((x) => x.sid).filter(Boolean)]); }
|
|
1170
|
+
|
|
1171
|
+
function embedLaunch(project, session) {
|
|
1172
|
+
if (!fs.existsSync(project.cwd)) { flash(T.missing + ': ' + shortPath(project.cwd)); return; }
|
|
1173
|
+
const bin = findClaude();
|
|
1174
|
+
if (!bin) { flash(T.noClaude); return; }
|
|
1175
|
+
const key = session ? session.id : 'new-' + Date.now();
|
|
1176
|
+
const ex = chatKeyOf(key);
|
|
1177
|
+
if (ex) { const x = E.sessions.get(ex); x.unseen = false; E.shown = ex; E.focus = 'right'; render(); return; }
|
|
1178
|
+
const { pty, Terminal } = E.deps; const { rw, th } = embedLayout();
|
|
1179
|
+
const args = [...(session ? ['--resume', session.id] : []), ...extraArgs];
|
|
1180
|
+
const win = WIN && !/\.exe$/i.test(bin);
|
|
1181
|
+
const env = { ...process.env, HOPDECK_SKIP: '1', HOPDECK_INSIDE: '1', TERM: 'xterm-256color', COLORTERM: 'truecolor' };
|
|
1182
|
+
let p;
|
|
1183
|
+
try {
|
|
1184
|
+
p = pty.spawn(win ? (process.env.ComSpec || 'cmd.exe') : bin, win ? ['/d', '/c', bin, ...args] : args,
|
|
1185
|
+
{ name: 'xterm-256color', cols: rw, rows: th, cwd: project.cwd, env });
|
|
1186
|
+
} catch (e) { flash(String(e.message).split('\n')[0]); return; }
|
|
1187
|
+
const term = new Terminal({ cols: rw, rows: th, allowProposedApi: true, scrollback: 2000 });
|
|
1188
|
+
const sess = { p, term, cursorHidden: false, ready: false, lastData: Date.now(), 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) };
|
|
1189
|
+
const vis = (hidden) => (params) => { if (params.some((x) => x === 25 || (Array.isArray(x) && x.includes(25)))) sess.cursorHidden = hidden; return false; };
|
|
1190
|
+
term.parser.registerCsiHandler({ prefix: '?', final: 'h' }, vis(false));
|
|
1191
|
+
term.parser.registerCsiHandler({ prefix: '?', final: 'l' }, vis(true));
|
|
1192
|
+
term.onData((d) => { try { p.write(d); } catch { /* cerrado */ } }); // respuestas a consultas del terminal
|
|
1193
|
+
p.onData((d) => {
|
|
1194
|
+
sess.lastData = Date.now();
|
|
1195
|
+
// "listo" = ya hay texto visible. En Windows ConPTY manda secuencias de control al arrancar, antes de que Claude dibuje nada.
|
|
1196
|
+
term.write(d, () => { if (!sess.ready && hasContent(term)) sess.ready = true; if (E.shown === key) scheduleRender(); });
|
|
1197
|
+
});
|
|
1198
|
+
setTimeout(() => { if (!sess.ready) { sess.ready = true; if (E.shown === key) scheduleRender(); } }, 20000); // por si el chat nunca imprime
|
|
1199
|
+
p.onExit((ev) => {
|
|
1200
|
+
const code = ev && ev.exitCode;
|
|
1201
|
+
if ((code || !sess.ready) && !sess.closing) flash(T.exited(code || 0));
|
|
1202
|
+
E.sessions.delete(key); embedLive();
|
|
1203
|
+
if (E.shown === key) { E.shown = null; E.focus = 'left'; }
|
|
1204
|
+
try { term.dispose(); } catch { /* */ }
|
|
1205
|
+
render();
|
|
1206
|
+
});
|
|
1207
|
+
E.sessions.set(key, sess); E.shown = key; E.focus = 'right'; embedLive();
|
|
1208
|
+
if (!S.projects.some((q) => q.cwd === project.cwd && q.sessions.length)) { // carpeta sin historial: que la lista la muestre ya, con su chat nuevo
|
|
1209
|
+
reloadAsync(() => { const q = S.projects.find((x) => x.cwd === project.cwd); if (q) S.open = q.key; }, true);
|
|
1210
|
+
}
|
|
1211
|
+
ensureSpin(); render();
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
function selNorm(sl) {
|
|
1215
|
+
let a = sl.a, b = sl.b;
|
|
1216
|
+
if (b.y < a.y || (b.y === a.y && b.x < a.x)) [a, b] = [b, a];
|
|
1217
|
+
return [a, b];
|
|
1218
|
+
}
|
|
1219
|
+
function selRange(ty, rw) {
|
|
1220
|
+
if (!E.sel || !E.sel.down) return null;
|
|
1221
|
+
const [a, b] = selNorm(E.sel);
|
|
1222
|
+
if (ty < a.y || ty > b.y) return null;
|
|
1223
|
+
return [ty === a.y ? a.x : 0, ty === b.y ? b.x : rw - 1];
|
|
1224
|
+
}
|
|
1225
|
+
function selText(sh, sl) {
|
|
1226
|
+
const [a, b] = selNorm(sl); const buf = sh.term.buffer.active; const out = [];
|
|
1227
|
+
for (let y = a.y; y <= b.y; y++) {
|
|
1228
|
+
const l = buf.getLine(buf.viewportY + y);
|
|
1229
|
+
out.push(l ? l.translateToString(true, y === a.y ? a.x : 0, y === b.y ? b.x + 1 : sh.term.cols) : '');
|
|
1230
|
+
}
|
|
1231
|
+
return out.join('\n').replace(/\s+$/, '');
|
|
1232
|
+
}
|
|
1233
|
+
/** Copia al portapapeles: OSC 52 (la mayoría de terminales) + comando del sistema como respaldo. */
|
|
1234
|
+
function copyText(t) {
|
|
1235
|
+
try { process.stdout.write(`\x1b]52;c;${Buffer.from(t).toString('base64')}\x07`); } catch { /* */ }
|
|
1236
|
+
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 { /* */ } };
|
|
1237
|
+
if (process.platform === 'darwin') run('pbcopy', []);
|
|
1238
|
+
else if (WIN) run('powershell', ['-NoProfile', '-Command', '[Console]::InputEncoding=[Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())']);
|
|
1239
|
+
else if (process.env.WAYLAND_DISPLAY) run('wl-copy', []);
|
|
1240
|
+
else run('xclip', ['-selection', 'clipboard']);
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
function scrollSession(sh, lines) { // lines > 0 = hacia arriba
|
|
1244
|
+
if (!sh || sh.term.buffer.active.type === 'alternate') return;
|
|
1245
|
+
sh.term.scrollLines(-lines);
|
|
1246
|
+
}
|
|
1247
|
+
|
|
1248
|
+
/** Rueda sobre el chat: si Claude captura el ratón o usa pantalla alternativa, se la reenviamos; si no, scroll del historial. */
|
|
1249
|
+
function wheelChat(sh, up, x, y) {
|
|
1250
|
+
if (!sh || !sh.ready) return;
|
|
1251
|
+
const t = sh.term, alt = t.buffer.active.type === 'alternate';
|
|
1252
|
+
if (t.modes.mouseTrackingMode !== 'none') {
|
|
1253
|
+
const { SW, rw, th } = embedLayout(), x0 = SW ? SW + 2 : 1;
|
|
1254
|
+
const cx = clamp(x - x0 + 1, 1, rw), cy = clamp(y - 3 + 1, 1, th);
|
|
1255
|
+
try { sh.p.write(`\x1b[<${up ? 64 : 65};${cx};${cy}M`.repeat(3)); } catch { /* cerrado */ }
|
|
1256
|
+
} else if (alt) {
|
|
1257
|
+
const k = (up ? '\x1b[A' : '\x1b[B').replace('[', t.modes.applicationCursorKeysMode ? 'O' : '[');
|
|
1258
|
+
try { sh.p.write(k.repeat(3)); } catch { /* cerrado */ }
|
|
1259
|
+
} else scrollSession(sh, up ? 3 : -3);
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
/** Modos de ratón que se piden al terminal: clics, formato SGR y (solo en el modo embebido, que lo usa para el hover) el movimiento. */
|
|
1263
|
+
const mouseModes = (on) => (EMBED ? ['1000', '1003', '1006'] : ['1000', '1006']).map((m) => `\x1b[?${m}${on ? 'h' : 'l'}`).join('');
|
|
1264
|
+
|
|
1265
|
+
function setMouse(on) {
|
|
1266
|
+
E.mouse = on;
|
|
1267
|
+
process.stdout.write(mouseModes(on));
|
|
1268
|
+
render();
|
|
1269
|
+
}
|
|
1270
|
+
|
|
1271
|
+
/**
|
|
1272
|
+
* Ratón en el modo tmux (la lista es su propio panel): rueda para moverse y clic para abrir. tmux solo reenvía los
|
|
1273
|
+
* eventos a un panel cuyo programa los ha pedido; sin esto, los clics solo cambiaban el foco del panel.
|
|
1274
|
+
*/
|
|
1275
|
+
function sidebarMouse(b, x, y, type, rows = process.stdout.rows || 30) {
|
|
1276
|
+
if (b & 64) { // rueda
|
|
1277
|
+
const d = (b & 1) === 0 ? -3 : 3;
|
|
1278
|
+
if (S.fb) S.fb.i = clamp(S.fb.i + d, 0, Math.max(0, fbRows().length - 1));
|
|
1279
|
+
else if (S.qs) S.qs.i = clamp(S.qs.i + d, 0, Math.max(0, qsItems().length - 1));
|
|
1280
|
+
else S.c = clamp(S.c + d, 0, Math.max(0, flatList().length - 1));
|
|
1281
|
+
return render();
|
|
1282
|
+
}
|
|
1283
|
+
if (type !== 'M' || (b & 3) !== 0 || (b & 32)) return; // solo clic izquierdo (no soltar, ni arrastrar, ni otros botones)
|
|
1284
|
+
if (S.help || S.prompt !== null || y < 3 || y > rows - 3) return; // las filas de la lista van de la 3 a rows-3
|
|
1285
|
+
if (S.qs) { const i = S.qs.off + (y - 3); if (qsItems()[i]) { S.qs.i = i; return onKeyTree('\r'); } return; }
|
|
1286
|
+
if (S.fb) { const i = S.fb.off + (y - 3); if (fbRows()[i]) { S.fb.i = i; fbActivate(); } return; }
|
|
1287
|
+
const i = S.coff + (y - 3);
|
|
1288
|
+
if (flatList()[i]) { S.c = i; return onKeyTree('\r'); }
|
|
1289
|
+
}
|
|
1290
|
+
|
|
1291
|
+
function onMouse(b, x, y, type) {
|
|
1292
|
+
if (E.gallery) return;
|
|
1293
|
+
const { SW, rh } = embedLayout();
|
|
1294
|
+
const sh = E.sessions.get(E.shown);
|
|
1295
|
+
if (b & 64) { // rueda
|
|
1296
|
+
E.hover = null;
|
|
1297
|
+
const up = (b & 1) === 0;
|
|
1298
|
+
if (x <= SW && S.fb) S.fb.i = clamp(S.fb.i + (up ? -3 : 3), 0, fbRows().length - 1);
|
|
1299
|
+
else if (x <= SW) { const n = flatList().length; S.c = clamp(S.c + (up ? -3 : 3), 0, Math.max(0, n - 1)); }
|
|
1300
|
+
else wheelChat(sh, up, x, y);
|
|
1301
|
+
return render();
|
|
1302
|
+
}
|
|
1303
|
+
if ((b & 32) && (b & 3) === 3) { // movimiento sin botón (hover): previsualiza la conversación bajo el cursor
|
|
1304
|
+
if (S.help || S.qs || E.sel) return;
|
|
1305
|
+
if (S.fb) { const i = S.fb.off + (y - 3); if (x <= SW && y >= 3 && y <= rh - 2 && fbRows()[i] && i !== S.fb.i) { S.fb.i = i; scheduleRender(); } return; }
|
|
1306
|
+
if (sh) { if (x > SW) hoverChat(sh, x, y); else if (E.hover) { E.hover = null; scheduleRender(); } return; }
|
|
1307
|
+
if (x > SW || y < 3 || y > rh - 2) return;
|
|
1308
|
+
const i = S.coff + (y - 3), L = flatList();
|
|
1309
|
+
if (L[i] && i !== S.c) { S.c = i; scheduleRender(); }
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
const x0 = SW ? SW + 2 : 1, inPane = (SW ? x > SW + 1 : true) && y >= 3 && sh && sh.ready;
|
|
1313
|
+
const cell = () => ({ x: clamp(x - x0, 0, embedLayout().rw - 1), y: clamp(y - 3, 0, embedLayout().th - 1) });
|
|
1314
|
+
if ((b & 32) && (b & 3) === 0) { if (E.sel && E.sel.down) { E.sel.b = cell(); render(); } return; } // arrastre
|
|
1315
|
+
if (type === 'm') { // soltar: copiar la selección
|
|
1316
|
+
const sl = E.sel; E.sel = null;
|
|
1317
|
+
if (sl && sl.down && (sl.a.x !== sl.b.x || sl.a.y !== sl.b.y) && sh) {
|
|
1318
|
+
const t = selText(sh, sl);
|
|
1319
|
+
if (t) { copyText(t); E.note = { t: T.copied(t.length), until: Date.now() + 3000 }; }
|
|
1320
|
+
}
|
|
1321
|
+
return render();
|
|
1322
|
+
}
|
|
1323
|
+
if (type !== 'M' || (b & 3) !== 0) return; // solo clic izquierdo
|
|
1324
|
+
if (inPane) { E.focus = 'right'; const c = cell(); E.sel = { a: c, b: c, down: true }; return render(); }
|
|
1325
|
+
E.sel = null;
|
|
1326
|
+
if (S.fb && x <= SW) {
|
|
1327
|
+
E.focus = 'left'; const i = S.fb.off + (y - 3);
|
|
1328
|
+
if (S.prompt === null && y >= 3 && y <= rh - 2 && fbRows()[i]) { S.fb.i = i; return fbActivate(); }
|
|
1329
|
+
return render();
|
|
1330
|
+
}
|
|
1331
|
+
if (x <= SW) {
|
|
1332
|
+
E.focus = 'left';
|
|
1333
|
+
const i = S.coff + (y - 3), L = flatList();
|
|
1334
|
+
if (y >= 3 && y <= rh - 2 && L[i]) { S.c = i; return onKeyTree('\r'); }
|
|
1335
|
+
} else if (x > SW + 1 && sh && sh.ready) E.focus = 'right';
|
|
1336
|
+
render();
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
function hasContent(term) {
|
|
1340
|
+
const b = term.buffer.active;
|
|
1341
|
+
for (let y = 0; y < term.rows; y++) {
|
|
1342
|
+
const l = b.getLine(b.viewportY + y);
|
|
1343
|
+
if (l && l.translateToString(true).trim()) return true;
|
|
1344
|
+
}
|
|
1345
|
+
return false;
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
function embedInput(s) {
|
|
1349
|
+
E.sel = null; E.hover = null;
|
|
1350
|
+
if (s === '\x1bOP' || s === '\x1b[11~' || s === '\x1b[1;1P') { E.focus = 'left'; if (E.hideSide) { E.hideSide = false; embedResize(); } else render(); return; }
|
|
1351
|
+
const sh = E.sessions.get(E.shown);
|
|
1352
|
+
const b = sh.term.buffer.active, scrolled = b.baseY > b.viewportY;
|
|
1353
|
+
const page = Math.max(1, Math.floor(embedLayout().th / 2));
|
|
1354
|
+
if (s === '\x1b[5~' || s === '\x1b[5;2~') { scrollSession(sh, page); return render(); }
|
|
1355
|
+
if (s === '\x1b[6~' || s === '\x1b[6;2~') { scrollSession(sh, -page); return render(); }
|
|
1356
|
+
if (scrolled && (s === '\x1b[F' || s === '\x1b[4~' || s === '\x1bOF')) { sh.term.scrollToBottom(); return render(); }
|
|
1357
|
+
if (scrolled) { sh.term.scrollToBottom(); render(); }
|
|
1358
|
+
let d = s;
|
|
1359
|
+
// Ctrl+V → Alt+V: en Windows Claude Code pega imágenes con Alt+V; así funciona el atajo de siempre.
|
|
1360
|
+
if (WIN && d === '\x16') d = '\x1bv';
|
|
1361
|
+
if (!sh.term.modes.bracketedPasteMode) d = d.replace(/\x1b\[20[01]~/g, '');
|
|
1362
|
+
if (sh.term.modes.applicationCursorKeysMode) d = d.replace(/\x1b\[([ABCDHF])/g, '\x1bO$1');
|
|
1363
|
+
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
|
|
1364
|
+
try { sh.p.write(d); } catch { /* cerrado */ }
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
/** Aviso de escritorio cuando un chat termina mientras miras otra cosa. */
|
|
1368
|
+
function notifyDesktop(msg) {
|
|
1369
|
+
if (CFG.notify === false) return;
|
|
1370
|
+
msg = clean(msg).slice(0, 200); // viene del historial: sin caracteres de control
|
|
1371
|
+
try {
|
|
1372
|
+
process.stdout.write(`\x1b]9;${msg}\x07`);
|
|
1373
|
+
const spawnQuiet = (cmd, args, env) => { const c = cp.spawn(cmd, args, { stdio: 'ignore', detached: true, windowsHide: true, env: { ...process.env, ...env } }); c.on('error', () => {}); c.unref(); };
|
|
1374
|
+
if (process.platform === 'darwin') spawnQuiet('osascript', ['-e', 'display notification (system attribute "HOPDECK_MSG") with title "Hopdeck"'], { HOPDECK_MSG: msg });
|
|
1375
|
+
else if (WIN) spawnQuiet('powershell', ['-NoProfile', '-WindowStyle', 'Hidden', '-Command',
|
|
1376
|
+
'Add-Type -AssemblyName System.Windows.Forms,System.Drawing; $n=New-Object System.Windows.Forms.NotifyIcon; $n.Icon=[System.Drawing.SystemIcons]::Information; $n.Visible=$true; $n.ShowBalloonTip(6000,"Hopdeck",$env:HOPDECK_MSG,"Info"); Start-Sleep 7; $n.Dispose()'], { HOPDECK_MSG: msg });
|
|
1377
|
+
else spawnQuiet('notify-send', ['--', 'Hopdeck', msg], {}); // "--": un mensaje que empiece por "-" no es una opción
|
|
1378
|
+
} catch { /* sin notificaciones */ }
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
/** Cierra una conversación abierta (si está trabajando pide confirmar con una segunda pulsación). */
|
|
1382
|
+
function closeChat(key) {
|
|
1383
|
+
if (SIDEBAR) {
|
|
1384
|
+
try {
|
|
1385
|
+
const x = tmuxPanes().find((q) => q.key === key); if (!x) return flash(T.notOpen);
|
|
1386
|
+
const mine = process.env.TMUX_PANE;
|
|
1387
|
+
const slot = tmux('list-panes', '-t', mine, '-F', '#{pane_id}').split('\n').find((id) => id && id !== mine);
|
|
1388
|
+
if (x.id === slot) { // el panel visible se deja como "elige una conversación"
|
|
1389
|
+
tmux('respawn-pane', '-k', '-t', slot, ['env', 'HOPDECK_INSIDE=1', process.execPath, __filename, '--idle'].map(sq).join(' '));
|
|
1390
|
+
tmux('set-option', '-p', '-t', slot, '-u', '@hopdeck_key'); tmux('set-option', '-p', '-t', slot, '-u', '@hopdeck_title');
|
|
1391
|
+
} else tmux('kill-pane', '-t', x.id);
|
|
1392
|
+
tmux('select-pane', '-t', mine);
|
|
1393
|
+
} catch (e) { flash(String(e.message).split('\n').filter(Boolean).pop()); }
|
|
1394
|
+
refreshLive(); return;
|
|
1395
|
+
}
|
|
1396
|
+
const x = E.sessions.get(key);
|
|
1397
|
+
if (!x) return flash(T.notOpen);
|
|
1398
|
+
if (x.working && !(S.confirmClose && S.confirmClose.key === key && S.confirmClose.until > Date.now())) {
|
|
1399
|
+
S.confirmClose = { key, until: Date.now() + 4000 }; return flash(T.confirmClose);
|
|
1400
|
+
}
|
|
1401
|
+
S.confirmClose = null; x.closing = true;
|
|
1402
|
+
try { x.p.kill(); } catch { /* ya terminó */ }
|
|
1403
|
+
flash(T.closed(x.title));
|
|
1404
|
+
}
|
|
1405
|
+
|
|
1406
|
+
function pollChats() {
|
|
1407
|
+
const now = Date.now(); let changed = false;
|
|
1408
|
+
for (const [key, x] of E.sessions) {
|
|
1409
|
+
const working = x.ready && now - x.lastData < 1200;
|
|
1410
|
+
if (x.working && !working && x.busy) {
|
|
1411
|
+
x.busy = false;
|
|
1412
|
+
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); }
|
|
1413
|
+
}
|
|
1414
|
+
if (x.working !== working) { x.working = working; changed = true; }
|
|
1415
|
+
if (x.unseen && E.shown === key && E.focus === 'right') { x.unseen = false; changed = true; }
|
|
1416
|
+
}
|
|
1417
|
+
if (E.note && E.note.until < now) { E.note = null; changed = true; }
|
|
1418
|
+
if (changed) { if (x_any(E)) ensureSpin(); render(); }
|
|
1419
|
+
}
|
|
1420
|
+
const x_any = (e) => [...e.sessions.values()].some((x) => x.working);
|
|
1421
|
+
|
|
1422
|
+
function embedResize() {
|
|
1423
|
+
invalidate(); E.sel = null;
|
|
1424
|
+
const { rw, th } = embedLayout();
|
|
1425
|
+
for (const sess of E.sessions.values()) { try { sess.p.resize(rw, th); sess.term.resize(rw, th); } catch { /* */ } }
|
|
1426
|
+
render();
|
|
1427
|
+
}
|
|
1428
|
+
|
|
1429
|
+
function embedKillAll() { for (const sess of E.sessions.values()) { try { sess.p.kill(); } catch { /* */ } } }
|
|
1430
|
+
|
|
1431
|
+
// Redibujado diferencial: solo se reescriben las filas que cambiaron desde el último cuadro.
|
|
1432
|
+
let lastRows = [], forceFull = true;
|
|
1433
|
+
const invalidate = () => { forceFull = true; };
|
|
1434
|
+
function diffRows(rows) {
|
|
1435
|
+
let out = '';
|
|
1436
|
+
for (let i = 0; i < rows.length; i++) {
|
|
1437
|
+
if (forceFull || lastRows[i] !== rows[i]) out += `\x1b[${i + 1};1H` + rows[i];
|
|
1438
|
+
}
|
|
1439
|
+
lastRows = rows.slice(); forceFull = false;
|
|
1440
|
+
return out;
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
function render() {
|
|
1444
|
+
if (EMBED) return renderEmbed();
|
|
1445
|
+
const cols = process.stdout.columns || 100, rows = process.stdout.rows || 30;
|
|
1446
|
+
const lines = SIDEBAR ? frameTree(cols, rows) : frame(cols, rows);
|
|
1447
|
+
const full = [];
|
|
1448
|
+
for (let i = 0; i < rows; i++) full.push(lines[i] || ' '.repeat(cols));
|
|
1449
|
+
const out = diffRows(full);
|
|
1450
|
+
if (out) process.stdout.write(out);
|
|
1451
|
+
}
|
|
1452
|
+
|
|
1453
|
+
// ───────────────────────── terminal ─────────────────────────
|
|
1454
|
+
let active = false;
|
|
1455
|
+
function enter() {
|
|
1456
|
+
if (active) return; active = true; invalidate();
|
|
1457
|
+
process.stdout.write('\x1b[?1049h\x1b[?25l\x1b[2J' + ((EMBED || SIDEBAR) && E.mouse ? mouseModes(true) : ''));
|
|
1458
|
+
process.stdin.setRawMode(true); process.stdin.resume();
|
|
1459
|
+
}
|
|
1460
|
+
function leave() {
|
|
1461
|
+
if (!active) return; active = false;
|
|
1462
|
+
process.stdout.write(((EMBED || SIDEBAR) ? mouseModes(false) : '') + '\x1b[?25h\x1b[?1049l' + R);
|
|
1463
|
+
try { process.stdin.setRawMode(false); } catch { /* */ }
|
|
1464
|
+
process.stdin.pause();
|
|
1465
|
+
}
|
|
1466
|
+
function quit(code = 0) {
|
|
1467
|
+
cleanExports();
|
|
1468
|
+
if (EMBED || SIDEBAR) rememberState();
|
|
1469
|
+
if (EMBED) embedKillAll();
|
|
1470
|
+
if (SIDEBAR) { try { tmux('kill-server'); } catch { /* ya cerrado */ } }
|
|
1471
|
+
leave(); process.exit(code);
|
|
1472
|
+
}
|
|
1473
|
+
|
|
1474
|
+
function load(keepKey) {
|
|
1475
|
+
S.projects = scan();
|
|
1476
|
+
if (keepKey) { const i = S.projects.findIndex((p) => p.key === keepKey); if (i >= 0) S.pi = i; }
|
|
1477
|
+
}
|
|
1478
|
+
|
|
1479
|
+
const extraArgs = [];
|
|
1480
|
+
|
|
1481
|
+
/** Busca el ejecutable real de claude en el PATH (no depende de funciones del shell). */
|
|
1482
|
+
/** Busca un programa en el PATH (por defecto `claude`). Recuerda el resultado mientras el archivo siga existiendo. */
|
|
1483
|
+
const FOUND = new Map();
|
|
1484
|
+
function findClaude(name = 'claude') {
|
|
1485
|
+
const known = FOUND.get(name);
|
|
1486
|
+
if (known) { try { if (fs.statSync(known).isFile()) return known; } catch { /* ya no está: se busca otra vez */ } FOUND.delete(name); }
|
|
1487
|
+
const exts = WIN ? (process.env.PATHEXT || '.EXE;.CMD;.BAT').split(';').concat(['']) : [''];
|
|
1488
|
+
for (const dir of (process.env.PATH || '').split(path.delimiter)) {
|
|
1489
|
+
if (!dir) continue;
|
|
1490
|
+
for (const ext of exts) {
|
|
1491
|
+
const f = path.join(dir, name + ext.toLowerCase());
|
|
1492
|
+
try { if (fs.statSync(f).isFile()) { FOUND.set(name, f); return f; } } catch { /* siguiente */ }
|
|
1493
|
+
}
|
|
1494
|
+
}
|
|
1495
|
+
return null;
|
|
1496
|
+
}
|
|
1497
|
+
|
|
1498
|
+
/** El id de una sesión sale del nombre de su archivo; solo se pasa a `claude --resume` si es un identificador normal. */
|
|
1499
|
+
const safeId = (id) => /^[A-Za-z0-9._-]{1,128}$/.test(String(id || ''));
|
|
1500
|
+
|
|
1501
|
+
function launch(project, session) {
|
|
1502
|
+
if (session && !safeId(session.id)) { flash(T.badId); return; }
|
|
1503
|
+
if (SIDEBAR) return launchSlot(project, session);
|
|
1504
|
+
if (EMBED) return embedLaunch(project, session);
|
|
1505
|
+
if (!fs.existsSync(project.cwd)) { flash(T.missing + ': ' + shortPath(project.cwd)); return; }
|
|
1506
|
+
const bin = findClaude();
|
|
1507
|
+
if (!bin) { flash(T.noClaude); return; }
|
|
1508
|
+
leave();
|
|
1509
|
+
process.stdout.write('\x1b[2J\x1b[H');
|
|
1510
|
+
const args = [...(session ? ['--resume', session.id] : []), ...extraArgs];
|
|
1511
|
+
const opts = { cwd: project.cwd, stdio: 'inherit', env: { ...process.env, HOPDECK_SKIP: '1' } };
|
|
1512
|
+
const onInt = () => { /* Ctrl-C es del proceso hijo */ };
|
|
1513
|
+
process.on('SIGINT', onInt);
|
|
1514
|
+
let res;
|
|
1515
|
+
if (WIN && /\.(cmd|bat)$/i.test(bin)) { // los .cmd necesitan shell: una sola cadena evita DEP0190
|
|
1516
|
+
const q = (x) => (/^[\w.:\\/=@-]+$/.test(x) ? x : `"${x.replace(/"/g, '\\"')}"`);
|
|
1517
|
+
res = cp.spawnSync([`"${bin}"`, ...args.map(q)].join(' '), { ...opts, shell: true });
|
|
1518
|
+
} else res = cp.spawnSync(bin, args, opts);
|
|
1519
|
+
process.removeListener('SIGINT', onInt);
|
|
1520
|
+
if (res.error) {
|
|
1521
|
+
process.stdout.write(`\n${C.warn}${res.error.message}${R}\n${C.dim}${T.pressKey}${R}\n`);
|
|
1522
|
+
process.stdin.setRawMode(true); process.stdin.resume();
|
|
1523
|
+
process.stdin.once('data', () => { process.stdin.setRawMode(false); process.stdin.pause(); back(project.key); });
|
|
1524
|
+
return;
|
|
1525
|
+
}
|
|
1526
|
+
back(project.key);
|
|
1527
|
+
}
|
|
1528
|
+
function back(key) {
|
|
1529
|
+
S.focus = 0; S.si = 0; S.soff = 0; S.query = ''; S.searching = false;
|
|
1530
|
+
enter(); render();
|
|
1531
|
+
reloadAsync(() => { const i = S.projects.findIndex((p) => p.key === key); if (i >= 0) S.pi = i; });
|
|
1532
|
+
}
|
|
1533
|
+
|
|
1534
|
+
let flashT;
|
|
1535
|
+
function flash(msg) { S.flash = msg; render(); clearTimeout(flashT); flashT = setTimeout(() => { S.flash = ''; render(); }, 2500); }
|
|
1536
|
+
|
|
1537
|
+
|
|
1538
|
+
function move(d) {
|
|
1539
|
+
const V = view(); S.flash = '';
|
|
1540
|
+
if (S.focus === 0) { S.pi = clamp(S.pi + d, 0, Math.max(0, V.length - 1)); S.si = 0; S.soff = 0; }
|
|
1541
|
+
else { const n = V[S.pi] ? V[S.pi].ss.length + 1 : 1; S.si = clamp(S.si + d, 0, n - 1); }
|
|
1542
|
+
}
|
|
1543
|
+
|
|
1544
|
+
function onKey(raw) {
|
|
1545
|
+
const k = KEYMAP[raw] || raw;
|
|
1546
|
+
const V = view(); const cur = V[S.pi];
|
|
1547
|
+
if (k === 'ctrlc') return quit();
|
|
1548
|
+
if (S.searching) {
|
|
1549
|
+
if (k === 'esc') { S.query = ''; S.searching = false; S.pi = 0; S.si = 0; queryChanged(); }
|
|
1550
|
+
else if (k === 'enter') S.searching = false;
|
|
1551
|
+
else if (k === '\t') { S.deep = !S.deep; queryChanged(); }
|
|
1552
|
+
else if (k === 'bs') { S.query = S.query.slice(0, -1); S.pi = 0; S.si = 0; queryChanged(); }
|
|
1553
|
+
else if (k === 'up' || k === 'down') move(k === 'up' ? -1 : 1);
|
|
1554
|
+
else if (!KEYMAP[raw] && printable(k)) { S.query += k; S.pi = 0; S.si = 0; S.focus = 0; queryChanged(); }
|
|
1555
|
+
return render();
|
|
1556
|
+
}
|
|
1557
|
+
switch (k) {
|
|
1558
|
+
case 'q': return quit();
|
|
1559
|
+
case 'up': case 'k': move(-1); break;
|
|
1560
|
+
case 'down': case 'j': move(1); break;
|
|
1561
|
+
case 'pgup': move(-8); break;
|
|
1562
|
+
case 'pgdn': move(8); break;
|
|
1563
|
+
case 'home': case 'g': if (S.focus === 0) { S.pi = 0; S.si = 0; } else S.si = 0; break;
|
|
1564
|
+
case 'end': case 'G': if (S.focus === 0) { S.pi = Math.max(0, V.length - 1); S.si = 0; } else S.si = cur ? cur.ss.length : 0; break;
|
|
1565
|
+
case 'left': case 'h': S.focus = 0; break;
|
|
1566
|
+
case 'right': case 'l': if (cur) { S.focus = 1; S.si = Math.min(1, cur.ss.length); } break;
|
|
1567
|
+
case 'enter':
|
|
1568
|
+
if (!cur) break;
|
|
1569
|
+
if (S.focus === 0) { S.focus = 1; S.si = Math.min(1, cur.ss.length); break; }
|
|
1570
|
+
return launch(cur.p, S.si === 0 ? null : cur.ss[S.si - 1]);
|
|
1571
|
+
case 'n': if (cur) return launch(cur.p, null); break;
|
|
1572
|
+
case '/': S.searching = true; S.focus = 0; break;
|
|
1573
|
+
case 'r': reloadAsync(() => { const i = view().findIndex((x) => cur && x.p.key === cur.p.key); if (i >= 0) S.pi = i; }); break;
|
|
1574
|
+
case 'H': S.showHidden = !S.showHidden; break;
|
|
1575
|
+
case 'p': case 'x':
|
|
1576
|
+
if (cur) {
|
|
1577
|
+
const pr = cur.p; toggleProject(pr, k === 'p' ? 'pinned' : 'hidden');
|
|
1578
|
+
const i = view().findIndex((x) => x.p === pr); S.pi = i >= 0 ? i : Math.max(0, S.pi - 1); S.si = 0;
|
|
1579
|
+
}
|
|
1580
|
+
break;
|
|
1581
|
+
case 'esc':
|
|
1582
|
+
if (S.focus === 1) S.focus = 0; else if (S.query) { S.query = ''; S.pi = 0; } else return quit();
|
|
1583
|
+
break;
|
|
1584
|
+
default: break;
|
|
1585
|
+
}
|
|
1586
|
+
render();
|
|
1587
|
+
}
|
|
1588
|
+
|
|
1589
|
+
function splash(done, total) {
|
|
1590
|
+
const c = process.stdout.columns || 80, r = process.stdout.rows || 24;
|
|
1591
|
+
const lines = [[C.brand + C.bold, '» Hopdeck'], ['', ''],
|
|
1592
|
+
[C.dim, `${spin()} ${T.loading}${total ? ` ${done}/${total}` : '…'}`]];
|
|
1593
|
+
let out = '\x1b[2J';
|
|
1594
|
+
lines.forEach(([st, t], i) => { out += `\x1b[${Math.max(1, Math.floor(r / 2) - 1 + i)};${Math.max(1, Math.floor((c - strW(t)) / 2) + 1)}H${st}${t}${R}`; });
|
|
1595
|
+
process.stdout.write(out);
|
|
1596
|
+
}
|
|
1597
|
+
|
|
1598
|
+
async function run() {
|
|
1599
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) { printList(); return; }
|
|
1600
|
+
if (!SIDEBAR && process.env.HOPDECK_INSIDE) { console.log(T.inside); return; }
|
|
1601
|
+
if (!SIDEBAR) await offerShortcut(); // primera vez: ¿quieres que `claude` abra Hopdeck?
|
|
1602
|
+
if (!SIDEBAR) {
|
|
1603
|
+
const preferTmux = !WIN && !process.env.HOPDECK_NOTMUX && !process.env.HOPDECK_EMBED && hasTmux();
|
|
1604
|
+
if (preferTmux) return bootstrap();
|
|
1605
|
+
if (!process.env.HOPDECK_NOEMBED) { E.deps = loadDeps(); EMBED = !!E.deps; }
|
|
1606
|
+
}
|
|
1607
|
+
process.on('exit', () => { if (active) { try { process.stdout.write('\x1b[?1000l\x1b[?1003l\x1b[?1006l\x1b[?25h\x1b[?1049l'); } catch { /* */ } } });
|
|
1608
|
+
process.on('SIGTERM', () => quit(0));
|
|
1609
|
+
enter();
|
|
1610
|
+
splash(0, 0);
|
|
1611
|
+
const tick = setInterval(() => { frameN++; splash(prog[0], prog[1]); }, 90);
|
|
1612
|
+
const prog = [0, 0];
|
|
1613
|
+
S.projects = await scanAsync((d, t) => { prog[0] = d; prog[1] = t; });
|
|
1614
|
+
clearInterval(tick); invalidate();
|
|
1615
|
+
if (SIDEBAR || EMBED) {
|
|
1616
|
+
S.open = S.projects[0] && S.projects[0].key;
|
|
1617
|
+
restoreState();
|
|
1618
|
+
if (SIDEBAR) { process.stdout.write('\x1b[?1004h'); setInterval(refreshLive, 2000); }
|
|
1619
|
+
}
|
|
1620
|
+
process.stdout.on('resize', EMBED ? embedResize : () => { invalidate(); render(); });
|
|
1621
|
+
if (EMBED) setInterval(pollChats, 400);
|
|
1622
|
+
setInterval(() => { // lista siempre al día
|
|
1623
|
+
if (S.loading || reloading || S.searching || S.query || S.prompt !== null || S.help) return;
|
|
1624
|
+
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); }
|
|
1625
|
+
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); }
|
|
1626
|
+
}, 20000);
|
|
1627
|
+
process.stdin.on('data', (buf) => {
|
|
1628
|
+
if (!active) return;
|
|
1629
|
+
let s = normalizeKeys(buf.toString('utf8'));
|
|
1630
|
+
if (EMBED) {
|
|
1631
|
+
s = s.replace(/\x1b\[<(\d+);(\d+);(\d+)([Mm])/g, (m, b, x, y, t) => { onMouse(+b, +x, +y, t); return ''; });
|
|
1632
|
+
if (!s) return;
|
|
1633
|
+
if (s === '\x1bOR' || s === '\x1b[13~') { CFG.mouse = !E.mouse; saveCfg(); return setMouse(!E.mouse); }
|
|
1634
|
+
if (E.gallery) { for (const k of parseKeys(s)) galleryKey(k); return; }
|
|
1635
|
+
if (s === '\x1b[17~' && E.focus === 'right') return closeChat(E.shown);
|
|
1636
|
+
if (s === '\x1b[18~') return openGalleryShown();
|
|
1637
|
+
if (s === '\x1b[15~') { E.focus = 'left'; if (E.hideSide) E.hideSide = false; S.qs = { q: '', pc: 0, i: 0, off: 0 }; return embedResize(); }
|
|
1638
|
+
if (s === '\x1bOS' || s === '\x1b[14~') {
|
|
1639
|
+
E.hideSide = !E.hideSide && E.sessions.has(E.shown);
|
|
1640
|
+
E.focus = E.hideSide ? 'right' : 'left'; return embedResize();
|
|
1641
|
+
}
|
|
1642
|
+
}
|
|
1643
|
+
if (SIDEBAR) { // modo tmux: eventos de ratón de la lista y F3 para apagar/encender el ratón
|
|
1644
|
+
s = s.replace(/\x1b\[<(\d+);(\d+);(\d+)([Mm])/g, (m, b, x, y, t) => { sidebarMouse(+b, +x, +y, t); return ''; });
|
|
1645
|
+
if (!s) return;
|
|
1646
|
+
if (s === '\x1bOR' || s === '\x1b[13~') { CFG.mouse = !E.mouse; saveCfg(); return setMouse(!E.mouse); }
|
|
1647
|
+
}
|
|
1648
|
+
if (EMBED && E.focus === 'right' && E.sessions.has(E.shown)) return embedInput(s);
|
|
1649
|
+
for (const k of parseKeys(s)) (SIDEBAR || EMBED ? onKeyTree : onKey)(k);
|
|
1650
|
+
});
|
|
1651
|
+
render();
|
|
1652
|
+
}
|
|
1653
|
+
|
|
1654
|
+
function doctor() {
|
|
1655
|
+
const ok = (m) => console.log(` ${C.ok}✔${R} ${m}`);
|
|
1656
|
+
const bad = (m, hint) => console.log(` ${C.warn}✘${R} ${m}${hint ? `\n ${C.dim}${hint}${R}` : ''}`);
|
|
1657
|
+
console.log(`\n ${C.brand}${C.bold}» Hop${R}${C.text}${C.bold}deck doctor${R} ${C.dim}v${VERSION}${R}\n`);
|
|
1658
|
+
if (parseInt(process.versions.node, 10) < 22) bad(T.dcNodeOld(process.version), T.dcNodeOldHint);
|
|
1659
|
+
else ok(`Node ${process.version} · ${process.platform} ${process.arch}`);
|
|
1660
|
+
const n = projectDirs().length;
|
|
1661
|
+
const histDir = shortPath(path.join(CONFIG_DIR, 'projects'));
|
|
1662
|
+
n ? ok(T.dcHist(n, histDir)) : bad(T.dcNoHist(histDir), T.dcNoHistHint);
|
|
1663
|
+
const bin = findClaude();
|
|
1664
|
+
bin ? ok(T.dcClaude(shortPath(bin))) : bad(T.dcNoClaude, WIN ? T.dcInstallWin : T.dcInstallUnix);
|
|
1665
|
+
const tm = !WIN && hasTmux();
|
|
1666
|
+
const deps = loadDeps();
|
|
1667
|
+
if (tm) ok(T.dcTmux);
|
|
1668
|
+
else if (deps) ok(T.dcEmbed);
|
|
1669
|
+
else bad(T.dcNone, WIN ? T.dcNoneWin : T.dcNoneUnix);
|
|
1670
|
+
let wrapped = false;
|
|
1671
|
+
for (const t of targets()) { try { if (fs.readFileSync(t.file, 'utf8').includes(MARK_A)) wrapped = true; } catch { /* */ } }
|
|
1672
|
+
wrapped ? ok(T.dcShort) : bad(T.dcNoShort, findClaude('hopdeck') ? T.dcNoShortHint : T.dcNoCmdHint); // sin el comando en el PATH, "hopdeck install" no existe todavía
|
|
1673
|
+
ok(T.dcPrefs(shortPath(CFG_FILE), shortPath(CACHE_FILE)));
|
|
1674
|
+
if (process.env.WT_SESSION) { // dentro de Windows Terminal: Ctrl+V solo pega texto y no deja pegar imágenes
|
|
1675
|
+
const f = wtSettingsFile(); let st = null;
|
|
1676
|
+
try { st = f ? wtCtrlV(fs.readFileSync(f, 'utf8')) : null; } catch { /* */ }
|
|
1677
|
+
if (st === 'custom') ok(T.wtOk);
|
|
1678
|
+
else if (st === 'paste') bad(T.wtBad, T.wtHint);
|
|
1679
|
+
else bad(T.wtUnknown, T.wtHint);
|
|
1680
|
+
}
|
|
1681
|
+
console.log('');
|
|
1682
|
+
}
|
|
1683
|
+
|
|
1684
|
+
function printList() {
|
|
1685
|
+
for (const p of scan()) {
|
|
1686
|
+
console.log(clean(`${p.name} (${p.sessions.length}) ${shortPath(p.cwd)}`));
|
|
1687
|
+
for (const s of p.sessions.slice(0, 5)) console.log(clean(` ${ago(s.mtime).padEnd(8)} ${s.title}`));
|
|
1688
|
+
}
|
|
1689
|
+
}
|
|
1690
|
+
|
|
1691
|
+
// ───────────────────────── instalación del atajo ─────────────────────────
|
|
1692
|
+
const MARK_A = '# >>> hopdeck >>>';
|
|
1693
|
+
const MARK_B = '# <<< hopdeck <<<';
|
|
1694
|
+
const SNIP = {
|
|
1695
|
+
posix: `${MARK_A}
|
|
1696
|
+
claude() {
|
|
1697
|
+
if [ $# -eq 0 ] && [ -t 0 ] && [ -t 1 ] && [ -z "$HOPDECK_SKIP" ] && command -v hopdeck >/dev/null 2>&1; then
|
|
1698
|
+
hopdeck
|
|
1699
|
+
else
|
|
1700
|
+
command claude "$@"
|
|
1701
|
+
fi
|
|
1702
|
+
}
|
|
1703
|
+
${MARK_B}
|
|
1704
|
+
`,
|
|
1705
|
+
fish: `${MARK_A}
|
|
1706
|
+
function claude
|
|
1707
|
+
if test (count $argv) -eq 0; and isatty stdin; and isatty stdout; and test -z "$HOPDECK_SKIP"; and type -q hopdeck
|
|
1708
|
+
hopdeck
|
|
1709
|
+
else
|
|
1710
|
+
command claude $argv
|
|
1711
|
+
end
|
|
1712
|
+
end
|
|
1713
|
+
${MARK_B}
|
|
1714
|
+
`,
|
|
1715
|
+
pwsh: `${MARK_A}
|
|
1716
|
+
function claude {
|
|
1717
|
+
if ($args.Count -eq 0 -and -not $env:HOPDECK_SKIP -and (Get-Command hopdeck -ErrorAction SilentlyContinue)) { hopdeck }
|
|
1718
|
+
else { & (Get-Command claude -CommandType Application | Select-Object -First 1).Source @args }
|
|
1719
|
+
}
|
|
1720
|
+
${MARK_B}
|
|
1721
|
+
`,
|
|
1722
|
+
};
|
|
1723
|
+
|
|
1724
|
+
function stripBlock(txt) {
|
|
1725
|
+
const a = txt.indexOf(MARK_A), b = txt.indexOf(MARK_B);
|
|
1726
|
+
if (a < 0 || b < 0) return txt;
|
|
1727
|
+
return (txt.slice(0, a) + txt.slice(b + MARK_B.length)).replace(/\n{3,}/g, '\n\n').replace(/^\n+/, '');
|
|
1728
|
+
}
|
|
1729
|
+
|
|
1730
|
+
function targets() {
|
|
1731
|
+
// HOPDECK_PROFILES (rutas separadas como las del PATH): perfiles a usar en lugar de los detectados. Pensado para las pruebas.
|
|
1732
|
+
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' }));
|
|
1733
|
+
const list = []; const h = os.homedir();
|
|
1734
|
+
const add = (file, kind) => { if (!list.some((t) => t.file === file)) list.push({ file, kind }); };
|
|
1735
|
+
const sh = process.env.SHELL || '';
|
|
1736
|
+
if (WIN) {
|
|
1737
|
+
for (const exe of ['pwsh', 'powershell']) {
|
|
1738
|
+
try {
|
|
1739
|
+
const out = cp.execSync(`${exe} -NoProfile -Command "$PROFILE.CurrentUserCurrentHost"`, { stdio: ['ignore', 'pipe', 'ignore'], timeout: 8000 }).toString().trim();
|
|
1740
|
+
if (out) add(out, 'pwsh');
|
|
1741
|
+
} catch { /* no instalado */ }
|
|
1742
|
+
}
|
|
1743
|
+
if (fs.existsSync(path.join(h, '.bashrc'))) add(path.join(h, '.bashrc'), 'posix'); // Git Bash
|
|
1744
|
+
} else {
|
|
1745
|
+
if (/zsh/.test(sh) || fs.existsSync(path.join(h, '.zshrc'))) add(path.join(h, '.zshrc'), 'posix');
|
|
1746
|
+
if (/bash/.test(sh) || fs.existsSync(path.join(h, '.bashrc'))) add(path.join(h, '.bashrc'), 'posix');
|
|
1747
|
+
if (/fish/.test(sh)) add(path.join(h, '.config', 'fish', 'conf.d', 'hopdeck.fish'), 'fish');
|
|
1748
|
+
if (!list.length) add(path.join(h, '.bashrc'), 'posix');
|
|
1749
|
+
}
|
|
1750
|
+
return list;
|
|
1751
|
+
}
|
|
1752
|
+
|
|
1753
|
+
/**
|
|
1754
|
+
* Copia de seguridad del perfil de shell antes de tocarlo por primera vez: `<perfil>.hopdeck-backup`.
|
|
1755
|
+
* La primera copia es la original y no se sobrescribe. Si no se puede copiar, lanza el error y el perfil no se modifica.
|
|
1756
|
+
*/
|
|
1757
|
+
function backupProfile(file) {
|
|
1758
|
+
const bak = file + '.hopdeck-backup';
|
|
1759
|
+
if (!fs.existsSync(file) || fs.existsSync(bak)) return null;
|
|
1760
|
+
fs.copyFileSync(file, bak);
|
|
1761
|
+
return bak;
|
|
1762
|
+
}
|
|
1763
|
+
|
|
1764
|
+
/** Añade (o quita, si `remove`) el atajo `claude` de los perfiles de shell. `list`/`quiet` permiten probarlo sin tocar tus perfiles reales. */
|
|
1765
|
+
function install(remove, list = targets(), quiet = false) {
|
|
1766
|
+
const log = (m) => { if (!quiet) console.log(m); };
|
|
1767
|
+
const done = [], baks = [];
|
|
1768
|
+
for (const t of list) {
|
|
1769
|
+
try {
|
|
1770
|
+
let txt = null; try { txt = fs.readFileSync(t.file, 'utf8'); } catch { /* nuevo */ }
|
|
1771
|
+
if (remove && (txt === null || !txt.includes(MARK_A))) continue; // no hay nada que quitar: el archivo no se toca
|
|
1772
|
+
const before = txt || '';
|
|
1773
|
+
let out = stripBlock(before);
|
|
1774
|
+
if (!remove) out = (out && !out.endsWith('\n') ? out + '\n' : out) + (out ? '\n' : '') + SNIP[t.kind];
|
|
1775
|
+
if (out !== before) {
|
|
1776
|
+
const bak = backupProfile(t.file); if (bak) baks.push(bak);
|
|
1777
|
+
fs.mkdirSync(path.dirname(t.file), { recursive: true });
|
|
1778
|
+
fs.writeFileSync(t.file, out);
|
|
1779
|
+
}
|
|
1780
|
+
done.push(t.file);
|
|
1781
|
+
} catch (e) { log(`${C.warn}✗ ${t.file}: ${e.message}${R}`); }
|
|
1782
|
+
}
|
|
1783
|
+
const ok = (s) => `${C.ok}✓${R} ${s}`;
|
|
1784
|
+
baks.forEach((b) => log(ok(T.bakMsg(shortPath(b)))));
|
|
1785
|
+
if (remove) {
|
|
1786
|
+
log(ok(LANG === 'es' ? 'Atajo eliminado. Escribir "claude" vuelve a ser el comportamiento normal.' : 'Shortcut removed. Typing "claude" is back to normal.'));
|
|
1787
|
+
} else {
|
|
1788
|
+
done.forEach((f) => log(ok(shortPath(f))));
|
|
1789
|
+
if (!quiet) tutorial(true);
|
|
1790
|
+
}
|
|
1791
|
+
return { done, baks };
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
// ── Primer arranque: ofrecer que escribir `claude` abra Hopdeck ──
|
|
1795
|
+
const markAsked = () => { CFG.shortcutAsked = true; saveCfg(); };
|
|
1796
|
+
const hasShortcut = (list) => list.some((t) => { try { return fs.readFileSync(t.file, 'utf8').includes(MARK_A); } catch { return false; } });
|
|
1797
|
+
|
|
1798
|
+
/** Espera una tecla; `accept(k)` devuelve el valor a entregar, o undefined para seguir esperando. Ctrl+C sale. */
|
|
1799
|
+
function readKey(accept) {
|
|
1800
|
+
return new Promise((resolve) => {
|
|
1801
|
+
const wasRaw = process.stdin.isRaw;
|
|
1802
|
+
process.stdin.setRawMode(true); process.stdin.resume();
|
|
1803
|
+
const on = (buf) => {
|
|
1804
|
+
const k = buf.toString('utf8');
|
|
1805
|
+
if (k === '\x03') { try { process.stdin.setRawMode(false); } catch { /* */ } process.stdout.write('\n'); process.exit(130); }
|
|
1806
|
+
const v = accept(k);
|
|
1807
|
+
if (v === undefined) return;
|
|
1808
|
+
process.stdin.removeListener('data', on);
|
|
1809
|
+
try { process.stdin.setRawMode(!!wasRaw); } catch { /* */ }
|
|
1810
|
+
process.stdin.pause();
|
|
1811
|
+
resolve(v);
|
|
1812
|
+
};
|
|
1813
|
+
process.stdin.on('data', on);
|
|
1814
|
+
});
|
|
1815
|
+
}
|
|
1816
|
+
|
|
1817
|
+
function askShortcut() {
|
|
1818
|
+
process.stdout.write(`\n ${C.brand}${C.bold}» Hop${R}${C.text}${C.bold}deck${R}\n\n ${C.text}${C.bold}${T.offerQ}${R}\n ${C.dim}${T.offerInfo}${R}\n\n ${C.accent}${T.offerKeys}${R}\n`);
|
|
1819
|
+
return readKey((k) => (k === '\r' || k === '\n' || /^[sSyY]$/.test(k) ? 'yes' : /^[nN]$/.test(k) ? 'no' : k === '\x1b' || /^[mM]$/.test(k) ? 'later' : undefined));
|
|
1820
|
+
}
|
|
1821
|
+
|
|
1822
|
+
/**
|
|
1823
|
+
* La primera vez que se abre Hopdeck pregunta si `claude` a secas debe abrirlo (instala el atajo, con copia de seguridad del perfil).
|
|
1824
|
+
* Solo pregunta una vez ("Más tarde" no cuenta) y nunca si ya está instalado. Devuelve el resultado; `opts` permite probarlo sin terminal.
|
|
1825
|
+
*/
|
|
1826
|
+
async function offerShortcut(opts = {}) {
|
|
1827
|
+
if (CFG.shortcutAsked || process.env.HOPDECK_NOPROMPT) return 'skipped';
|
|
1828
|
+
const list = opts.list || targets();
|
|
1829
|
+
if (hasShortcut(list)) { markAsked(); return 'installed'; }
|
|
1830
|
+
const ans = await (opts.ask || askShortcut)();
|
|
1831
|
+
if (ans === 'no') { markAsked(); return 'no'; }
|
|
1832
|
+
if (ans !== 'yes') return 'later';
|
|
1833
|
+
const r = install(false, list, true);
|
|
1834
|
+
markAsked();
|
|
1835
|
+
if (!opts.quiet) {
|
|
1836
|
+
process.stdout.write(`\n ${r.done.length ? `${C.ok}✓${R} ${T.offerDone}` : `${C.warn}✗${R} ${T.offerFail}`}\n`);
|
|
1837
|
+
r.baks.forEach((b) => process.stdout.write(` ${C.dim}${T.bakMsg(shortPath(b))}${R}\n`));
|
|
1838
|
+
process.stdout.write(`\n ${C.dim}${T.offerCont}${R}`);
|
|
1839
|
+
await readKey(() => true);
|
|
1840
|
+
process.stdout.write('\n');
|
|
1841
|
+
}
|
|
1842
|
+
return r.done.length ? 'yes' : 'failed';
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
function tutorial(afterInstall) {
|
|
1846
|
+
const a = C.accent, d = C.dim, b = C.bold;
|
|
1847
|
+
const L = LANG === 'es' ? [
|
|
1848
|
+
`${C.brand}${b}» Hop${R}${C.text}${b}deck${R} ${d}v${VERSION}${R}`, '',
|
|
1849
|
+
afterInstall ? `${C.ok}Listo.${R} Abre una terminal nueva y escribe ${b}claude${R}.` : `Escribe ${b}hopdeck${R} (o solo ${b}claude${R} si instalaste el atajo).`, '',
|
|
1850
|
+
`${a}1${R} Elige un proyecto con ${a}↑ ↓${R} ${d}(panel izquierdo)${R}`,
|
|
1851
|
+
`${a}2${R} Pulsa ${a}→${R} o ${a}⏎${R} para ver sus conversaciones anteriores`,
|
|
1852
|
+
`${a}3${R} ${a}⏎${R} reanuda una conversación · ${a}+ Nueva${R} o ${a}n${R} empieza una nueva`,
|
|
1853
|
+
`${a}4${R} Al salir de Claude (${d}/exit${R}) vuelves aquí, sin abrir otra terminal`, '',
|
|
1854
|
+
`${d}/ buscar · r recargar · q salir${R}`,
|
|
1855
|
+
`${d}claude con argumentos (claude -p "...", claude --resume) funciona igual que siempre.${R}`,
|
|
1856
|
+
`${d}Desinstalar: hopdeck uninstall${R}`,
|
|
1857
|
+
] : [
|
|
1858
|
+
`${C.brand}${b}» Hop${R}${C.text}${b}deck${R} ${d}v${VERSION}${R}`, '',
|
|
1859
|
+
afterInstall ? `${C.ok}Done.${R} Open a new terminal and type ${b}claude${R}.` : `Type ${b}hopdeck${R} (or just ${b}claude${R} if you installed the shortcut).`, '',
|
|
1860
|
+
`${a}1${R} Pick a project with ${a}↑ ↓${R} ${d}(left pane)${R}`,
|
|
1861
|
+
`${a}2${R} Press ${a}→${R} or ${a}⏎${R} to see its previous conversations`,
|
|
1862
|
+
`${a}3${R} ${a}⏎${R} resumes a conversation · ${a}+ New${R} or ${a}n${R} starts a fresh one`,
|
|
1863
|
+
`${a}4${R} When you exit Claude (${d}/exit${R}) you land back here — no new terminal needed`, '',
|
|
1864
|
+
`${d}/ search · r reload · q quit${R}`,
|
|
1865
|
+
`${d}claude with arguments (claude -p "...", claude --resume) works as usual.${R}`,
|
|
1866
|
+
`${d}Uninstall: hopdeck uninstall${R}`,
|
|
1867
|
+
];
|
|
1868
|
+
console.log('\n' + L.map((x) => ' ' + x).join('\n') + '\n');
|
|
1869
|
+
}
|
|
1870
|
+
|
|
1871
|
+
// ───────────────────────── entrada ─────────────────────────
|
|
1872
|
+
function main() {
|
|
1873
|
+
const [cmd, ...rest] = process.argv.slice(2);
|
|
1874
|
+
if (cmd === 'install') { install(false); markAsked(); }
|
|
1875
|
+
else if (cmd === 'uninstall') { install(true); markAsked(); }
|
|
1876
|
+
else if (cmd === 'help' || cmd === '--help' || cmd === '-h') tutorial(false);
|
|
1877
|
+
else if (cmd === '--version' || cmd === '-v') console.log(VERSION);
|
|
1878
|
+
else if (cmd === '--list') printList();
|
|
1879
|
+
else if (cmd === 'doctor') doctor();
|
|
1880
|
+
else if (cmd === '--idle') idle();
|
|
1881
|
+
else if (cmd === '--frame') { // vista previa de un cuadro (pruebas)
|
|
1882
|
+
load();
|
|
1883
|
+
S.pi = +process.env.HOPDECK_PI || 0; S.focus = +process.env.HOPDECK_FOCUS || 0; S.si = +process.env.HOPDECK_SI || 0;
|
|
1884
|
+
const c = +process.env.COLUMNS || 100, r = +process.env.LINES || 28;
|
|
1885
|
+
if (process.env.HOPDECK_TREE) { S.open = S.projects[1] && S.projects[1].key; S.c = +process.env.HOPDECK_C || 0; console.log(frameTree(c, r).join('\n')); }
|
|
1886
|
+
else console.log(frame(c, r).join('\n'));
|
|
1887
|
+
} else {
|
|
1888
|
+
extraArgs.push(...[cmd, ...rest].filter((a) => a && a !== '--sidebar'));
|
|
1889
|
+
run().catch((e) => { try { leave(); } catch { /* */ } console.error(e); process.exit(1); });
|
|
1890
|
+
}
|
|
1891
|
+
}
|
|
1892
|
+
|
|
1893
|
+
if (require.main === module) main();
|
|
1894
|
+
else {
|
|
1895
|
+
// al hacer require() (pruebas automáticas) no se ejecuta nada: solo se exponen las piezas puras
|
|
1896
|
+
module.exports = {
|
|
1897
|
+
cw, strW, fit, clean, imageExt, exportImages, safeId, findClaude, install, backupProfile, ago, tidy, fuzzy, wrapText, parseKeys, KEYMAP, isType, T, S, CFG, E,
|
|
1898
|
+
readSession, buildProject, scan, scanAsync, finishScan, sortProjects, projectDirs,
|
|
1899
|
+
view, flatList, stripBlock, offerShortcut, SNIP, MARK_A, MARK_B, toggleProject, cacheLoad, selNorm,
|
|
1900
|
+
decodePNG, decodeImage, scaleBox, fitSize, halfBlocks, collectImages, extractImages,
|
|
1901
|
+
editBuf, normalizeKeys, stripJsonc, wtCtrlV, fbNames, fbOpen, fbRows, sidebarMouse, gitBranch, linkChats, findImageByNumber: images.findImageByNumber,
|
|
1902
|
+
};
|
|
1903
|
+
}
|