hopdeck 1.4.2 → 1.5.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 CHANGED
@@ -1,5 +1,20 @@
1
1
  # Cambios
2
2
 
3
+ ## Sin publicar
4
+
5
+ ### Nuevo
6
+ - Primer soporte para Codex CLI: `hopdeck --provider codex`, proyectos y conversaciones mediante `codex app-server`, vistas previas, chats nuevos y reanudados con `codex resume`, y varios chats abiertos en el panel integrado.
7
+ - `hopdeck shortcut on` instala o actualiza los atajos de Claude y Codex. Con argumentos se ejecuta directamente la CLI correspondiente.
8
+ - Preferencias e historial separados por proveedor; los títulos y archivados de Codex se gestionan localmente en `~/.hopdeck-codex.json`.
9
+
10
+ ### Límites de la primera versión
11
+ - Imágenes, estadísticas y búsqueda en el contenido completo permanecen en el modo Claude. Los indicadores de actividad de Codex dependen de su terminal.
12
+
13
+ ## 1.4.3
14
+
15
+ ### Arreglado
16
+ - **Teclas repetidas al pie de la lista.** La fila de la lista repetía `n nueva`, `/ buscar` y `? ayuda`, que ya dice la barra de abajo (`[/] buscar [n] nueva …`). Ahora esa fila solo dice lo propio de la fila marcada: sobre un proyecto, `⏎ desplegar p fijar x ocultar`; sobre una conversación, `⏎ reanudar R renombrar a archivar`. También se quitaron los espacios que sobraban tras la última tecla y que hacían que se cortara con «…» aunque cupiera.
17
+
3
18
  ## 1.4.2
4
19
 
5
20
  ### Nuevo
package/README.en.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  <p align="center"><img alt="The Hopdeck mascot: an orange toad with headphones" src="docs/mascot.png" width="130"></p>
9
9
 
10
- <p align="center"><b>Hop between your Claude Code projects and conversations without leaving the terminal.</b></p>
10
+ <p align="center"><b>Hop between your Claude Code or Codex projects and conversations without leaving the terminal.</b></p>
11
11
 
12
12
  [Español](README.md) · **English**
13
13
 
@@ -19,6 +19,20 @@
19
19
  Type `claude` in your terminal and **pick which project and conversation to continue**, without leaving and without `cd`.
20
20
  The project list stays on the left and the conversation on the right.
21
21
 
22
+ ### Claude and Codex
23
+
24
+ With shortcuts installed, `claude` opens Hopdeck for Claude Code and `codex` opens it for Codex CLI. Each mode has its own history and preferences. Commands with arguments (`claude -p ...`, `codex exec ...`, `codex resume ...`) still run the original CLI directly.
25
+
26
+ ```bash
27
+ hopdeck --provider claude
28
+ hopdeck --provider codex
29
+ hopdeck shortcut on
30
+ ```
31
+
32
+ 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.
33
+
34
+ **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.
35
+
22
36
  <picture>
23
37
  <source media="(prefers-color-scheme: light)" srcset="docs/screenshots/02-vista-dividida-light.svg">
24
38
  <img alt="Split view: project list on the left, chat on the right" src="docs/screenshots/02-vista-dividida.svg">
@@ -26,8 +40,8 @@ The project list stays on the left and the conversation on the right.
26
40
 
27
41
  <p align="center"><img alt="Hopdeck in action: preview, chat, image on hover and git panel" src="docs/demo.gif" width="900"></p>
28
42
 
29
- > **Independent community project.** Not affiliated with, endorsed or sponsored by Anthropic.
30
- > "Claude" and "Claude Code" are trademarks of Anthropic, PBC. Hopdeck only reads the local history that Claude Code already keeps on your machine and launches the `claude` command you have installed.
43
+ > **Independent community project.** Not affiliated with, endorsed or sponsored by Anthropic or OpenAI.
44
+ > Hopdeck reads local Claude Code history or queries history through Codex CLI, then launches your installed `claude` or `codex` command. Each CLI retains its own authentication and normal connections.
31
45
 
32
46
  ## Contents
33
47
 
@@ -43,7 +57,7 @@ Hopdeck shows **all your projects and conversations on one screen**, with previe
43
57
  **You need**
44
58
 
45
59
  - [Node.js](https://nodejs.org) 22 or newer.
46
- - [Claude Code](https://claude.com/claude-code) installed (the `claude` command must work in your terminal).
60
+ - [Claude Code](https://claude.com/claude-code) or [Codex CLI](https://developers.openai.com/codex/cli) installed (the corresponding command must work in your terminal).
47
61
  - A terminal with color. On Windows, **Windows Terminal** is recommended.
48
62
 
49
63
  **Install**
package/README.md CHANGED
@@ -7,7 +7,7 @@
7
7
 
8
8
  <p align="center"><img alt="La mascota de Hopdeck: un sapo naranja con auriculares" src="docs/mascot.png" width="130"></p>
9
9
 
10
- <p align="center"><b>Salta entre tus proyectos y conversaciones de Claude Code, sin salir de la terminal.</b></p>
10
+ <p align="center"><b>Salta entre tus proyectos y conversaciones de Claude Code o Codex, sin salir de la terminal.</b></p>
11
11
 
12
12
  **Español** · [English](README.en.md)
13
13
 
@@ -19,6 +19,20 @@
19
19
  Escribe `claude` en tu terminal y **elige en qué proyecto y conversación seguir**, sin salir y sin hacer `cd`.
20
20
  La lista de proyectos queda a la izquierda y la conversación a la derecha.
21
21
 
22
+ ### Claude y Codex
23
+
24
+ Con los atajos instalados, `claude` abre Hopdeck con Claude Code y `codex` lo abre con Codex CLI. Cada modo muestra su propio historial y recuerda sus propias preferencias. Los comandos con argumentos (`claude -p ...`, `codex exec ...`, `codex resume ...`) siguen ejecutando directamente su CLI.
25
+
26
+ ```bash
27
+ hopdeck --provider claude
28
+ hopdeck --provider codex
29
+ hopdeck shortcut on
30
+ ```
31
+
32
+ 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.
33
+
34
+ **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.
35
+
22
36
  <picture>
23
37
  <source media="(prefers-color-scheme: light)" srcset="docs/screenshots/02-vista-dividida-light.svg">
24
38
  <img alt="Vista dividida: lista de proyectos a la izquierda y el chat a la derecha" src="docs/screenshots/02-vista-dividida.svg">
@@ -26,8 +40,8 @@ La lista de proyectos queda a la izquierda y la conversación a la derecha.
26
40
 
27
41
  <p align="center"><img alt="Hopdeck en acción: vista previa, chat, imagen al pasar el cursor y panel de git" src="docs/demo.gif" width="900"></p>
28
42
 
29
- > **Proyecto independiente de la comunidad.** No está afiliado, respaldado ni patrocinado por Anthropic.
30
- > "Claude" y "Claude Code" son marcas de Anthropic, PBC. Hopdeck solo lee el historial local que Claude Code ya guarda en tu equipo y lanza el comando `claude` que tú tengas instalado.
43
+ > **Proyecto independiente de la comunidad.** No está afiliado, respaldado ni patrocinado por Anthropic ni OpenAI.
44
+ > Hopdeck lee el historial local de Claude Code o consulta el historial mediante Codex CLI y lanza el comando `claude` o `codex` que tengas instalado. Cada CLI conserva su autenticación y sus conexiones habituales.
31
45
 
32
46
  ## Índice
33
47
 
@@ -43,7 +57,7 @@ Hopdeck te enseña **todos tus proyectos y conversaciones en una sola pantalla**
43
57
  **Necesitas**
44
58
 
45
59
  - [Node.js](https://nodejs.org) 22 o superior.
46
- - [Claude Code](https://claude.com/claude-code) instalado (el comando `claude` debe funcionar en tu terminal).
60
+ - [Claude Code](https://claude.com/claude-code) o [Codex CLI](https://developers.openai.com/codex/cli) instalado (el comando correspondiente debe funcionar en tu terminal).
47
61
  - Una terminal con color. En Windows se recomienda **Windows Terminal**.
48
62
 
49
63
  **Instalar**
@@ -220,6 +234,8 @@ Casi nunca hace falta tocar nada. Lo más útil:
220
234
  | Variable de entorno | Efecto |
221
235
  |---|---|
222
236
  | `HOPDECK_LANG` | `es` o `en` (por defecto, el idioma del sistema) |
237
+ | `HOPDECK_PROVIDER` | `claude` o `codex` (por defecto, `claude`; `--provider` tiene prioridad) |
238
+ | `CODEX_HOME` | Carpeta de Codex, si no es `~/.codex` |
223
239
  | `HOPDECK_THEME` | `light` o `dark`: manda sobre lo guardado con `hopdeck theme` |
224
240
  | `HOPDECK_SIXEL` | `1` fuerza la imagen real al pasar el cursor por `[Image #N]`, `0` usa siempre bloques (por defecto se detecta) |
225
241
  | `HOPDECK_BUSY` | `output` marca un chat como «trabajando» con cualquier salida reciente. Por defecto solo cuando Claude muestra «esc to interrupt» |
package/SECURITY.md CHANGED
@@ -2,14 +2,15 @@
2
2
 
3
3
  ## Qué hace (y qué no) este programa con tus datos
4
4
 
5
- - Lee el historial local de Claude Code (`~/.claude/projects`, o `CLAUDE_CONFIG_DIR`). **No envía nada a internet**: no tiene telemetría, ni analítica, ni peticiones de red.
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
6
  - Escribe solo en tu equipo:
7
7
  - `~/.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
+ - `~/.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.
8
9
  - Una carpeta temporal privada con las imágenes cuando abres la galería con `o` (se borra al salir).
9
10
  - Con `hopdeck shortcut on`, un bloque marcado en el perfil de tu shell (`~/.bashrc`, `~/.zshrc`, perfil de PowerShell…). Antes guarda una copia `<perfil>.hopdeck-backup` (la primera, sin sobrescribirla). `hopdeck shortcut off` quita el bloque.
10
11
  - `hopdeck uninstall` (siempre con tu confirmación, o `--yes`) quita ese bloque, borra tus preferencias y la caché, y ejecuta `npm uninstall -g hopdeck`. No toca tu historial de Claude Code ni las copias de seguridad de los perfiles.
11
12
  - Al renombrar una conversación (`R`), añade una línea `custom-title` al final de su archivo `.jsonl`, igual que hace Claude Code.
12
- - Ejecuta el comando `claude` que encuentre en tu `PATH`. Si alguien puede cambiar tu `PATH`, puede cambiar qué se ejecuta (como con cualquier programa).
13
+ - 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).
13
14
  - 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.
14
15
 
15
16
  ## Versiones con soporte
package/bin/hopdeck.js CHANGED
@@ -3,13 +3,18 @@
3
3
  /**
4
4
  * Hopdeck
5
5
  * Selector visual de proyectos y sesiones para Claude Code.
6
- * Cero dependencias · arranque instantáneo.
6
+ * Claude Code y Codex CLI en una misma interfaz de terminal.
7
7
  */
8
8
  const fs = require('fs');
9
9
  const os = require('os');
10
10
  const path = require('path');
11
11
  const cp = require('child_process');
12
12
  const readline = require('readline');
13
+ let provider;
14
+ try { provider = require('../lib/provider'); }
15
+ catch (err) { if (require.main !== module) throw err; console.error(err.message); process.exit(2); }
16
+ const codexHistory = require('../lib/codex-history');
17
+ const { findExecutable } = require('../lib/executable');
13
18
 
14
19
  const { LANG, T } = require('../lib/i18n');
15
20
  const { TRUE, NOCOL, LIGHT, setTheme, isLight, fg, bg, R, C, cw, strW, fit, clean } = require('../lib/style');
@@ -30,7 +35,7 @@ let VERSION = '0.0.0';
30
35
  try { VERSION = require('../package.json').version; } catch { /* sin package.json */ }
31
36
  const WIN = process.platform === 'win32';
32
37
  // Preferencias propias: proyectos fijados/ocultos, ancho del panel, ratón.
33
- const CFG_FILE = process.env.HOPDECK_CONFIG || path.join(os.homedir(), '.hopdeck.json');
38
+ const CFG_FILE = process.env.HOPDECK_CONFIG || provider.configFile;
34
39
  const CFG = { pinned: [], hidden: [], archived: [], sidebar: 0, mouse: true, notify: true, last: null };
35
40
  const saveCfg = () => { try { fs.writeFileSync(CFG_FILE, JSON.stringify(CFG, null, 2), { mode: 0o600 }); } catch { /* solo lectura */ } };
36
41
  try { Object.assign(CFG, JSON.parse(fs.readFileSync(CFG_FILE, 'utf8'))); } catch { /* primera vez */ }
@@ -45,7 +50,8 @@ function sortProjects(list) {
45
50
  }
46
51
 
47
52
  function finishScan(projects) {
48
- endScan();
53
+ if (!provider.isCodex) endScan();
54
+ if (provider.isCodex) for (const p of projects) for (const s of p.sessions) s.title = CFG.titles?.[s.id] || s.title;
49
55
  const cur = process.cwd();
50
56
  const have = (d) => projects.some((p) => p.cwd === d);
51
57
  if (!have(cur)) projects.push({ key: '__cwd', cwd: cur, name: baseName(cur), sessions: [], mtime: Date.now() });
@@ -72,7 +78,8 @@ function linkChats(projects) {
72
78
  for (const x of pend) {
73
79
  if (pend.filter((y) => y.cwd === x.cwd).length !== 1) continue; // varios chats nuevos en la misma carpeta: ambiguo
74
80
  const p = projects.find((q) => q.cwd === x.cwd); if (!p) continue;
75
- 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];
81
+ const candidates = p.sessions.filter((q) => q.mtime >= x.t0 - 2000 && !taken.has(q.id) && !E.sessions.has(q.id) && (!provider.isCodex || !x.knownIds?.has(q.id))).sort((a, b) => b.mtime - a.mtime);
82
+ const c = provider.isCodex && candidates.length !== 1 ? null : candidates[0];
76
83
  if (c) { x.sid = c.id; x.title = c.title; taken.add(c.id); }
77
84
  }
78
85
  embedLive();
@@ -102,12 +109,14 @@ function gitBranch(cwd) {
102
109
  }
103
110
 
104
111
  function scan() {
112
+ if (provider.isCodex) return finishScan(codexHistory.scanSync());
105
113
  beginScan();
106
114
  return finishScan(projectDirs().map(buildProject).filter(Boolean));
107
115
  }
108
116
 
109
117
  /** Igual que scan() pero cede el control al bucle de eventos para poder animar el loader. */
110
118
  async function scanAsync(onProgress) {
119
+ if (provider.isCodex) return finishScan(await codexHistory.scanProjectsAsync(onProgress));
111
120
  const dirs = projectDirs(); const projects = [];
112
121
  beginScan();
113
122
  for (let i = 0; i < dirs.length; i++) {
@@ -149,7 +158,9 @@ async function reloadAsync(after, silent) {
149
158
  if (reloading) return;
150
159
  reloading = true; if (!silent) { S.loading = true; ensureSpin(); if (active) render(); }
151
160
  deepPrev = null;
152
- try { S.projects = await scanAsync(); } finally { reloading = false; if (!silent) S.loading = false; }
161
+ try { S.projects = await scanAsync(); }
162
+ catch (err) { S.flash = String(err.message).split('\n')[0]; }
163
+ finally { reloading = false; if (!silent) S.loading = false; }
153
164
  if (after) after();
154
165
  if (active) render();
155
166
  }
@@ -181,6 +192,8 @@ let deepT = null, deepTok = 0, deepPrev = null, deepJob = null;
181
192
  function queryChanged() {
182
193
  clearTimeout(deepT); deepTok++; S.deepHits = null;
183
194
  if (deepJob) { deepJob.cancel(); deepJob = null; }
195
+ // Codex history is served by its CLI; this release searches titles, projects and first messages.
196
+ if (provider.isCodex) { S.deep = false; S.auto = false; S.loading = false; return; }
184
197
  // Si ningún título ni proyecto coincide, se busca solo dentro del contenido sin que haya que pedirlo con Tab
185
198
  S.auto = !S.deep && S.query.trim().length >= 3 && !view().length;
186
199
  const deepOn = S.deep || S.auto;
@@ -381,7 +394,7 @@ function frameTree(W, H) {
381
394
  S.coff = scroll(S.coff, S.c, bodyH);
382
395
  const lines = [];
383
396
  const searchOn = !S.fb && !S.qs && S.prompt === null && !S.help && (S.searching || !!S.query.trim()); // hay una búsqueda en marcha
384
- const head = [[' » ', C.brand], ['Hop', C.brand + C.bold], ['deck', C.text + C.bold], [' ' + S.projects.length, C.dim], [S.loading && !searchOn ? ' ' + spin() : '', C.accent], ...liveSummary()];
397
+ const head = [[' » ', C.brand], ['Hop', C.brand + C.bold], ['deck', C.text + C.bold], [' ' + provider.label, C.dim], [' ' + S.projects.length, C.dim], [S.loading && !searchOn ? ' ' + spin() : '', C.accent], ...liveSummary()];
385
398
  // «⌕ / buscar» siempre a la vista, arriba a la derecha (sin la palabra si el título y los chats abiertos ya ocupan el sitio)
386
399
  const headW = head.reduce((a, [t]) => a + strW(t), 0), longHint = ' ⌕ / ' + T.k.find + ' ', hint = headW + strW(longHint) <= W ? longHint : headW + 5 <= W ? ' ⌕ / ' : '';
387
400
  lines.push(searchOn
@@ -480,12 +493,13 @@ function frameTree(W, H) {
480
493
  lines.push(fit([[' ⏎', C.accent], [' ' + T.k.open + ' ', C.dim], S.searching ? ['Tab', C.accent] : ['/', C.accent], S.searching ? [' ' + (deepOn ? '◉ ' : '○ ') + T.deep + ' ', deepOn ? C.ok : C.dim] : [' ' + T.kEdit + ' ', C.dim],
481
494
  ['esc', C.accent], [' ' + (S.searching ? T.kEsc : T.kClear), C.dim]], W));
482
495
  } else {
496
+ // solo lo que la barra de abajo no dice: qué hace ⏎ en la fila marcada y sus teclas propias (n, /, ?, q… ya están abajo)
483
497
  const k = T.k, segs = [[' ', '']];
484
- const keys = !cur ? [['⏎', k.open], ['n', k.neu], ['/', k.find], ['?', T.kHelp]]
485
- : cur.t === 'p' ? [['⏎', T.kUnfold], ['n', k.neu], ['p', T.kPin], ['/', k.find], ['?', T.kHelp]]
486
- : cur.t === 's' ? [['⏎', k.resume], ['R', T.kRename], ['n', k.neu], ['/', k.find], ['?', T.kHelp]]
487
- : [['⏎', k.open], ['n', k.neu], ['/', k.find], ['?', T.kHelp]];
488
- for (const [key, desc] of keys) segs.push([key, C.accent], [' ' + desc + ' ', C.dim]);
498
+ const keys = !cur ? [['⏎', k.open]]
499
+ : cur.t === 'p' ? [['⏎', T.kUnfold], ['p', T.kPin], ['x', T.kHide]]
500
+ : cur.t === 's' ? [['⏎', k.resume], ['R', T.kRename], ['a', T.kArchive]]
501
+ : [['⏎', k.open]];
502
+ keys.forEach(([key, desc], i) => segs.push([key, C.accent], [' ' + desc + (i < keys.length - 1 ? ' ' : ''), C.dim])); // sin espacios tras la última: contarían para el ancho y forzarían el «…»
489
503
  lines.push(fit(segs, W));
490
504
  }
491
505
  return lines;
@@ -510,7 +524,7 @@ function tmuxPanes() {
510
524
  /** Abre (o trae al frente) una conversación en el panel derecho sin matar las demás. */
511
525
  function launchSlot(project, session) {
512
526
  if (!fs.existsSync(project.cwd)) { flash(T.missing + ': ' + shortPath(project.cwd)); return; }
513
- const bin = findClaude();
527
+ const bin = findClaude(provider.id);
514
528
  if (!bin) { flash(T.noClaude); return; }
515
529
  const mine = process.env.TMUX_PANE;
516
530
  const key = session ? session.id : 'new-' + Date.now();
@@ -519,7 +533,7 @@ function launchSlot(project, session) {
519
533
  const slot = tmux('list-panes', '-t', mine, '-F', '#{pane_id}').split('\n').find((id) => id && id !== mine);
520
534
  let target = session && (panes.find((x) => x.key === key) || {}).id;
521
535
  if (!target) {
522
- const cmd = chatCmd(bin, [...(session ? ['--resume', session.id] : []), ...extraArgs], mine);
536
+ const cmd = chatCmd(bin, provider.launchArgs(session, extraArgs), mine);
523
537
  const slotInfo = panes.find((x) => x.id === slot);
524
538
  if (slotInfo && !slotInfo.key) { tmux('respawn-pane', '-k', '-t', slot, '-c', project.cwd, cmd); target = slot; }
525
539
  else target = tmux('new-window', '-d', '-P', '-F', '#{pane_id}', '-c', project.cwd, cmd);
@@ -565,6 +579,9 @@ function doRename(x, name) {
565
579
  name = (name || '').trim();
566
580
  if (!x || !name) return;
567
581
  if (S.live.has(x.id)) { flash(T.busyRename); return; }
582
+ if (provider.isCodex) {
583
+ CFG.titles = { ...CFG.titles, [x.id]: name }; saveCfg(); reloadKeep(); return;
584
+ }
568
585
  // Claude Code guarda el título como una línea más del historial
569
586
  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; }
570
587
  reloadKeep();
@@ -1088,6 +1105,7 @@ const previewMsgs = () => (CFG.previewMsgs > 0 ? CFG.previewMsgs : 12);
1088
1105
  const extractImages = (file) => images.extractImages(file, maxImages());
1089
1106
 
1090
1107
  async function imagesOf(x) {
1108
+ if (provider.isCodex) return [];
1091
1109
  const hit = IMG.get(x.file);
1092
1110
  if (hit && hit.m === x.mtime) return hit.images;
1093
1111
  const images = await extractImages(x.file);
@@ -1332,9 +1350,18 @@ function galleryKey(raw) {
1332
1350
  // Vista previa de los últimos mensajes de la conversación seleccionada (cuando no hay un chat abierto).
1333
1351
  const PREV = new Map();
1334
1352
  function previewFor(x) {
1335
- const hit = PREV.get(x.file);
1353
+ const key = provider.isCodex ? x.id : x.file;
1354
+ const hit = PREV.get(key);
1336
1355
  if (hit && hit.m === x.mtime) return hit.msgs;
1337
- PREV.set(x.file, { m: x.mtime, msgs: null });
1356
+ PREV.set(key, { m: x.mtime, msgs: null });
1357
+ if (provider.isCodex) {
1358
+ codexHistory.previewSession(x, previewMsgs()).then((msgs) => {
1359
+ PREV.set(key, { m: x.mtime, msgs }); if (active) render();
1360
+ }, () => {
1361
+ PREV.set(key, { m: x.mtime, msgs: x.first ? [{ role: 'user', text: x.first }] : [] }); if (active) render();
1362
+ });
1363
+ return null;
1364
+ }
1338
1365
  (async () => {
1339
1366
  let msgs = [];
1340
1367
  try {
@@ -1395,6 +1422,7 @@ const chatFile = (x) => x.file || (x.sid ? fileOfSid(x.sid) : null);
1395
1422
  * plano y, si el archivo crece (el chat abierto), se actualiza leyendo solo lo nuevo, como mucho cada 3 s.
1396
1423
  */
1397
1424
  function chatStats(file) {
1425
+ if (provider.isCodex) return undefined;
1398
1426
  if (!file) return undefined;
1399
1427
  let e = STATS.get(file);
1400
1428
  if (e) { STATS.delete(file); STATS.set(file, e); } // los más recientes al final
@@ -1511,13 +1539,13 @@ function embedLive() { S.live = new Set([...E.sessions.keys(), ...[...E.sessions
1511
1539
 
1512
1540
  function embedLaunch(project, session) {
1513
1541
  if (!fs.existsSync(project.cwd)) { flash(T.missing + ': ' + shortPath(project.cwd)); return; }
1514
- const bin = findClaude();
1542
+ const bin = findClaude(provider.id);
1515
1543
  if (!bin) { flash(T.noClaude); return; }
1516
1544
  const key = session ? session.id : 'new-' + Date.now();
1517
1545
  const ex = chatKeyOf(key);
1518
1546
  if (ex) { const x = E.sessions.get(ex); x.unseen = false; E.shown = ex; E.focus = 'right'; render(); return; }
1519
1547
  const { pty, Terminal } = E.deps; const { rw, th } = embedLayout();
1520
- const args = [...(session ? ['--resume', session.id] : []), ...extraArgs];
1548
+ const args = provider.launchArgs(session, extraArgs);
1521
1549
  const win = WIN && !/\.exe$/i.test(bin);
1522
1550
  const env = { ...process.env, HOPDECK_SKIP: '1', HOPDECK_INSIDE: '1', TERM: 'xterm-256color', COLORTERM: 'truecolor' };
1523
1551
  let p;
@@ -1527,6 +1555,7 @@ function embedLaunch(project, session) {
1527
1555
  } catch (e) { flash(String(e.message).split('\n')[0]); return; }
1528
1556
  const term = new Terminal({ cols: rw, rows: th, allowProposedApi: true, scrollback: 2000 });
1529
1557
  const sess = { p, term, cursorHidden: false, ready: false, lastData: Date.now(), quietUntil: 0, working: false, busy: false, unseen: false, title: session ? session.title : T.newChat, t0: Date.now(), project: project.name, cwd: project.cwd, sid: session ? session.id : null, closing: false, branch: gitBranch(project.cwd) };
1558
+ if (provider.isCodex) sess.knownIds = new Set(project.sessions.map((s) => s.id));
1530
1559
  const vis = (hidden) => (params) => { if (params.some((x) => x === 25 || (Array.isArray(x) && x.includes(25)))) sess.cursorHidden = hidden; return false; };
1531
1560
  term.parser.registerCsiHandler({ prefix: '?', final: 'h' }, vis(false));
1532
1561
  term.parser.registerCsiHandler({ prefix: '?', final: 'l' }, vis(true));
@@ -1877,6 +1906,7 @@ function leave() {
1877
1906
  process.stdin.pause();
1878
1907
  }
1879
1908
  function quit(code = 0) {
1909
+ codexHistory.close();
1880
1910
  cleanExports();
1881
1911
  if (EMBED || SIDEBAR) rememberState();
1882
1912
  if (EMBED) embedKillAll();
@@ -1893,19 +1923,8 @@ const extraArgs = [];
1893
1923
 
1894
1924
  /** Busca el ejecutable real de claude en el PATH (no depende de funciones del shell). */
1895
1925
  /** Busca un programa en el PATH (por defecto `claude`). Recuerda el resultado mientras el archivo siga existiendo. */
1896
- const FOUND = new Map();
1897
1926
  function findClaude(name = 'claude') {
1898
- const known = FOUND.get(name);
1899
- if (known) { try { if (fs.statSync(known).isFile()) return known; } catch { /* ya no está: se busca otra vez */ } FOUND.delete(name); }
1900
- const exts = WIN ? (process.env.PATHEXT || '.EXE;.CMD;.BAT').split(';').concat(['']) : [''];
1901
- for (const dir of (process.env.PATH || '').split(path.delimiter)) {
1902
- if (!dir) continue;
1903
- for (const ext of exts) {
1904
- const f = path.join(dir, name + ext.toLowerCase());
1905
- try { if (fs.statSync(f).isFile()) { FOUND.set(name, f); return f; } } catch { /* siguiente */ }
1906
- }
1907
- }
1908
- return null;
1927
+ return findExecutable(name);
1909
1928
  }
1910
1929
 
1911
1930
  /** El id de una sesión sale del nombre de su archivo; solo se pasa a `claude --resume` si es un identificador normal. */
@@ -1916,11 +1935,11 @@ function launch(project, session) {
1916
1935
  if (SIDEBAR) return launchSlot(project, session);
1917
1936
  if (EMBED) return embedLaunch(project, session);
1918
1937
  if (!fs.existsSync(project.cwd)) { flash(T.missing + ': ' + shortPath(project.cwd)); return; }
1919
- const bin = findClaude();
1938
+ const bin = findClaude(provider.id);
1920
1939
  if (!bin) { flash(T.noClaude); return; }
1921
1940
  leave();
1922
1941
  process.stdout.write('\x1b[2J\x1b[H');
1923
- const args = [...(session ? ['--resume', session.id] : []), ...extraArgs];
1942
+ const args = provider.launchArgs(session, extraArgs);
1924
1943
  const opts = { cwd: project.cwd, stdio: 'inherit', env: { ...process.env, HOPDECK_SKIP: '1' } };
1925
1944
  const onInt = () => { /* Ctrl-C es del proceso hijo */ };
1926
1945
  process.on('SIGINT', onInt);
@@ -2036,8 +2055,8 @@ async function run() {
2036
2055
  splash(0, 0);
2037
2056
  const tick = setInterval(() => { frameN++; splash(prog[0], prog[1]); }, 90);
2038
2057
  const prog = [0, 0];
2039
- S.projects = await scanAsync((d, t) => { prog[0] = d; prog[1] = t; });
2040
- clearInterval(tick); invalidate();
2058
+ try { S.projects = await scanAsync((d, t) => { prog[0] = d; prog[1] = t; }); }
2059
+ finally { clearInterval(tick); invalidate(); }
2041
2060
  if (SIDEBAR || EMBED) {
2042
2061
  S.open = S.projects[0] && S.projects[0].key;
2043
2062
  restoreState();
@@ -2087,18 +2106,20 @@ function doctor() {
2087
2106
  console.log(`\n ${C.brand}${C.bold}» Hop${R}${C.text}${C.bold}deck doctor${R} ${C.dim}v${VERSION}${R}\n`);
2088
2107
  if (parseInt(process.versions.node, 10) < 22) bad(T.dcNodeOld(process.version), T.dcNodeOldHint);
2089
2108
  else ok(`Node ${process.version} · ${process.platform} ${process.arch}`);
2090
- const n = projectDirs().length;
2091
- const histDir = shortPath(path.join(CONFIG_DIR, 'projects'));
2092
- n ? ok(T.dcHist(n, histDir)) : bad(T.dcNoHist(histDir), T.dcNoHistHint);
2093
- const bin = findClaude();
2094
- bin ? ok(T.dcClaude(shortPath(bin))) : bad(T.dcNoClaude, WIN ? T.dcInstallWin : T.dcInstallUnix);
2109
+ const histDir = shortPath(provider.isCodex ? codexHistory.CONFIG_DIR : path.join(CONFIG_DIR, 'projects'));
2110
+ const bin = findClaude(provider.id);
2111
+ bin ? ok(T.dcClaude(shortPath(bin))) : bad(T.dcNoClaude, provider.isCodex ? 'npm install -g @openai/codex' : WIN ? T.dcInstallWin : T.dcInstallUnix);
2112
+ try {
2113
+ const n = provider.isCodex ? (bin ? codexHistory.scanSync().length : 0) : projectDirs().length;
2114
+ n ? ok(T.dcHist(n, histDir)) : bad(T.dcNoHist(histDir), T.dcNoHistHint);
2115
+ } catch (err) { bad(clean(err.message), 'codex app-server'); }
2095
2116
  const tm = !WIN && hasTmux();
2096
2117
  const deps = loadDeps();
2097
2118
  if (tm) ok(T.dcTmux);
2098
2119
  else if (deps) ok(T.dcEmbed);
2099
2120
  else bad(T.dcNone, WIN ? T.dcNoneWin : T.dcNoneUnix);
2100
2121
  let wrapped = false;
2101
- for (const t of targets()) { try { if (fs.readFileSync(t.file, 'utf8').includes(MARK_A)) wrapped = true; } catch { /* */ } }
2122
+ for (const t of targets()) { try { const txt = fs.readFileSync(t.file, 'utf8'); if (txt.includes(MARK_A) && txt.includes('hopdeck --provider codex')) wrapped = true; } catch { /* */ } }
2102
2123
  wrapped ? ok(T.dcShort) : bad(T.dcNoShort, findClaude('hopdeck') ? T.dcNoShortHint : T.dcNoCmdHint); // sin el comando en el PATH, "hopdeck shortcut on" no existe todavía
2103
2124
  ok(T.dcPrefs(shortPath(CFG_FILE), shortPath(CACHE_FILE)));
2104
2125
  if (process.env.WT_SESSION) { // dentro de Windows Terminal: Ctrl+V solo pega texto y no deja pegar imágenes
@@ -2151,6 +2172,15 @@ ${MARK_B}
2151
2172
  `,
2152
2173
  };
2153
2174
 
2175
+ // Keep one managed block, so upgrading an existing Claude-only shortcut is idempotent.
2176
+ // Arguments always go straight to the original CLI; only a bare command opens Hopdeck.
2177
+ for (const kind of Object.keys(SNIP)) {
2178
+ const claude = SNIP[kind].replace(MARK_A, '').replace(MARK_B, '').trim()
2179
+ .replace(/\{ hopdeck \}/g, '{ hopdeck --provider claude }').replace(/^(\s+)hopdeck$/gm, '$1hopdeck --provider claude');
2180
+ const codex = claude.replace(/\bclaude\b/g, 'codex');
2181
+ SNIP[kind] = `${MARK_A}\n${claude}\n${codex}\n${MARK_B}\n`;
2182
+ }
2183
+
2154
2184
  function stripBlock(txt) {
2155
2185
  const a = txt.indexOf(MARK_A), b = txt.indexOf(MARK_B);
2156
2186
  if (a < 0 || b < 0) return txt;
@@ -2213,7 +2243,7 @@ function install(remove, list = targets(), quiet = false) {
2213
2243
  const ok = (s) => `${C.ok}✓${R} ${s}`;
2214
2244
  baks.forEach((b) => log(ok(T.bakMsg(shortPath(b)))));
2215
2245
  if (remove) {
2216
- log(ok(LANG === 'es' ? 'Atajo eliminado. Escribir "claude" vuelve a ser el comportamiento normal.' : 'Shortcut removed. Typing "claude" is back to normal.'));
2246
+ log(ok(LANG === 'es' ? 'Atajos eliminados. "claude" y "codex" vuelven a su comportamiento normal.' : 'Shortcuts removed. "claude" and "codex" are back to normal.'));
2217
2247
  } else {
2218
2248
  done.forEach((f) => log(ok(shortPath(f))));
2219
2249
  if (!quiet) tutorial(true);
@@ -2239,7 +2269,9 @@ async function uninstallAll({ yes = false, list = targets() } = {}) {
2239
2269
  const had = hasShortcut(list);
2240
2270
  const r = install(true, list, true);
2241
2271
  if (had && r.done.length) ok(T.unShortcutOff); else note(T.unNoShortcut);
2242
- for (const f of [CFG_FILE, CACHE_FILE, CACHE_FILE + '.tmp']) { try { fs.rmSync(f, { force: true }); } catch { /* */ } }
2272
+ const dataFiles = [CFG_FILE, CACHE_FILE, CACHE_FILE + '.tmp'];
2273
+ if (!process.env.HOPDECK_CONFIG) dataFiles.push(path.join(os.homedir(), '.hopdeck.json'), path.join(os.homedir(), '.hopdeck-codex.json'));
2274
+ for (const f of new Set(dataFiles)) { try { fs.rmSync(f, { force: true }); } catch { /* */ } }
2243
2275
  ok(T.unData);
2244
2276
  if (process.env.HOPDECK_NO_NPM) { note(T.unSkipNpm); console.log(`\n ${C.dim}${T.unDone}${R}`); return 0; }
2245
2277
  const res = cp.spawnSync('npm uninstall -g hopdeck', { shell: true, stdio: 'inherit' }); // comando fijo, sin datos de fuera
@@ -2334,6 +2366,9 @@ function tutorial(afterInstall) {
2334
2366
  `${d}claude with arguments (claude -p "...", claude --resume) works as usual.${R}`,
2335
2367
  `${d}Remove the shortcut: hopdeck shortcut off · Uninstall everything: hopdeck uninstall${R}`,
2336
2368
  ];
2369
+ if (provider.isCodex) for (let i = 0; i < L.length; i++) L[i] = L[i].replace(/Claude/g, 'Codex').replace(/claude --resume/g, 'codex resume').replace(/claude -p/g, 'codex exec').replace(/\bclaude\b/g, 'codex');
2370
+ L.push('', LANG === 'es' ? `${d}claude → Hopdeck Claude · codex → Hopdeck Codex (con los atajos instalados).${R}` : `${d}claude → Hopdeck Claude · codex → Hopdeck Codex (with shortcuts installed).${R}`);
2371
+ L.push(`${d}hopdeck --provider claude | hopdeck --provider codex${R}`);
2337
2372
  console.log('\n' + L.map((x) => ' ' + x).join('\n') + '\n');
2338
2373
  }
2339
2374
 
@@ -2357,7 +2392,7 @@ function suggestCommand(word) {
2357
2392
  const OWN_FLAGS = ['--help', '-h', '--version', '-v', '--list', '--idle', '--frame', '--sidebar'];
2358
2393
 
2359
2394
  function main() {
2360
- const [cmd, ...rest] = process.argv.slice(2);
2395
+ const [cmd, ...rest] = provider.args;
2361
2396
  // una palabra suelta, o una opción con guiones que se parece a un comando (--uninstall, --unistall…), es una errata: no se abre
2362
2397
  // Hopdeck ni se le pasa nada a claude
2363
2398
  if (cmd && !commandName(cmd) && !OWN_FLAGS.includes(cmd) && (!cmd.startsWith('-') || suggestCommand(cmd))) {
@@ -2404,11 +2439,14 @@ function main() {
2404
2439
  else console.log(frame(c, r).join('\n'));
2405
2440
  } else {
2406
2441
  extraArgs.push(...[cmd, ...rest].filter((a) => a && a !== '--sidebar'));
2407
- run().catch((e) => { try { leave(); } catch { /* */ } console.error(e); process.exit(1); });
2442
+ run().catch((e) => { codexHistory.close(); try { leave(); } catch { /* */ } console.error(e.message); process.exit(1); });
2408
2443
  }
2409
2444
  }
2410
2445
 
2411
- if (require.main === module) main();
2446
+ if (require.main === module) {
2447
+ process.on('exit', () => codexHistory.close());
2448
+ try { main(); } catch (err) { console.error(err.message); process.exitCode = 1; }
2449
+ }
2412
2450
  else {
2413
2451
  // al hacer require() (pruebas automáticas) no se ejecuta nada: solo se exponen las piezas puras
2414
2452
  module.exports = {
@@ -0,0 +1,149 @@
1
+ 'use strict';
2
+ // Use Codex's local JSON-RPC API rather than depending on its private SQLite/rollout formats.
3
+ const cp = require('child_process');
4
+ const readline = require('readline');
5
+ const os = require('os');
6
+ const path = require('path');
7
+ const { findExecutable } = require('./executable');
8
+ const { baseName, tidy } = require('./text');
9
+
10
+ class CodexClient {
11
+ constructor({ bin, args = ['app-server'], timeout = 30000 } = {}) {
12
+ this.bin = bin; this.args = args; this.timeout = timeout; this.next = 1;
13
+ this.pending = new Map(); this.proc = null; this.ready = null;
14
+ }
15
+ start() {
16
+ if (this.ready) return this.ready;
17
+ this.ready = (async () => {
18
+ const bin = this.bin || findExecutable('codex');
19
+ if (!bin) throw new Error('Codex CLI not found in PATH');
20
+ const batch = process.platform === 'win32' && /\.(cmd|bat)$/i.test(bin);
21
+ // Only the trusted executable and fixed app-server argument enter cmd.exe; RPC data uses stdin.
22
+ const p = this.proc = cp.spawn(batch ? process.env.ComSpec || 'cmd.exe' : bin,
23
+ batch ? ['/d', '/s', '/c', `""${bin}" app-server"`] : this.args,
24
+ { stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true, windowsVerbatimArguments: batch, env: { ...process.env, HOPDECK_SKIP: '1' } });
25
+ const fail = (err) => {
26
+ if (this.proc !== p) return;
27
+ for (const { reject, timer } of this.pending.values()) { clearTimeout(timer); reject(err); }
28
+ this.pending.clear();
29
+ if (this.proc === p) { this.proc = null; this.ready = null; }
30
+ };
31
+ p.on('error', fail);
32
+ p.on('exit', (code) => fail(new Error('Codex app-server exited' + (code ? ' (' + code + ')' : ''))));
33
+ p.stdin.on('error', fail);
34
+ p.stderr.resume(); // never expose logs, auth data or personal history in the UI
35
+ this.lines = readline.createInterface({ input: p.stdout });
36
+ this.lines.on('line', (line) => {
37
+ let msg; try { msg = JSON.parse(line); } catch { return; }
38
+ const request = !msg.method && this.pending.get(msg.id);
39
+ if (request) {
40
+ clearTimeout(request.timer); this.pending.delete(msg.id);
41
+ if (msg.error) { const err = new Error(msg.error.message || 'Codex request failed'); err.code = msg.error.code; request.reject(err); }
42
+ else request.resolve(msg.result);
43
+ } else if (msg.id !== undefined && msg.method) {
44
+ // This client only reads history: it never approves server-initiated actions.
45
+ p.stdin.write(JSON.stringify({ id: msg.id, error: { code: -32601, message: 'Unsupported request' } }) + '\n');
46
+ }
47
+ });
48
+ await this.send('initialize', { clientInfo: { name: 'hopdeck', title: 'Hopdeck', version: '1.4.3' } });
49
+ p.stdin.write(JSON.stringify({ method: 'initialized', params: {} }) + '\n');
50
+ })().catch((err) => { this.close(); throw err; });
51
+ return this.ready;
52
+ }
53
+ send(method, params) {
54
+ return new Promise((resolve, reject) => {
55
+ if (!this.proc) return reject(new Error('Codex app-server is not running'));
56
+ const id = this.next++;
57
+ const timer = setTimeout(() => { this.close(new Error('Codex request timed out: ' + method)); }, this.timeout);
58
+ this.pending.set(id, { resolve, reject, timer });
59
+ this.proc.stdin.write(JSON.stringify({ id, method, params }) + '\n');
60
+ });
61
+ }
62
+ async request(method, params) { await this.start(); return this.send(method, params); }
63
+ close(err = new Error('Codex history connection closed')) {
64
+ const p = this.proc; this.proc = null; this.ready = null;
65
+ for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(err); }
66
+ this.pending.clear();
67
+ if (this.lines) this.lines.close();
68
+ if (p) { p.stdin.destroy(); try { p.kill(); } catch { /* closed */ } }
69
+ }
70
+ }
71
+
72
+ function groupThreads(threads) {
73
+ const groups = new Map(), seen = new Set();
74
+ for (const t of threads) {
75
+ if (!t || !t.id || !t.cwd || seen.has(t.id)) continue;
76
+ seen.add(t.id);
77
+ const cwd = t.cwd;
78
+ let p = groups.get(cwd);
79
+ if (!p) { p = { key: 'codex:' + cwd, cwd, name: baseName(cwd), sessions: [], mtime: 0 }; groups.set(cwd, p); }
80
+ const mtime = Number(t.updatedAt || t.createdAt || 0) * 1000;
81
+ const first = tidy(typeof t.preview === 'string' ? t.preview : '').slice(0, 300);
82
+ p.sessions.push({ id: t.id, title: tidy(t.name || first || t.id), first, cwd, mtime, last: mtime, provider: 'codex' });
83
+ p.mtime = Math.max(p.mtime, mtime);
84
+ }
85
+ for (const p of groups.values()) p.sessions.sort((a, b) => b.mtime - a.mtime);
86
+ return [...groups.values()];
87
+ }
88
+
89
+ async function listProjects(client, onProgress) {
90
+ const threads = [], cursors = new Set(); let cursor = null;
91
+ do {
92
+ const page = await client.request('thread/list', { limit: 100, sortKey: 'updated_at', archived: false, cursor });
93
+ threads.push(...(page.data || []));
94
+ if (onProgress) onProgress(threads.length, threads.length);
95
+ cursor = page.nextCursor;
96
+ if (cursor && cursors.has(cursor)) throw new Error('Codex returned a repeated history cursor');
97
+ if (cursor) cursors.add(cursor);
98
+ } while (cursor);
99
+ return groupThreads(threads);
100
+ }
101
+
102
+ function messagesFromItems(items) {
103
+ return items.flatMap((item) => {
104
+ let role, text;
105
+ if (item.type === 'userMessage') { role = 'user'; text = (item.content || []).filter((c) => c.type === 'text').map((c) => c.text).join('\n'); }
106
+ else if (item.type === 'agentMessage') { role = 'assistant'; text = item.text; }
107
+ if (!role || typeof text !== 'string' || !text.trim()) return [];
108
+ return [{ role, text: tidy(text).slice(0, 700) }];
109
+ });
110
+ }
111
+
112
+ async function preview(client, session, limit = 12) {
113
+ try {
114
+ // New versions support bounded item pagination for both paginated and legacy history.
115
+ const items = []; let cursor = null;
116
+ for (let i = 0; i < 5; i++) {
117
+ const page = await client.request('thread/items/list', { threadId: session.id, limit: 50, sortDirection: 'desc', cursor });
118
+ items.push(...(page.data || []).map((entry) => entry.item || entry));
119
+ if (messagesFromItems(items).length >= limit || !page.nextCursor || page.nextCursor === cursor) break;
120
+ cursor = page.nextCursor;
121
+ }
122
+ return messagesFromItems(items.reverse()).slice(-limit);
123
+ } catch (err) {
124
+ // Older releases expose turns through thread/read instead.
125
+ if (err.code !== -32601 && !/unknown method|unknown variant|unsupported|not found/i.test(err.message)) throw err;
126
+ const result = await client.request('thread/read', { threadId: session.id, includeTurns: true });
127
+ return messagesFromItems((result.thread?.turns || []).flatMap((turn) => turn.items || [])).slice(-limit);
128
+ }
129
+ }
130
+
131
+ let client;
132
+ const getClient = () => client || (client = new CodexClient());
133
+ const close = () => { if (client) client.close(); client = null; };
134
+ // Text-only commands use a short-lived process so synchronous callers retain their existing API.
135
+ function scanSync() {
136
+ const result = cp.spawnSync(process.execPath, [__filename, '--list'], { encoding: 'utf8', windowsHide: true, timeout: 60000, maxBuffer: 32 * 1024 * 1024 });
137
+ if (result.error) throw result.error;
138
+ if (result.status !== 0) throw new Error(result.stderr.trim() || 'Could not read Codex history');
139
+ return JSON.parse(result.stdout);
140
+ }
141
+ module.exports = {
142
+ CodexClient, groupThreads, listProjects, messagesFromItems, preview, scanSync, close,
143
+ scanProjectsAsync: (progress) => listProjects(getClient(), progress),
144
+ previewSession: (session, limit) => preview(getClient(), session, limit),
145
+ CONFIG_DIR: process.env.CODEX_HOME || path.join(os.homedir(), '.codex'),
146
+ };
147
+ if (require.main === module) {
148
+ listProjects(getClient()).then((projects) => { process.stdout.write(JSON.stringify(projects)); close(); }, (err) => { console.error(err.message); close(); process.exitCode = 1; });
149
+ }
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const path = require('path');
4
+ const found = new Map();
5
+ function findExecutable(name) {
6
+ const hit = found.get(name);
7
+ if (hit) { try { if (fs.statSync(hit).isFile()) return hit; } catch { /* search again */ } found.delete(name); }
8
+ const win = process.platform === 'win32';
9
+ const exts = win ? (process.env.PATHEXT || '.EXE;.CMD;.BAT').split(';').concat(['']) : [''];
10
+ const pathKey = Object.keys(process.env).find((k) => k.toLowerCase() === 'path') || 'PATH';
11
+ for (const dir of (process.env[pathKey] || '').split(path.delimiter)) {
12
+ if (!dir) continue;
13
+ for (const ext of exts) {
14
+ const file = path.join(dir, name + ext.toLowerCase());
15
+ try { if (fs.statSync(file).isFile()) { found.set(name, file); return file; } } catch { /* next */ }
16
+ }
17
+ }
18
+ return null;
19
+ }
20
+ module.exports = { findExecutable };
package/lib/i18n.js CHANGED
@@ -18,7 +18,7 @@ const T = {
18
18
  imgNoPrev: 'No se puede previsualizar este formato', imgHint: '← → navegar o abrir en el visor esc cerrar', imgFolder: 'Imágenes abiertas en el visor',
19
19
  more: (n) => `mostrar ${n} más…`, busyRename: 'Cierra la conversación antes de renombrarla', renameLbl: 'nombre',
20
20
  copied: (n) => `Copiado (${n} caracteres)`, archMsg: 'Archivada (H para verlas)', unarchMsg: 'Desarchivada', qsHint: 'saltar a cualquier conversación',
21
- prevHint: '⏎ reanudar esta conversación', bar8: 'git', gitNone: 'Elige un proyecto', gitNoRepo: 'Esta carpeta no es un repositorio git', gitMissing: 'git no está instalado', gitErr: 'No se pudo leer el repositorio', gitClean: 'sin cambios', gitDirty: (n) => (n === 1 ? '1 cambio sin guardar' : `${n} cambios sin guardar`), gitMore: (n) => `… y ${n} más`, gitBranches: 'Ramas recientes', gitActivity: 'Actividad de ramas', gitNoActivity: 'Sin cambios de rama', gitFrom: 'desde', gitNarrow: (n) => `Terminal estrecha: el panel de git necesita ${n} columnas`, gitOnlyEmbed: 'El panel de git solo está en el terminal integrado', prevInfo: (a, n) => `${a === 'ahora' ? 'ahora mismo' : 'hace ' + a} · últimos ${n} mensajes`, kUnfold: 'desplegar', kRename: 'renombrar', kPin: 'fijar', kHelp: 'ayuda', noPrev: 'Sin mensajes para mostrar',
21
+ prevHint: '⏎ reanudar esta conversación', bar8: 'git', gitNone: 'Elige un proyecto', gitNoRepo: 'Esta carpeta no es un repositorio git', gitMissing: 'git no está instalado', gitErr: 'No se pudo leer el repositorio', gitClean: 'sin cambios', gitDirty: (n) => (n === 1 ? '1 cambio sin guardar' : `${n} cambios sin guardar`), gitMore: (n) => `… y ${n} más`, gitBranches: 'Ramas recientes', gitActivity: 'Actividad de ramas', gitNoActivity: 'Sin cambios de rama', gitFrom: 'desde', gitNarrow: (n) => `Terminal estrecha: el panel de git necesita ${n} columnas`, gitOnlyEmbed: 'El panel de git solo está en el terminal integrado', prevInfo: (a, n) => `${a === 'ahora' ? 'ahora mismo' : 'hace ' + a} · últimos ${n} mensajes`, kUnfold: 'desplegar', kRename: 'renombrar', kPin: 'fijar', kHelp: 'ayuda', kArchive: 'archivar', kHide: 'ocultar', noPrev: 'Sin mensajes para mostrar',
22
22
  bar6: 'ocultar lista', bar7: 'mostrar lista', deep: 'contenido', pathPrompt: 'nombre de la nueva carpeta', mkIn: 'se crea en', fbTitle: 'Elegir carpeta', fbHere: 'Abrir chat aquí', fbNew: 'Nueva carpeta aquí…', fbUp: 'Subir un nivel', fbProj: 'proyecto', fbHint: '⏎ entrar · ␣ abrir · / buscar · . ocultas', fbDrives: 'Este equipo', fbRecent: 'reciente', hoverMiss: (n) => `[Image #${n}]: aún no está en el historial`, fbEmpty: 'Sin subcarpetas', badId: 'Identificador de sesión no válido',
23
23
  imgClickHint: 'clic: abrir en grande', imgOpened: (n) => `[Image #${n}] abierta en el visor de imágenes`,
24
24
  unknownCmd: (c) => `Comando desconocido: "${c}"`, didYouMean: (s) => `¿Quisiste decir "${s}"?`, cmdList: 'Comandos: hopdeck shortcut on|off · theme light|dark|auto · mascot · uninstall · doctor · help (y --list, --version).\nLas opciones de claude (por ejemplo --model opus) se pasan tal cual: hopdeck --model opus',
@@ -66,7 +66,7 @@ const T = {
66
66
  imgNoPrev: 'This format cannot be previewed', imgHint: '← → browse o open in viewer esc close', imgFolder: 'Images opened in the viewer',
67
67
  more: (n) => `show ${n} more…`, busyRename: 'Close the conversation before renaming it', renameLbl: 'name',
68
68
  copied: (n) => `Copied (${n} chars)`, archMsg: 'Archived (H to show)', unarchMsg: 'Unarchived', qsHint: 'jump to any conversation',
69
- prevHint: '⏎ resume this conversation', bar8: 'git', gitNone: 'Pick a project', gitNoRepo: 'This folder is not a git repository', gitMissing: 'git is not installed', gitErr: 'Could not read the repository', gitClean: 'clean', gitDirty: (n) => (n === 1 ? '1 uncommitted change' : `${n} uncommitted changes`), gitMore: (n) => `… and ${n} more`, gitBranches: 'Recent branches', gitActivity: 'Branch activity', gitNoActivity: 'No branch changes', gitFrom: 'from', gitNarrow: (n) => `Terminal too narrow: the git panel needs ${n} columns`, gitOnlyEmbed: 'The git panel is only in the built-in terminal', prevInfo: (a, n) => `${a === 'now' ? 'just now' : a + ' ago'} · last ${n} messages`, kUnfold: 'unfold', kRename: 'rename', kPin: 'pin', kHelp: 'help', noPrev: 'No messages to show',
69
+ prevHint: '⏎ resume this conversation', bar8: 'git', gitNone: 'Pick a project', gitNoRepo: 'This folder is not a git repository', gitMissing: 'git is not installed', gitErr: 'Could not read the repository', gitClean: 'clean', gitDirty: (n) => (n === 1 ? '1 uncommitted change' : `${n} uncommitted changes`), gitMore: (n) => `… and ${n} more`, gitBranches: 'Recent branches', gitActivity: 'Branch activity', gitNoActivity: 'No branch changes', gitFrom: 'from', gitNarrow: (n) => `Terminal too narrow: the git panel needs ${n} columns`, gitOnlyEmbed: 'The git panel is only in the built-in terminal', prevInfo: (a, n) => `${a === 'now' ? 'just now' : a + ' ago'} · last ${n} messages`, kUnfold: 'unfold', kRename: 'rename', kPin: 'pin', kHelp: 'help', kArchive: 'archive', kHide: 'hide', noPrev: 'No messages to show',
70
70
  bar6: 'hide list', bar7: 'show list', deep: 'content', pathPrompt: 'new folder name', mkIn: 'created in', fbTitle: 'Pick a folder', fbHere: 'Open chat here', fbNew: 'New folder here…', fbUp: 'Go up', fbProj: 'project', fbHint: '⏎ enter · ␣ open · / find · . hidden', fbDrives: 'This PC', fbRecent: 'recent', hoverMiss: (n) => `[Image #${n}]: not in the history yet`, fbEmpty: 'No subfolders', badId: 'Invalid session id',
71
71
  imgClickHint: 'click: open full size', imgOpened: (n) => `[Image #${n}] opened in the image viewer`,
72
72
  unknownCmd: (c) => `Unknown command: "${c}"`, didYouMean: (s) => `Did you mean "${s}"?`, cmdList: 'Commands: hopdeck shortcut on|off · theme light|dark|auto · mascot · uninstall · doctor · help (and --list, --version).\nclaude options (for example --model opus) are passed through as they are: hopdeck --model opus',
@@ -101,4 +101,17 @@ const T = {
101
101
  },
102
102
  }[LANG];
103
103
 
104
+ // Product-specific copy follows the selected CLI; interface text remains shared.
105
+ if (require('./provider').isCodex) {
106
+ for (const [key, value] of Object.entries(T)) {
107
+ const adapt = (text) => typeof text === 'string' ? text.replace(/Claude Code/g, 'Codex CLI').replace(/Claude/g, 'Codex').replace(/claude/g, 'codex') : text;
108
+ if (typeof value === 'string') T[key] = adapt(value);
109
+ else if (typeof value === 'function') T[key] = (...args) => adapt(value(...args));
110
+ else if (Array.isArray(value)) T[key] = value.map(adapt);
111
+ }
112
+ 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
+ T.offerQ = LANG === 'es' ? '¿Quieres abrir Hopdeck escribiendo claude o codex?' : 'Do you want to open Hopdeck by typing claude or codex?';
116
+ T.dcShort = LANG === 'es' ? 'Atajos instalados: "claude" y "codex" abren Hopdeck' : 'Shortcuts installed: "claude" and "codex" open Hopdeck';
104
117
  module.exports = { LANG, T };
@@ -0,0 +1,24 @@
1
+ 'use strict';
2
+ const path = require('path');
3
+ const os = require('os');
4
+
5
+ // Hopdeck options precede the options forwarded to the selected CLI.
6
+ function parseProvider(argv, fallback = 'claude') {
7
+ const args = [...argv]; let id = fallback;
8
+ if (args[0] === '--provider') {
9
+ id = args[1]; args.splice(0, 2);
10
+ } else if (args[0] && args[0].startsWith('--provider=')) id = args.shift().slice(11);
11
+ if (!['claude', 'codex'].includes(id)) throw new Error('Usage: hopdeck --provider claude|codex');
12
+ return { id, args };
13
+ }
14
+
15
+ const selected = parseProvider(require.main && /hopdeck\.js$/.test(require.main.filename) ? process.argv.slice(2) : [], process.env.HOPDECK_PROVIDER || 'claude');
16
+ const isCodex = selected.id === 'codex';
17
+ // Child Hopdeck instances (including tmux panes) inherit the selected provider.
18
+ process.env.HOPDECK_PROVIDER = selected.id;
19
+ module.exports = {
20
+ ...selected, isCodex, parseProvider,
21
+ label: isCodex ? 'Codex' : 'Claude',
22
+ configFile: path.join(os.homedir(), isCodex ? '.hopdeck-codex.json' : '.hopdeck.json'),
23
+ launchArgs: (session, extra = []) => [...(session ? (isCodex ? ['resume', session.id] : ['--resume', session.id]) : []), ...extra],
24
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "hopdeck",
3
- "version": "1.4.2",
4
- "description": "Selector visual de proyectos y conversaciones para Claude Code, en la terminal: salta entre proyectos sin hacer cd.",
3
+ "version": "1.5.0",
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",
7
7
  "homepage": "https://github.com/fabriciodev26/hopdeck#readme",
@@ -31,6 +31,7 @@
31
31
  "keywords": [
32
32
  "claude",
33
33
  "claude-code",
34
+ "codex",
34
35
  "cli",
35
36
  "projects",
36
37
  "resume",
@@ -42,7 +43,7 @@
42
43
  "wsl"
43
44
  ],
44
45
  "scripts": {
45
- "test": "node --test test/unit.test.js test/e2e.test.js test/ui.test.js",
46
+ "test": "node --test test/unit.test.js test/e2e.test.js test/ui.test.js test/codex.test.js",
46
47
  "doctor": "node bin/hopdeck.js doctor",
47
48
  "screenshots": "node scripts/screenshots.js",
48
49
  "demo": "node scripts/demo.js"