hopdeck 1.5.4 → 1.5.6

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 CHANGED
@@ -1,5 +1,17 @@
1
1
  # Cambios
2
2
 
3
+ ## 1.5.6
4
+
5
+ ### Documentación y comprobaciones
6
+ - Instalación con pnpm documentada en español e inglés, con instrucciones para configurar la carpeta global y una nota sobre la espera de pnpm 12 para versiones recién publicadas.
7
+ - Verificación automática de la instalación global del paquete publicado en Windows, Linux y macOS Intel, con Node 22/24 y pnpm 10.32.1/12.21.0. Comprueba el comando global, el terminal integrado de Claude y Codex, la reanudación, la entrada de texto y el cierre.
8
+
9
+ ## 1.5.5
10
+
11
+ ### Arreglado
12
+ - Un clic sobre una URL `http://` o `https://` del chat abre el navegador predeterminado, también cuando el enlace ocupa varias líneas. Funciona en Claude y Codex; arrastrar sigue seleccionando texto.
13
+ - Imágenes en el modo Codex: galería con `i` / `F7`, vista previa al pasar el cursor por `[Image #N]` y apertura con clic. Se leen adjuntos del historial y archivos locales, con soporte para la API anterior de Codex y para la numeración que vuelve a empezar en cada mensaje. Los mensajes que solo contienen imágenes también aparecen en la vista previa de la conversación.
14
+
3
15
  ## 1.5.4
4
16
 
5
17
  ### Nuevo
package/README.en.md CHANGED
@@ -33,7 +33,9 @@ hopdeck shortcut on
33
33
 
34
34
  Existing users can run `hopdeck shortcut on` again and open a new terminal to add the Codex shortcut. From a source checkout, run `npm link` first to point the global command at the local version.
35
35
 
36
- **First Codex version:** projects, conversations, previews, project/title/first-message search, new and resumed chats, multiple live chats and the Git panel. Requires an installed `codex` supporting `codex app-server`. Hopdeck reads history through its local API and resumes with `codex resume <ID>`; it does not edit Codex databases. Custom titles and archives are local to Hopdeck (`~/.hopdeck-codex.json`). Image galleries, statistics and full-content search remain available in Claude mode; Codex activity indicators are basic and depend on its terminal text.
36
+ **Codex mode:** projects, conversations, previews, images, project/title/first-message search, new and resumed chats, multiple live chats and the Git panel. Requires an installed `codex` supporting `codex app-server`. Hopdeck reads history through its local API and resumes with `codex resume <ID>`; it does not edit Codex databases. Custom titles and archives are local to Hopdeck (`~/.hopdeck-codex.json`). Statistics and full-content search remain available in Claude mode; Codex activity indicators are basic and depend on its terminal text.
37
+
38
+ In Codex, `i` / `F7` opens the gallery and `[Image #N]` markers support hover previews and full-size clicks. Images come from saved history attachments and local files that still exist. Remote URLs and attachments exposed only as `fileId` are not downloaded. Deleted files and images that have not been sent yet cannot be previewed.
37
39
 
38
40
  <picture>
39
41
  <source media="(prefers-color-scheme: light)" srcset="docs/screenshots/02-vista-dividida-light.svg">
@@ -69,6 +71,15 @@ npm install -g hopdeck
69
71
  hopdeck
70
72
  ```
71
73
 
74
+ You can also install it with pnpm:
75
+
76
+ ```bash
77
+ pnpm add -g hopdeck@latest
78
+ hopdeck
79
+ ```
80
+
81
+ If pnpm asks you to configure its global directory, run `pnpm setup` and open a new terminal. pnpm 12 may select the previous version during its default 24-hour waiting period for newly published releases.
82
+
72
83
  The first time you open each Hopdeck mode, a welcome screen shows the version and the commands to get started. Press `Enter` to continue or `Esc` to skip it; it will not appear again in that mode. The usual shortcut question follows. It does not appear with `--version`, `--help`, `--list`, in CI, or with `HOPDECK_NOPROMPT=1`. Installation remains `npm install -g hopdeck`, with no extra options.
73
84
 
74
85
  Done. You can also try it without installing: `npx hopdeck`.
@@ -166,6 +177,8 @@ It always starts at `~`. Recently used folders appear on top (`↻ recent`).
166
177
 
167
178
  ### Images in the chat
168
179
 
180
+ In Claude and Codex chats, click an `http://` or `https://` URL to open your default browser. Links wrapped across lines also work; dragging over text still selects it.
181
+
169
182
  <picture>
170
183
  <source media="(prefers-color-scheme: light)" srcset="docs/screenshots/04-hover-imagen-light.svg">
171
184
  <img alt="Floating box with the image when hovering [Image #1]" src="docs/screenshots/04-hover-imagen.svg">
package/README.md CHANGED
@@ -33,7 +33,9 @@ hopdeck shortcut on
33
33
 
34
34
  Si ya tenías el atajo de Claude, ejecuta otra vez `hopdeck shortcut on` y abre una terminal nueva para añadir el de Codex. Desde una copia del repositorio, usa primero `npm link` para actualizar el comando global con tu código local.
35
35
 
36
- **Primera versión de Codex:** lista proyectos y conversaciones, vista previa, búsqueda por proyecto/título/primer mensaje, chats nuevos y reanudados, varios chats abiertos y panel de Git. Necesita `codex` instalado y con soporte para `codex app-server`. Hopdeck consulta el historial mediante su API local y reanuda con `codex resume <ID>`; no modifica las bases de datos de Codex. Los nombres personalizados y archivados se guardan solo en Hopdeck (`~/.hopdeck-codex.json`). La galería de imágenes, estadísticas y búsqueda en el contenido completo quedan disponibles en el modo Claude; los indicadores de actividad de Codex son básicos y dependen del texto de su terminal.
36
+ **Modo Codex:** lista proyectos y conversaciones, vista previa, imágenes, búsqueda por proyecto/título/primer mensaje, chats nuevos y reanudados, varios chats abiertos y panel de Git. Necesita `codex` instalado y con soporte para `codex app-server`. Hopdeck consulta el historial mediante su API local y reanuda con `codex resume <ID>`; no modifica las bases de datos de Codex. Los nombres personalizados y archivados se guardan solo en Hopdeck (`~/.hopdeck-codex.json`). Las estadísticas y la búsqueda en el contenido completo quedan disponibles en el modo Claude; los indicadores de actividad de Codex son básicos y dependen del texto de su terminal.
37
+
38
+ En Codex, `i` / `F7` abre la galería y las marcas `[Image #N]` permiten previsualizar con el cursor o abrir con clic. Se leen los adjuntos guardados en el historial y los archivos locales que sigan existiendo. Las URL remotas y los adjuntos que Codex solo identifica mediante `fileId` no se descargan. Un archivo borrado o una imagen aún sin enviar no tiene vista previa.
37
39
 
38
40
  <picture>
39
41
  <source media="(prefers-color-scheme: light)" srcset="docs/screenshots/02-vista-dividida-light.svg">
@@ -69,6 +71,15 @@ npm install -g hopdeck
69
71
  hopdeck
70
72
  ```
71
73
 
74
+ También puedes instalarlo con pnpm:
75
+
76
+ ```bash
77
+ pnpm add -g hopdeck@latest
78
+ hopdeck
79
+ ```
80
+
81
+ Si pnpm pide configurar su carpeta global, ejecuta `pnpm setup` y abre una terminal nueva. pnpm 12 puede seleccionar la versión anterior durante su espera predeterminada de 24 horas para versiones recién publicadas.
82
+
72
83
  Al abrir cada modo de Hopdeck por primera vez aparece una bienvenida con la versión y los comandos para empezar. Pulsa `Enter` para continuar o `Esc` para omitirla; después no vuelve a aparecer en ese modo. Sigue la pregunta habitual de los atajos. No se muestra con `--version`, `--help`, `--list`, en CI ni con `HOPDECK_NOPROMPT=1`. La instalación sigue siendo `npm install -g hopdeck`, sin opciones adicionales.
73
84
 
74
85
  Listo. También puedes probarlo sin instalar: `npx hopdeck`.
@@ -166,6 +177,8 @@ Empieza siempre en `~`. Las carpetas que usaste hace poco aparecen arriba (`↻
166
177
 
167
178
  ### Imágenes del chat
168
179
 
180
+ En los chats de Claude y Codex, un clic sobre una URL `http://` o `https://` abre el navegador predeterminado. También reconoce enlaces partidos entre líneas; arrastrar sobre el texto permite seleccionarlo.
181
+
169
182
  <picture>
170
183
  <source media="(prefers-color-scheme: light)" srcset="docs/screenshots/04-hover-imagen-light.svg">
171
184
  <img alt="Cuadro flotante con la imagen al pasar el cursor por [Image #1]" src="docs/screenshots/04-hover-imagen.svg">
package/SECURITY.md CHANGED
@@ -3,6 +3,7 @@
3
3
  ## Qué hace (y qué no) este programa con tus datos
4
4
 
5
5
  - Lee el historial local de Claude Code (`~/.claude/projects`, o `CLAUDE_CONFIG_DIR`). En modo Codex, consulta `thread/list` y las vistas previas mediante `codex app-server` por stdin/stdout; no abre puertos ni modifica sus bases de datos. Hopdeck no añade telemetría, analítica ni peticiones de red propias. Las CLI de Claude y Codex conservan sus conexiones y ajustes habituales.
6
+ - Las imágenes de Codex se leen de sus adjuntos en la API local o de los archivos locales referenciados. Solo se aceptan archivos regulares con cabeceras de imagen reconocidas, de hasta 18 MB por imagen; no se descargan URL remotas ni se abren rutas de red.
6
7
  - Escribe solo en tu equipo:
7
8
  - `~/.hopdeck.json` (preferencias: proyectos fijados, ocultos, recientes…) y `~/.hopdeck-cache.json` (índice de títulos y primeros mensajes, con permisos solo para tu usuario).
8
9
  - `~/.hopdeck-codex.json` para las preferencias, títulos personalizados y archivados locales del modo Codex. Renombrar o archivar aquí no cambia las conversaciones de Codex.
@@ -12,6 +13,7 @@
12
13
  - Al renombrar una conversación (`R`), añade una línea `custom-title` al final de su archivo `.jsonl`, igual que hace Claude Code.
13
14
  - Ejecuta el comando `claude` o `codex` que encuentre en tu `PATH`. Si alguien puede cambiar tu `PATH`, puede cambiar qué se ejecuta (como con cualquier programa).
14
15
  - Lo que se muestra en pantalla procedente del historial (títulos, mensajes, rutas) se limpia de caracteres de control y secuencias de escape antes de dibujarse.
16
+ - Un clic sobre una URL del chat abre el navegador predeterminado. Solo se aceptan enlaces HTTP/HTTPS, que se pasan como un argumento al programa del sistema sin usar un intérprete de comandos.
15
17
 
16
18
  ## Versiones con soporte
17
19
 
package/bin/hopdeck.js CHANGED
@@ -25,6 +25,7 @@ const { baseName, tidy, home, shortPath, fold, queryWords, matchWords, fuzzy, wr
25
25
  const hist = require('../lib/history');
26
26
  const { CONFIG_DIR, CACHE_FILE, textOf, isType, cacheLoad, cacheSave, readSession, decodeDir, projectDirs, buildProject, beginScan, endScan } = hist;
27
27
  const images = require('../lib/images');
28
+ const { urlAt, openUrl } = require('../lib/links');
28
29
  const { encodeSixel } = require('../lib/sixel');
29
30
  const gitlib = require('../lib/git');
30
31
  const deepsearch = require('../lib/deepsearch');
@@ -1106,12 +1107,12 @@ const previewMsgs = () => (CFG.previewMsgs > 0 ? CFG.previewMsgs : 12);
1106
1107
  const extractImages = (file) => images.extractImages(file, maxImages());
1107
1108
 
1108
1109
  async function imagesOf(x) {
1109
- if (provider.isCodex) return [];
1110
- const hit = IMG.get(x.file);
1111
- if (hit && hit.m === x.mtime) return hit.images;
1112
- const images = await extractImages(x.file);
1113
- IMG.set(x.file, { m: x.mtime, images });
1114
- return images;
1110
+ const key = provider.isCodex ? 'codex:' + x.id : x.file, hit = IMG.get(key);
1111
+ if (hit && hit.m === x.mtime && Date.now() < hit.until) return hit.images;
1112
+ const entry = { m: x.mtime, until: provider.isCodex ? Date.now() + 2000 : Infinity,
1113
+ images: provider.isCodex ? codexHistory.imagesSession(x, maxImages()) : extractImages(x.file) };
1114
+ IMG.set(key, entry);
1115
+ try { return await entry.images; } catch (err) { if (IMG.get(key) === entry) IMG.delete(key); throw err; }
1115
1116
  }
1116
1117
 
1117
1118
  /** Abre un archivo o carpeta con el programa por defecto del sistema. */
@@ -1263,10 +1264,11 @@ function hoverPopup(hv, rw, th) {
1263
1264
  }
1264
1265
 
1265
1266
  /** La imagen que corresponde a "[Image #n]" en la conversación de este chat, o null si aún no está en el historial. */
1266
- async function imageForMarker(sh, n) {
1267
+ async function imageForMarker(sh, n, y) {
1267
1268
  try {
1268
1269
  const sess = await shownSession(sh);
1269
1270
  if (!sess) return null;
1271
+ if (provider.isCodex) return await codexHistory.imageForNumber(sess, n, codexMarkerOffset(sh.term, y, n));
1270
1272
  const imgs = await imagesOf(sess);
1271
1273
  let img = imgs.find((im) => im.n === n) || (imgs.some((im) => im.n) ? null : imgs[n - 1]) || null;
1272
1274
  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
@@ -1274,12 +1276,24 @@ async function imageForMarker(sh, n) {
1274
1276
  } catch { return null; }
1275
1277
  }
1276
1278
 
1279
+ // Codex restarts image numbering in each user message. Count from the end of the
1280
+ // terminal transcript so older visible messages resolve to their own attachment.
1281
+ function codexMarkerOffset(term, y, n) {
1282
+ if (!Number.isInteger(y)) return 0;
1283
+ const b = term.buffer.active; let count = 0;
1284
+ for (let row = b.viewportY + y + 1; row < b.length; row++) {
1285
+ const text = b.getLine(row)?.translateToString(true) || '';
1286
+ for (const match of text.matchAll(/\[Image\s*#(\d+)\]/g)) if (+match[1] === n) count++;
1287
+ }
1288
+ return count;
1289
+ }
1290
+
1277
1291
  /**
1278
1292
  * Clic en un "[Image #N]": abre esa imagen en el visor del sistema, a su tamaño real. En el terminal solo se puede dibujar una
1279
1293
  * vista rápida (dos píxeles por carácter): una captura de pantalla con texto de 1917 px de ancho queda en unos 50 y no se lee.
1280
1294
  */
1281
- async function openMarkerImage(sh, n) {
1282
- const img = await imageForMarker(sh, n);
1295
+ async function openMarkerImage(sh, n, y) {
1296
+ const img = await imageForMarker(sh, n, y);
1283
1297
  const note = (t) => { E.note = { t, until: Date.now() + 2500 }; scheduleRender(); };
1284
1298
  if (!img) return note(T.hoverMiss(n));
1285
1299
  const { files } = exportImages([img]);
@@ -1296,12 +1310,12 @@ function hoverChat(sh, x, y) {
1296
1310
  if (hit) { n = hit.n; at = { x: hit.x, y: y - 3 }; }
1297
1311
  }
1298
1312
  if (!n) { if (E.hover) { E.hover = null; scheduleRender(); } return; }
1299
- const k = `${n}:${at.x}:${at.y}`;
1313
+ const k = `${sh.sid || sh.t0}:${n}:${at.x}:${at.y}:${sh.term.buffer.active.viewportY}`;
1300
1314
  if (E.hover && E.hover.k === k) return;
1301
1315
  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() } };
1302
1316
  E.hover = hv; scheduleRender();
1303
1317
  (async () => {
1304
- const img = await imageForMarker(sh, n);
1318
+ const img = await imageForMarker(sh, n, at.y);
1305
1319
  if (E.hover !== hv) return; // el cursor ya se fue
1306
1320
  if (!img) { hv.g.loading = false; E.note = { t: T.hoverMiss(n), until: Date.now() + 2000 }; return scheduleRender(); }
1307
1321
  hv.g.images = [img]; hv.g.loading = false; scheduleRender();
@@ -1691,7 +1705,7 @@ function sidebarMouse(b, x, y, type, rows = process.stdout.rows || 30) {
1691
1705
 
1692
1706
  function onMouse(b, x, y, type) {
1693
1707
  if (E.gallery) return;
1694
- const { SW, GW, rw, rh } = embedLayout();
1708
+ const { SW, GW, rw, rh, th } = embedLayout();
1695
1709
  const sh = E.sessions.get(E.shown);
1696
1710
  // líneas divisorias arrastrables (columna de cada '│'): lista|chat y chat|git
1697
1711
  const sx = SW ? SW + 1 : 0, gx = GW ? sx + rw + 1 : 0;
@@ -1720,20 +1734,24 @@ function onMouse(b, x, y, type) {
1720
1734
  if (L[i] && i !== S.c) { S.c = i; scheduleRender(); }
1721
1735
  return;
1722
1736
  }
1723
- const x0 = SW ? SW + 2 : 1, inPane = (SW ? x > SW + 1 : true) && y >= 3 && sh && sh.ready;
1737
+ const x0 = SW ? SW + 2 : 1, inPane = (SW ? x > SW + 1 : true) && y >= 3 && y < th + 3 && sh && sh.ready;
1724
1738
  // celda del chat bajo el ratón; `y` es la línea del historial (ver selRange), así que sirve aunque el chat esté desplazado
1725
1739
  const cell = () => { const L = embedLayout(); return { x: clamp(x - x0, 0, L.rw - 1), y: sh.term.buffer.active.viewportY + clamp(y - 3, 0, L.th - 1) }; };
1726
1740
  if ((b & 32) && (b & 3) === 0) { // arrastre
1727
- if (E.sel && E.sel.down && sh) { E.sel.b = cell(); selEdge(sh, y - 3); render(); }
1741
+ if (E.sel && E.sel.down && sh) { E.sel.b = cell(); if (E.sel.a.x !== E.sel.b.x || E.sel.a.y !== E.sel.b.y) E.sel.moved = true; selEdge(sh, y - 3); render(); }
1728
1742
  return;
1729
1743
  }
1730
1744
  if (type === 'm') { // soltar
1731
1745
  stopSelScroll();
1732
1746
  const sl = E.sel;
1733
1747
  if (!sl || !sl.down) return render();
1734
- if (sl.a.x === sl.b.x && sl.a.y === sl.b.y) { // un clic sin arrastrar: si es sobre un [Image #N], se abre la imagen
1748
+ if (!sl.moved && sl.a.x === sl.b.x && sl.a.y === sl.b.y) { // clic: imágenes y enlaces web; arrastrar sigue seleccionando texto
1735
1749
  E.sel = null;
1736
- if (sh && sh.ready) { const hit = imageMarkerAt(sh.term, sl.a.y - sh.term.buffer.active.viewportY, sl.a.x); if (hit) openMarkerImage(sh, hit.n); }
1750
+ if (sh && sh.ready) {
1751
+ const row = sl.a.y - sh.term.buffer.active.viewportY, hit = imageMarkerAt(sh.term, row, sl.a.x);
1752
+ if (hit) openMarkerImage(sh, hit.n, row);
1753
+ else { const url = urlAt(sh.term, row, sl.a.x); if (url && openUrl(url)) E.note = { t: T.linkOpened, until: Date.now() + 2500 }; }
1754
+ }
1737
1755
  return render();
1738
1756
  }
1739
1757
  sl.down = false; // la selección se queda marcada: no se copia sola (se copia con Ctrl+C o clic derecho), salvo con "copyOnSelect": true
@@ -2471,6 +2489,6 @@ else {
2471
2489
  readSession, buildProject, scan, scanAsync, finishScan, sortProjects, projectDirs,
2472
2490
  view, flatList, stripBlock, offerShortcut, uninstallAll, commandName, suggestCommand, parseTermReplies, sixelOn, SNIP, MARK_A, MARK_B, toggleProject, cacheLoad, selNorm,
2473
2491
  decodePNG, decodeImage, scaleBox, fitSize, halfBlocks, collectImages, extractImages,
2474
- onMouse, dragPanel, panelLimits, embedLayout, sessTag, editBuf, normalizeKeys, stripJsonc, wtCtrlV, fbNames, fbOpen, fbRows, sidebarMouse, toggleTheme, gitBranch, imageMarkerAt, shownSession, linkChats, findImageByNumber: images.findImageByNumber,
2492
+ onMouse, dragPanel, panelLimits, embedLayout, sessTag, editBuf, normalizeKeys, stripJsonc, wtCtrlV, fbNames, fbOpen, fbRows, sidebarMouse, toggleTheme, gitBranch, imageMarkerAt, codexMarkerOffset, shownSession, linkChats, findImageByNumber: images.findImageByNumber,
2475
2493
  };
2476
2494
  }
@@ -4,6 +4,9 @@ const cp = require('child_process');
4
4
  const readline = require('readline');
5
5
  const os = require('os');
6
6
  const path = require('path');
7
+ const fs = require('fs');
8
+ const { fileURLToPath } = require('url');
9
+ const { sniffExt } = require('./images');
7
10
  const { findExecutable } = require('./executable');
8
11
  const { baseName, tidy } = require('./text');
9
12
 
@@ -124,7 +127,12 @@ async function listProjects(client, onProgress) {
124
127
  function messagesFromItems(items) {
125
128
  return items.flatMap((item) => {
126
129
  let role, text;
127
- if (item.type === 'userMessage') { role = 'user'; text = (item.content || []).filter((c) => c.type === 'text').map((c) => c.text).join('\n'); }
130
+ if (item.type === 'userMessage') {
131
+ role = 'user'; text = (item.content || []).filter((c) => c.type === 'text').map((c) => c.text).join('\n');
132
+ const count = (item.content || []).filter((c) => c.type === 'image' || c.type === 'localImage').length;
133
+ const labels = Array.from({ length: count }, (_, i) => `[Image #${i + 1}]`).filter((label) => !text.includes(label));
134
+ text = [...labels, text].filter(Boolean).join('\n');
135
+ }
128
136
  else if (item.type === 'agentMessage') { role = 'assistant'; text = item.text; }
129
137
  if (!role || typeof text !== 'string' || !text.trim()) return [];
130
138
  return [{ role, text: tidy(text).slice(0, 700) }];
@@ -150,6 +158,97 @@ async function preview(client, session, limit = 12) {
150
158
  }
151
159
  }
152
160
 
161
+ // Read attachments through the same public history API. Never fetch remote image URLs.
162
+ const MAX_IMAGE_BYTES = 18 * 1024 * 1024;
163
+ async function readImage(ref, cwd) {
164
+ let bytes, file;
165
+ if (typeof ref.url === 'string' && ref.url.startsWith('data:')) {
166
+ if (ref.url.length > MAX_IMAGE_BYTES * 4 / 3 + 128) return null;
167
+ const match = /^data:image\/[a-z0-9.+-]+;base64,([a-z0-9+/=\r\n]+)$/i.exec(ref.url);
168
+ if (!match) return null;
169
+ bytes = Buffer.from(match[1], 'base64');
170
+ } else {
171
+ try {
172
+ file = ref.path || (typeof ref.url === 'string' && ref.url.startsWith('file:') ? fileURLToPath(ref.url) : null);
173
+ if (!file || /\0/.test(file) || /^[/\\]{2}/.test(file)) return null;
174
+ if (!path.isAbsolute(file)) { if (!cwd || !path.isAbsolute(cwd)) return null; file = path.resolve(cwd, file); }
175
+ const handle = await fs.promises.open(file, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK || 0));
176
+ try {
177
+ const stat = await handle.stat();
178
+ if (!stat.isFile() || stat.size > MAX_IMAGE_BYTES || stat.size < 13) return null;
179
+ const header = Buffer.alloc(16); await handle.read(header, 0, header.length, 0);
180
+ if (sniffExt(header) === 'img' && header.toString('latin1', 0, 2) !== 'BM') return null;
181
+ // Bound the read even if the file grows after stat().
182
+ bytes = Buffer.alloc(stat.size); let offset = 0;
183
+ while (offset < bytes.length) { const read = await handle.read(bytes, offset, bytes.length - offset, offset); if (!read.bytesRead) break; offset += read.bytesRead; }
184
+ bytes = bytes.subarray(0, offset);
185
+ } finally { await handle.close(); }
186
+ } catch { return null; }
187
+ }
188
+ if (!bytes || bytes.length > MAX_IMAGE_BYTES) return null;
189
+ const ext = sniffExt(bytes), bmp = bytes.toString('latin1', 0, 2) === 'BM';
190
+ if (ext === 'img' && !bmp) return null;
191
+ return { data: bytes.toString('base64'), media: `image/${bmp ? 'bmp' : ext === 'jpg' ? 'jpeg' : ext}` };
192
+ }
193
+
194
+ async function* attachmentItems(client, session, sortDirection = 'asc') {
195
+ let page;
196
+ try { page = await client.request('thread/items/list', { threadId: session.id, limit: 50, sortDirection, cursor: null }); }
197
+ catch (err) {
198
+ if (err.code !== -32601 && !/unknown method|unknown variant|unsupported|not found/i.test(err.message)) throw err;
199
+ const result = await client.request('thread/read', { threadId: session.id, includeTurns: true });
200
+ const items = (result.thread?.turns || []).flatMap((turn) => turn.items || []);
201
+ for (const item of sortDirection === 'desc' ? items.reverse() : items) yield item;
202
+ return;
203
+ }
204
+ const cursors = new Set(), ids = new Set();
205
+ while (true) {
206
+ for (const entry of page.data || []) {
207
+ const item = entry.item || entry;
208
+ if (item.id && ids.has(item.id)) continue;
209
+ if (item.id) ids.add(item.id);
210
+ yield item;
211
+ }
212
+ if (!page.nextCursor) return;
213
+ if (cursors.has(page.nextCursor)) throw new Error('Codex returned a repeated image history cursor');
214
+ cursors.add(page.nextCursor);
215
+ page = await client.request('thread/items/list', { threadId: session.id, limit: 50, sortDirection, cursor: page.nextCursor });
216
+ }
217
+ }
218
+
219
+ function attachments(item) {
220
+ if (item.type === 'userMessage') {
221
+ const content = item.content || [];
222
+ // Codex's TUI numbers remote inputs first, then local inputs, starting at 1 per message.
223
+ return [...content.filter((c) => c.type === 'image'), ...content.filter((c) => c.type === 'localImage')]
224
+ .map((ref, i) => ({ ...ref, n: i + 1 }));
225
+ }
226
+ if (item.type === 'imageView') return [{ path: item.path }];
227
+ if (item.type === 'imageGeneration' && item.status === 'completed') {
228
+ return [item.savedPath ? { path: item.savedPath } : { url: typeof item.result === 'string' ? 'data:image/png;base64,' + item.result : undefined }];
229
+ }
230
+ return [];
231
+ }
232
+
233
+ async function sessionImages(client, session, max = 200) {
234
+ const out = []; let bytes = 0;
235
+ for await (const item of attachmentItems(client, session)) for (const ref of attachments(item)) {
236
+ const image = await readImage(ref, session.cwd);
237
+ if (!image) continue;
238
+ out.push({ ...image, ...(ref.n ? { n: ref.n } : {}) }); bytes += image.data.length;
239
+ if (out.length >= max || bytes >= 64e6) return out;
240
+ }
241
+ return out;
242
+ }
243
+
244
+ async function findSessionImage(client, session, n, fromEnd = 0) {
245
+ if (!Number.isSafeInteger(n) || n < 1 || !Number.isSafeInteger(fromEnd) || fromEnd < 0) return null;
246
+ for await (const item of attachmentItems(client, session, 'desc')) for (const ref of attachments(item)) if (ref.n === n) {
247
+ if (fromEnd-- === 0) return readImage(ref, session.cwd);
248
+ }
249
+ return null;
250
+ }
251
+
153
252
  let client;
154
253
  const getClient = () => client || (client = new CodexClient());
155
254
  const close = () => { if (client) client.close(); client = null; };
@@ -161,9 +260,11 @@ function scanSync() {
161
260
  return JSON.parse(result.stdout);
162
261
  }
163
262
  module.exports = {
164
- CodexClient, isCodexThread, groupThreads, listProjects, messagesFromItems, preview, scanSync, close,
263
+ CodexClient, isCodexThread, groupThreads, listProjects, messagesFromItems, preview, sessionImages, findSessionImage, scanSync, close,
165
264
  scanProjectsAsync: (progress) => listProjects(getClient(), progress),
166
265
  previewSession: (session, limit) => preview(getClient(), session, limit),
266
+ imagesSession: (session, max) => sessionImages(getClient(), session, max),
267
+ imageForNumber: (session, n, fromEnd) => findSessionImage(getClient(), session, n, fromEnd),
167
268
  CONFIG_DIR: process.env.CODEX_HOME || path.join(os.homedir(), '.codex'),
168
269
  };
169
270
  if (require.main === module) {
package/lib/i18n.js CHANGED
@@ -15,6 +15,7 @@ const T = {
15
15
  pressKey: 'Pulsa una tecla para volver…',
16
16
  exited: (c) => `La conversación terminó (código ${c})`, closed: (t) => `Conversación cerrada: ${t}`, confirmClose: 'Está trabajando. Pulsa c otra vez para cerrarla', notOpen: 'No hay ninguna conversación abierta que cerrar',
17
17
  noImages: 'Esta conversación no tiene imágenes', findImgs: 'Buscando imágenes…', decoding: 'Preparando imagen…',
18
+ linkOpened: 'Enlace abierto en el navegador',
18
19
  imgNoPrev: 'No se puede previsualizar este formato', imgHint: '← → navegar o abrir en el visor esc cerrar', imgFolder: 'Imágenes abiertas en el visor',
19
20
  more: (n) => `mostrar ${n} más…`, busyRename: 'Cierra la conversación antes de renombrarla', renameLbl: 'nombre',
20
21
  copied: (n) => `Copiado (${n} caracteres)`, archMsg: 'Archivada (H para verlas)', unarchMsg: 'Desarchivada', qsHint: 'saltar a cualquier conversación',
@@ -63,6 +64,7 @@ const T = {
63
64
  pressKey: 'Press any key to go back…',
64
65
  exited: (c) => `The conversation ended (code ${c})`, closed: (t) => `Conversation closed: ${t}`, confirmClose: 'It is working. Press c again to close it', notOpen: 'There is no open conversation to close',
65
66
  noImages: 'This conversation has no images', findImgs: 'Looking for images…', decoding: 'Preparing image…',
67
+ linkOpened: 'Link opened in the browser',
66
68
  imgNoPrev: 'This format cannot be previewed', imgHint: '← → browse o open in viewer esc close', imgFolder: 'Images opened in the viewer',
67
69
  more: (n) => `show ${n} more…`, busyRename: 'Close the conversation before renaming it', renameLbl: 'name',
68
70
  copied: (n) => `Copied (${n} chars)`, archMsg: 'Archived (H to show)', unarchMsg: 'Unarchived', qsHint: 'jump to any conversation',
@@ -110,7 +112,6 @@ if (require('./provider').isCodex) {
110
112
  else if (Array.isArray(value)) T[key] = value.map(adapt);
111
113
  }
112
114
  T.tryContent = LANG === 'es' ? 'Busca por proyecto, título o primer mensaje' : 'Search projects, titles or first messages';
113
- T.noImages = LANG === 'es' ? 'La galería de imágenes aún no está disponible en el modo Codex' : 'Image galleries are not available in Codex mode yet';
114
115
  }
115
116
  T.offerQ = LANG === 'es' ? '¿Quieres abrir Hopdeck escribiendo claude o codex?' : 'Do you want to open Hopdeck by typing claude or codex?';
116
117
  T.dcShort = LANG === 'es' ? 'Atajos instalados: "claude" y "codex" abren Hopdeck' : 'Shortcuts installed: "claude" and "codex" open Hopdeck';
package/lib/links.js ADDED
@@ -0,0 +1,56 @@
1
+ 'use strict';
2
+ const cp = require('child_process');
3
+ const fs = require('fs');
4
+
5
+ function webUrl(text) {
6
+ if (typeof text !== 'string' || text.length > 8192 || !/^https?:\/\//i.test(text) || /[\s\x00-\x1f\x7f]/u.test(text)) return null;
7
+ try { const url = new URL(text); return url.protocol === 'http:' || url.protocol === 'https:' ? url.href : null; } catch { return null; }
8
+ }
9
+
10
+ // Map terminal cells to text offsets, including wide Unicode characters and soft wraps.
11
+ function urlAt(term, y, col) {
12
+ const buffer = term.buffer.active, row = buffer.viewportY + y, line = buffer.getLine(row);
13
+ if (!line || col < 0 || col >= term.cols) return null;
14
+ const maxRows = Math.max(1, Math.ceil(16384 / term.cols)); let start = row, end = row;
15
+ while (start > 0 && row - start < maxRows && buffer.getLine(start)?.isWrapped) start--;
16
+ while (end + 1 < buffer.length && end - start < maxRows && buffer.getLine(end + 1)?.isWrapped) end++;
17
+ let text = '', offset = -1;
18
+ for (let r = start; r <= end; r++) {
19
+ const current = buffer.getLine(r);
20
+ for (let c = 0; c < term.cols; c++) {
21
+ const cell = current.getCell(c); if (!cell || cell.getWidth() === 0) continue;
22
+ if (r === row && col >= c && col < c + cell.getWidth()) offset = text.length;
23
+ text += cell.getChars() || ' ';
24
+ }
25
+ }
26
+ if (offset < 0) return null;
27
+ for (const match of text.matchAll(/https?:\/\/[^\s<>"`\x00-\x1f\x7f]+/gi)) {
28
+ let raw = match[0];
29
+ // Sentence punctuation and Markdown delimiters are outside the URL. Keep balanced URL parentheses.
30
+ while (true) {
31
+ const previous = raw;
32
+ raw = raw.replace(/[.,;:!?'…。,;:!?]+$/u, '');
33
+ for (const [open, close] of [['(', ')'], ['[', ']'], ['{', '}']]) {
34
+ if (raw.endsWith(close) && raw.split(close).length > raw.split(open).length) raw = raw.slice(0, -1);
35
+ }
36
+ if (raw === previous) break;
37
+ }
38
+ if (offset >= match.index && offset < match.index + raw.length) return webUrl(raw);
39
+ }
40
+ return null;
41
+ }
42
+
43
+ function openUrl(text, { platform = process.platform, env = process.env, spawn = cp.spawn } = {}) {
44
+ const url = webUrl(text); if (!url) return false;
45
+ if (env.HOPDECK_OPEN_LOG) {
46
+ try { fs.appendFileSync(env.HOPDECK_OPEN_LOG, url + '\n'); return true; } catch { return false; }
47
+ }
48
+ // URLs never enter cmd.exe or a shell: &, %, quotes and other URL characters stay data.
49
+ const command = platform === 'win32' || env.WSL_DISTRO_NAME ? 'explorer.exe' : platform === 'darwin' ? 'open' : 'xdg-open';
50
+ try {
51
+ const child = spawn(command, [url], { stdio: 'ignore', detached: true, windowsHide: true, shell: false });
52
+ child.on('error', () => {}); child.unref(); return true;
53
+ } catch { return false; }
54
+ }
55
+
56
+ module.exports = { webUrl, urlAt, openUrl };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hopdeck",
3
- "version": "1.5.4",
3
+ "version": "1.5.6",
4
4
  "description": "Selector visual de proyectos y conversaciones para Claude Code y Codex CLI, en la terminal: salta entre proyectos sin hacer cd.",
5
5
  "author": "fabriciodev26",
6
6
  "license": "MIT",