hopdeck 1.5.6 → 1.6.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,16 @@
1
1
  # Cambios
2
2
 
3
+ ## Sin publicar
4
+
5
+ ## 1.6.0
6
+
7
+ ### Nuevo
8
+ - Asistente de primer inicio: elegir Claude Code o Codex y recordar el proveedor predeterminado. Si falta la CLI, ofrece descargar y ejecutar su instalador oficial para Windows, Linux o macOS, seguido del inicio de sesión de la propia CLI. Permite cancelar, reintentar y posponer el inicio de sesión; también recupera una CLI que se haya eliminado antes de abrir un chat.
9
+ - Detección de las rutas de instalación nativas sin reiniciar la terminal. Las instalaciones de proveedores requieren aceptación en una terminal interactiva y no se ejecutan durante npm/pnpm, en CI ni con `HOPDECK_NOPROMPT=1`.
10
+
11
+ ### Mejorado
12
+ - Los enlaces del chat que muestran un título en lugar de una URL ahora abren su destino web al hacer clic (OSC 8), tanto en Claude como en Codex. Conservan el destino al partirse entre líneas, cambiar el ancho o recorrer el historial; arrastrar sigue seleccionando texto.
13
+
3
14
  ## 1.5.6
4
15
 
5
16
  ### Documentación y comprobaciones
package/README.en.md CHANGED
@@ -61,7 +61,7 @@ Hopdeck shows **all your projects and conversations on one screen**, with previe
61
61
  **You need**
62
62
 
63
63
  - [Node.js](https://nodejs.org) 22 or newer.
64
- - [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).
64
+ - An account for [Claude Code](https://claude.com/claude-code) or [Codex CLI](https://developers.openai.com/codex/cli). If the selected CLI is missing, Hopdeck offers to install it when you open it.
65
65
  - A terminal with color. On Windows, **Windows Terminal** is recommended.
66
66
 
67
67
  **Install**
@@ -80,7 +80,11 @@ hopdeck
80
80
 
81
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
82
 
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.
83
+ The first time you open Hopdeck, a welcome screen appears. Press `Enter` to continue or `Esc` to skip it. A bare `hopdeck` then lets you choose **Claude Code** or **Codex** and remembers your choice. You can also select one directly with `hopdeck --provider claude` or `hopdeck --provider codex`.
84
+
85
+ If the selected CLI is missing, Hopdeck shows **Install now** and the official installer URL. When you accept, it downloads and runs Anthropic's or OpenAI's installer for Windows, Linux or macOS, then offers to sign in through the CLI itself. You can cancel, retry a failure, or postpone signing in. Only the selected provider is installed. An existing installation takes you straight to your projects. If you remove the CLI later, Hopdeck offers to reinstall it when you try to open a chat.
86
+
87
+ Provider installation requires internet and its interpreter: PowerShell on Windows, Bash for Claude or `sh` for Codex on Linux/macOS. Hopdeck recognizes standard native installation locations without restarting the terminal. It never installs providers during `npm install` / `pnpm add`, with `--version`, `--help`, `--list`, in CI, or with `HOPDECK_NOPROMPT=1`. Uninstalling Hopdeck leaves Claude/Codex installed.
84
88
 
85
89
  Done. You can also try it without installing: `npx hopdeck`.
86
90
 
@@ -177,7 +181,7 @@ It always starts at `~`. Recently used folders appear on top (`↻ recent`).
177
181
 
178
182
  ### Images in the chat
179
183
 
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.
184
+ In Claude and Codex chats, click an `http://` or `https://` URL to open your default browser. Links displaying a title instead of the address (OSC 8) and links wrapped across lines also work; dragging over text still selects it.
181
185
 
182
186
  <picture>
183
187
  <source media="(prefers-color-scheme: light)" srcset="docs/screenshots/04-hover-imagen-light.svg">
@@ -287,8 +291,8 @@ Other variables: `HOPDECK_TMUX=1` uses tmux panes on Linux/macOS, `HOPDECK_EMBED
287
291
 
288
292
  ## Privacy
289
293
 
290
- - **Nothing is sent to the internet.** No telemetry, no analytics, no network requests. Everything happens on your machine.
291
- - It reads your local Claude Code history and launches the `claude` you already have. It does not touch your session or your credentials.
294
+ - **No telemetry or analytics.** History is queried locally. Hopdeck only downloads an installer when you accept setup for a missing provider; each CLI retains its normal connections.
295
+ - It reads Claude Code or Codex history and launches its CLI. Each provider handles authentication; Hopdeck does not store your credentials.
292
296
  - It only writes its preferences and cache (in your home folder), the `hopdeck shortcut on` block in your shell profile and, if you rename a conversation, that conversation's title.
293
297
 
294
298
  More details, and how to report a security problem: [SECURITY.md](SECURITY.md).
package/README.md CHANGED
@@ -61,7 +61,7 @@ Hopdeck te enseña **todos tus proyectos y conversaciones en una sola pantalla**
61
61
  **Necesitas**
62
62
 
63
63
  - [Node.js](https://nodejs.org) 22 o superior.
64
- - [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).
64
+ - Una cuenta para [Claude Code](https://claude.com/claude-code) o [Codex CLI](https://developers.openai.com/codex/cli). Si falta la CLI elegida, Hopdeck ofrece instalarla al abrirlo.
65
65
  - Una terminal con color. En Windows se recomienda **Windows Terminal**.
66
66
 
67
67
  **Instalar**
@@ -80,7 +80,11 @@ hopdeck
80
80
 
81
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
82
 
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.
83
+ Al abrir Hopdeck por primera vez aparece una bienvenida. Pulsa `Enter` para continuar o `Esc` para omitirla. Si entras con `hopdeck`, puedes elegir **Claude Code** o **Codex**; se recuerda tu elección. También puedes elegir directamente con `hopdeck --provider claude` o `hopdeck --provider codex`.
84
+
85
+ Si la CLI elegida no está instalada, verás **Instalar ahora** y la dirección del instalador oficial. Al aceptar, Hopdeck descarga y ejecuta el instalador de Anthropic u OpenAI para Windows, Linux o macOS, y después ofrece iniciar sesión mediante la propia CLI. Puedes cancelar, reintentar si falla o dejar el inicio de sesión para más tarde. Solo se instala el proveedor elegido. Si ya lo tienes, continúa directamente a tus proyectos. Si lo desinstalas después, Hopdeck vuelve a ofrecer instalarlo al intentar abrir un chat.
86
+
87
+ La instalación del proveedor necesita internet y su intérprete: PowerShell en Windows, Bash para Claude o `sh` para Codex en Linux/macOS. Hopdeck reconoce las rutas habituales de las instalaciones nativas sin exigir reiniciar la terminal. No instala proveedores durante `npm install` / `pnpm add`, con `--version`, `--help`, `--list`, en CI ni con `HOPDECK_NOPROMPT=1`. Al desinstalar Hopdeck, las CLI de Claude/Codex se conservan.
84
88
 
85
89
  Listo. También puedes probarlo sin instalar: `npx hopdeck`.
86
90
 
@@ -177,7 +181,7 @@ Empieza siempre en `~`. Las carpetas que usaste hace poco aparecen arriba (`↻
177
181
 
178
182
  ### Imágenes del chat
179
183
 
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.
184
+ En los chats de Claude y Codex, un clic sobre una URL `http://` o `https://` abre el navegador predeterminado. También funcionan los enlaces que muestran un título en lugar de la dirección (OSC 8) y los partidos entre líneas; arrastrar sobre el texto permite seleccionarlo.
181
185
 
182
186
  <picture>
183
187
  <source media="(prefers-color-scheme: light)" srcset="docs/screenshots/04-hover-imagen-light.svg">
@@ -290,8 +294,8 @@ Otras variables: `HOPDECK_TMUX=1` usa paneles de tmux en Linux/macOS, `HOPDECK_E
290
294
 
291
295
  ## Privacidad
292
296
 
293
- - **No envía nada a internet.** Sin telemetría, sin analítica, sin peticiones de red. Todo ocurre en tu equipo.
294
- - Lee tu historial local de Claude Code y lanza el `claude` que ya tienes. No toca tu sesión ni tus credenciales.
297
+ - **Sin telemetría ni analítica.** El historial se consulta localmente. Hopdeck solo descarga un instalador si aceptas preparar un proveedor que falta; cada CLI conserva sus conexiones habituales.
298
+ - Lee el historial de Claude Code o Codex y lanza su CLI. La autenticación la gestiona cada proveedor; Hopdeck no guarda tus credenciales.
295
299
  - Solo escribe sus preferencias y su caché (en tu carpeta de usuario), el bloque de `hopdeck shortcut on` en tu perfil de shell y, si renombras una conversación, el título de esa conversación.
296
300
 
297
301
  Más detalles, y cómo avisar de un problema de seguridad: [SECURITY.md](SECURITY.md).
package/SECURITY.md CHANGED
@@ -2,7 +2,9 @@
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`). 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.
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 ni analítica. Las CLI de Claude y Codex conservan sus conexiones y ajustes habituales.
6
+ - Si falta el proveedor elegido, Hopdeck muestra la URL de su instalador oficial y pide aceptar antes de descargarlo por HTTPS y ejecutarlo. Solo permite como origen inicial `https://claude.ai/install.sh` / `install.ps1` o `https://chatgpt.com/codex/install.sh` / `install.ps1`; los redireccionamientos deben seguir usando HTTPS. La descarga tiene límites de tamaño y tiempo y se guarda en una carpeta temporal privada que se elimina después. El instalador oficial gestiona sus archivos y cambios de PATH. No se ejecuta durante la instalación npm/pnpm ni en CI o con `HOPDECK_NOPROMPT=1`.
7
+ - El inicio de sesión se realiza con `claude auth login` o `codex login`, con entrada y salida directas a la terminal. Hopdeck no lee, copia ni guarda credenciales; solo recuerda si queda pendiente completar ese paso. Desinstalar Hopdeck conserva las CLI y sus cuentas.
6
8
  - 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.
7
9
  - Escribe solo en tu equipo:
8
10
  - `~/.hopdeck.json` (preferencias: proyectos fijados, ocultos, recientes…) y `~/.hopdeck-cache.json` (índice de títulos y primeros mensajes, con permisos solo para tu usuario).
package/bin/hopdeck.js CHANGED
@@ -14,7 +14,7 @@ let provider;
14
14
  try { provider = require('../lib/provider'); }
15
15
  catch (err) { if (require.main !== module) throw err; console.error(err.message); process.exit(2); }
16
16
  const codexHistory = require('../lib/codex-history');
17
- const { findExecutable } = require('../lib/executable');
17
+ const providerSetup = require('../lib/provider-setup');
18
18
 
19
19
  const { LANG, T } = require('../lib/i18n');
20
20
  const { showWelcome } = require('../lib/welcome');
@@ -1916,6 +1916,7 @@ function diffRows(rows) {
1916
1916
  }
1917
1917
 
1918
1918
  function render() {
1919
+ if (!active) return;
1919
1920
  if (EMBED) return renderEmbed();
1920
1921
  const cols = process.stdout.columns || 100, rows = process.stdout.rows || 30;
1921
1922
  const lines = SIDEBAR ? frameTree(cols, rows) : frame(cols, rows);
@@ -1957,14 +1958,28 @@ const extraArgs = [];
1957
1958
  /** Busca el ejecutable real de claude en el PATH (no depende de funciones del shell). */
1958
1959
  /** Busca un programa en el PATH (por defecto `claude`). Recuerda el resultado mientras el archivo siga existiendo. */
1959
1960
  function findClaude(name = 'claude') {
1960
- return findExecutable(name);
1961
+ return providerSetup.findProvider(name);
1961
1962
  }
1962
1963
 
1964
+ const ensureSelectedProvider = () => providerSetup.ensureProvider({ id: provider.id, config: CFG, save: saveCfg, ask: readKey, T,
1965
+ install: () => providerSetup.installProvider(provider.id), run: providerSetup.runCommand });
1966
+ let settingUpProvider = false;
1967
+
1963
1968
  /** El id de una sesión sale del nombre de su archivo; solo se pasa a `claude --resume` si es un identificador normal. */
1964
1969
  const safeId = (id) => /^[A-Za-z0-9._-]{1,128}$/.test(String(id || ''));
1965
1970
 
1966
- function launch(project, session) {
1971
+ async function launch(project, session) {
1967
1972
  if (session && !safeId(session.id)) { flash(T.badId); return; }
1973
+ if (!findClaude(provider.id)) {
1974
+ if (settingUpProvider) return;
1975
+ settingUpProvider = true;
1976
+ const wasActive = active; leave(); codexHistory.close();
1977
+ let ready = false;
1978
+ try { ready = await ensureSelectedProvider(); }
1979
+ catch (error) { process.stdout.write(clean(error.message) + '\n'); }
1980
+ finally { settingUpProvider = false; if (wasActive) { enter(); render(); } }
1981
+ if (!ready) return flash(T.setupUnavailable(provider.label, provider.id));
1982
+ }
1968
1983
  if (SIDEBAR) return launchSlot(project, session);
1969
1984
  if (EMBED) return embedLaunch(project, session);
1970
1985
  if (!fs.existsSync(project.cwd)) { flash(T.missing + ': ' + shortPath(project.cwd)); return; }
@@ -2073,8 +2088,22 @@ function splash(done, total) {
2073
2088
  async function run() {
2074
2089
  if (!process.stdin.isTTY || !process.stdout.isTTY) { printList(); return; }
2075
2090
  if (!SIDEBAR && process.env.HOPDECK_INSIDE) { console.log(T.inside); return; }
2076
- if (!SIDEBAR) await showWelcome({ config: CFG, save: saveCfg, lang: LANG,
2077
- wait: () => readKey(k => /^[\r\n]+$/.test(k) || k === '\x1b' ? true : undefined) });
2091
+ if (!SIDEBAR) {
2092
+ if (process.env.HOPDECK_WELCOME_DONE) { CFG.welcomeSeen = true; saveCfg(); }
2093
+ await showWelcome({ config: CFG, save: saveCfg, lang: LANG,
2094
+ wait: () => readKey(k => /^[\r\n]+$/.test(k) || k === '\x1b' ? true : undefined) });
2095
+ if (!provider.explicit && !provider.preferred && providerSetup.canPrompt()) {
2096
+ const selected = await providerSetup.chooseProvider({ ask: readKey, T });
2097
+ if (!selected) return;
2098
+ CFG.defaultProvider = selected; saveCfg();
2099
+ if (selected !== provider.id) {
2100
+ process.exitCode = await providerSetup.runCommand(process.execPath, [__filename, '--provider', selected, ...provider.args],
2101
+ { env: { ...process.env, HOPDECK_PROVIDER: selected, HOPDECK_WELCOME_DONE: '1' }, timeout: 0 });
2102
+ return;
2103
+ }
2104
+ }
2105
+ if (!await ensureSelectedProvider()) { if (!providerSetup.canPrompt()) process.exitCode = 1; return; }
2106
+ }
2078
2107
  if (!SIDEBAR) await offerShortcut(); // primera vez: ¿quieres que `claude` abra Hopdeck?
2079
2108
  if (!SIDEBAR) {
2080
2109
  // Por defecto se usa el terminal integrado (vista previa al pasar el cursor, imágenes). tmux solo con HOPDECK_TMUX=1,
@@ -7,7 +7,7 @@ const path = require('path');
7
7
  const fs = require('fs');
8
8
  const { fileURLToPath } = require('url');
9
9
  const { sniffExt } = require('./images');
10
- const { findExecutable } = require('./executable');
10
+ const { findProvider } = require('./provider-setup');
11
11
  const { baseName, tidy } = require('./text');
12
12
 
13
13
  class CodexClient {
@@ -18,7 +18,7 @@ class CodexClient {
18
18
  start() {
19
19
  if (this.ready) return this.ready;
20
20
  this.ready = (async () => {
21
- const bin = this.bin || findExecutable('codex');
21
+ const bin = this.bin || findProvider('codex');
22
22
  if (!bin) throw new Error('Codex CLI not found in PATH');
23
23
  const batch = process.platform === 'win32' && /\.(cmd|bat)$/i.test(bin);
24
24
  this.batch = batch;
package/lib/executable.js CHANGED
@@ -2,17 +2,17 @@
2
2
  const fs = require('fs');
3
3
  const path = require('path');
4
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)) {
5
+ function findExecutable(name, { env = process.env, platform = process.platform } = {}) {
6
+ const pathKey = Object.keys(env).find((k) => k.toLowerCase() === 'path') || 'PATH';
7
+ const key = platform + '\0' + name + '\0' + env[pathKey] + '\0' + env.PATHEXT, hit = found.get(key);
8
+ if (hit) { try { if (fs.statSync(hit).isFile()) return hit; } catch { /* search again */ } found.delete(key); }
9
+ const win = platform === 'win32', paths = win ? path.win32 : path.posix;
10
+ const exts = win ? (env.PATHEXT || '.EXE;.CMD;.BAT').split(';').concat(['']) : [''];
11
+ for (const dir of (env[pathKey] || '').split(win ? ';' : ':')) {
12
12
  if (!dir) continue;
13
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 */ }
14
+ const file = paths.join(dir, name + ext.toLowerCase());
15
+ try { if (fs.statSync(file).isFile()) { found.set(key, file); return file; } } catch { /* next */ }
16
16
  }
17
17
  }
18
18
  return null;
package/lib/i18n.js CHANGED
@@ -51,6 +51,17 @@ const T = {
51
51
  searchPh: 'buscar conversación o proyecto…', found: (n) => `${n} ${n === 1 ? 'resultado' : 'resultados'}`, noRes: (q) => `Sin resultados para «${q}»`,
52
52
  searchingContent: 'Buscando dentro de las conversaciones…', tryContent: 'Pulsa Tab para buscar también dentro del contenido', inContent: 'en el contenido', kClear: 'limpiar', kEdit: 'editar', kEsc: 'salir',
53
53
  inside: 'Ya estás dentro de Hopdeck (F1 para ir a la lista de proyectos).',
54
+ setupChoose: '¿Qué quieres usar con Hopdeck?', setupChoices: '[1] Claude Code [2] Codex [Esc] salir',
55
+ setupMissing: (name) => `${name} todavía no está instalado.`,
56
+ setupInstallInfo: 'Hopdeck puede descargar y ejecutar el instalador oficial para tu cuenta. Requiere internet.',
57
+ setupSource: (url) => `Origen: ${url}`, setupInstallKeys: '[Enter] Instalar ahora [Esc] salir',
58
+ setupInstalling: (name) => `Instalando ${name}…`, setupInstalled: (name) => `${name} instalado y listo.`,
59
+ setupFailed: (name) => `No se pudo preparar ${name}.`, setupRetryKeys: '[r] Reintentar [Enter/Esc] salir',
60
+ setupCancelled: 'Instalación cancelada. Puedes volver a abrir Hopdeck para intentarlo más tarde.',
61
+ setupUnavailable: (name, id) => `${name} no está disponible. Abre hopdeck --provider ${id} en una terminal interactiva para instalarlo.`,
62
+ setupLoginInfo: (name) => `Inicia sesión con ${name}. La CLI oficial gestiona tu cuenta y la autenticación.`,
63
+ setupLoginKeys: '[Enter] Iniciar sesión [m] Más tarde [Esc] salir', setupLoginDone: 'Sesión iniciada. Continuando a tus proyectos…',
64
+ setupLoginFailed: 'No se completó el inicio de sesión. Puedes reintentarlo o continuar más tarde.',
54
65
  },
55
66
  en: {
56
67
  projects: 'PROJECTS', sessions: 'SESSIONS', newChat: 'New conversation',
@@ -100,12 +111,24 @@ const T = {
100
111
  searchPh: 'search conversation or project…', found: (n) => `${n} ${n === 1 ? 'result' : 'results'}`, noRes: (q) => `No results for “${q}”`,
101
112
  searchingContent: 'Searching inside the conversations…', tryContent: 'Press Tab to also search inside the content', inContent: 'in content', kClear: 'clear', kEdit: 'edit', kEsc: 'exit',
102
113
  inside: 'You are already inside Hopdeck (F1 jumps to the project list).',
114
+ setupChoose: 'What would you like to use with Hopdeck?', setupChoices: '[1] Claude Code [2] Codex [Esc] quit',
115
+ setupMissing: (name) => `${name} is not installed yet.`,
116
+ setupInstallInfo: 'Hopdeck can download and run the official installer for your account. Internet access is required.',
117
+ setupSource: (url) => `Source: ${url}`, setupInstallKeys: '[Enter] Install now [Esc] quit',
118
+ setupInstalling: (name) => `Installing ${name}…`, setupInstalled: (name) => `${name} is installed and ready.`,
119
+ setupFailed: (name) => `Could not set up ${name}.`, setupRetryKeys: '[r] Retry [Enter/Esc] quit',
120
+ setupCancelled: 'Installation cancelled. Open Hopdeck again to try later.',
121
+ setupUnavailable: (name, id) => `${name} is unavailable. Open hopdeck --provider ${id} in an interactive terminal to install it.`,
122
+ setupLoginInfo: (name) => `Sign in with ${name}. The official CLI manages your account and authentication.`,
123
+ setupLoginKeys: '[Enter] Sign in [m] Later [Esc] quit', setupLoginDone: 'Signed in. Continuing to your projects…',
124
+ setupLoginFailed: 'Sign-in did not finish. You can retry or continue later.',
103
125
  },
104
126
  }[LANG];
105
127
 
106
128
  // Product-specific copy follows the selected CLI; interface text remains shared.
107
129
  if (require('./provider').isCodex) {
108
130
  for (const [key, value] of Object.entries(T)) {
131
+ if (key.startsWith('setup')) continue;
109
132
  const adapt = (text) => typeof text === 'string' ? text.replace(/Claude Code/g, 'Codex CLI').replace(/Claude/g, 'Codex').replace(/claude/g, 'codex') : text;
110
133
  if (typeof value === 'string') T[key] = adapt(value);
111
134
  else if (typeof value === 'function') T[key] = (...args) => adapt(value(...args));
package/lib/links.js CHANGED
@@ -11,6 +11,15 @@ function webUrl(text) {
11
11
  function urlAt(term, y, col) {
12
12
  const buffer = term.buffer.active, row = buffer.viewportY + y, line = buffer.getLine(row);
13
13
  if (!line || col < 0 || col >= term.cols) return null;
14
+ let cell = line.getCell(col);
15
+ if (cell?.getWidth() === 0 && col > 0) cell = line.getCell(col - 1);
16
+ // xterm 6 keeps OSC 8 destinations on cells, even when only a label is drawn.
17
+ // Headless has no public link lookup API; keep its version-specific access here.
18
+ const linkId = cell?.extended?.urlId;
19
+ if (linkId) {
20
+ try { return webUrl(term._core?._oscLinkService?.getLinkData(linkId)?.uri); }
21
+ catch { return null; }
22
+ }
14
23
  const maxRows = Math.max(1, Math.ceil(16384 / term.cols)); let start = row, end = row;
15
24
  while (start > 0 && row - start < maxRows && buffer.getLine(start)?.isWrapped) start--;
16
25
  while (end + 1 < buffer.length && end - start < maxRows && buffer.getLine(end + 1)?.isWrapped) end++;
@@ -0,0 +1,151 @@
1
+ 'use strict';
2
+ const fs = require('fs');
3
+ const os = require('os');
4
+ const path = require('path');
5
+ const cp = require('child_process');
6
+ const { findExecutable } = require('./executable');
7
+ const { clean } = require('./style');
8
+
9
+ const PROVIDERS = {
10
+ claude: { label: 'Claude Code', origin: 'https://claude.ai', shell: 'bash', login: ['auth', 'login'], status: ['auth', 'status'] },
11
+ codex: { label: 'Codex', origin: 'https://chatgpt.com/codex', shell: 'sh', login: ['login'], status: ['login', 'status'] },
12
+ };
13
+ function installerFor(id, platform = process.platform) {
14
+ const info = PROVIDERS[id];
15
+ if (!info || !['win32', 'darwin', 'linux'].includes(platform)) throw new Error('Unsupported provider or platform');
16
+ return { ...info, url: info.origin + (platform === 'win32' ? '/install.ps1' : '/install.sh'), interpreter: platform === 'win32' ? 'powershell.exe' : info.shell };
17
+ }
18
+ function canPrompt({ env = process.env, input = process.stdin, output = process.stdout } = {}) {
19
+ return !!input.isTTY && !!output.isTTY && !env.HOPDECK_NOPROMPT && !(env.CI && !['0', 'false'].includes(env.CI));
20
+ }
21
+ function findProvider(id, { env = process.env, platform = process.platform, home = os.homedir(), find = findExecutable } = {}) {
22
+ if (!PROVIDERS[id]) return find(id, { env, platform });
23
+ const hit = find(id, { env, platform }); if (hit) return hit;
24
+ const paths = platform === 'win32' ? path.win32 : path.posix, win = platform === 'win32';
25
+ const dirs = [paths.join(home, '.local', 'bin')];
26
+ if (id === 'codex') {
27
+ if (env.CODEX_INSTALL_DIR && paths.isAbsolute(env.CODEX_INSTALL_DIR)) dirs.unshift(env.CODEX_INSTALL_DIR);
28
+ if (win && env.LOCALAPPDATA) dirs.push(paths.join(env.LOCALAPPDATA, 'Programs', 'OpenAI', 'Codex', 'bin'));
29
+ }
30
+ for (const dir of dirs) {
31
+ const file = paths.join(dir, id + (win ? '.exe' : ''));
32
+ try {
33
+ if (!fs.statSync(file).isFile()) continue;
34
+ if (!win) fs.accessSync(file, fs.constants.X_OK);
35
+ const key = Object.keys(env).find((k) => k.toLowerCase() === 'path') || 'PATH';
36
+ env[key] = dir + (win ? ';' : ':') + (env[key] || '');
37
+ return file;
38
+ } catch { /* another installation location */ }
39
+ }
40
+ return null;
41
+ }
42
+
43
+ // Bounded HTTPS download. Only installerFor() supplies the initial URL.
44
+ async function downloadInstaller(url, file, fetchImpl = fetch) {
45
+ const allowed = Object.keys(PROVIDERS).flatMap((id) => ['win32', 'linux'].map((platform) => installerFor(id, platform).url));
46
+ if (!allowed.includes(url)) throw new Error('Unknown installer source');
47
+ const signal = AbortSignal.timeout(45000);
48
+ for (let redirects = 0; redirects <= 5; redirects++) {
49
+ const target = new URL(url);
50
+ if (target.protocol !== 'https:' || target.username || target.password) throw new Error('Installer requires HTTPS');
51
+ const response = await fetchImpl(url, { redirect: 'manual', signal });
52
+ if ([301, 302, 303, 307, 308].includes(response.status)) {
53
+ await response.body?.cancel();
54
+ const location = response.headers.get('location'); if (!location) throw new Error('Invalid installer redirect');
55
+ url = new URL(location, url).href; continue;
56
+ }
57
+ if (!response.ok || !response.body) throw new Error('Installer download failed (HTTP ' + response.status + ')');
58
+ const reader = response.body.getReader(), chunks = []; let size = 0;
59
+ try {
60
+ while (true) {
61
+ const { done, value } = await reader.read(); if (done) break;
62
+ size += value.byteLength; if (size > 2 * 1024 * 1024) throw new Error('Installer download is too large');
63
+ chunks.push(Buffer.from(value));
64
+ }
65
+ } finally { await reader.cancel().catch(() => {}); }
66
+ const data = Buffer.concat(chunks);
67
+ if (!data.length || /^\s*(?:<!doctype|<html)/i.test(data.toString('utf8', 0, 80))) throw new Error('Invalid installer response');
68
+ fs.writeFileSync(file, data, { mode: 0o600, flag: 'wx' }); return;
69
+ }
70
+ throw new Error('Too many installer redirects');
71
+ }
72
+
73
+ function runCommand(bin, args, { env = process.env, stdio = 'inherit', timeout = 600000 } = {}) {
74
+ return new Promise((resolve, reject) => {
75
+ let command = bin, argv = args, verbatim = false;
76
+ if (process.platform === 'win32' && /\.(cmd|bat)$/i.test(bin)) {
77
+ if (/["%\r\n]/.test(bin) || args.some((arg) => !/^[\w-]+$/.test(arg))) return reject(new Error('Unsupported batch command'));
78
+ command = env.ComSpec || 'cmd.exe'; argv = ['/d', '/v:off', '/s', '/c', `""${bin}" ${args.join(' ')}"`]; verbatim = true;
79
+ }
80
+ const child = cp.spawn(command, argv, { env: { ...env, HOPDECK_SKIP: '1' }, stdio, windowsHide: true, windowsVerbatimArguments: verbatim });
81
+ let timedOut = false, interrupted = false;
82
+ const stop = () => {
83
+ if (process.platform === 'win32' && child.pid) cp.spawnSync('taskkill.exe', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true, timeout: 5000 });
84
+ else child.kill();
85
+ };
86
+ const onInterrupt = () => { interrupted = true; stop(); };
87
+ process.on('SIGINT', onInterrupt);
88
+ const timer = timeout > 0 ? setTimeout(() => { timedOut = true; stop(); }, timeout) : null;
89
+ const cleanup = () => { clearTimeout(timer); process.removeListener('SIGINT', onInterrupt); };
90
+ child.once('error', (error) => { cleanup(); reject(error); });
91
+ child.once('close', (code) => { cleanup(); resolve(interrupted ? 130 : timedOut ? 124 : code ?? 1); });
92
+ });
93
+ }
94
+
95
+ async function installProvider(id, { platform = process.platform, env = process.env, find = findExecutable, download = downloadInstaller, run = runCommand } = {}) {
96
+ const plan = installerFor(id, platform);
97
+ const interpreter = find(plan.interpreter, { env, platform }) || (platform === 'win32' && find('pwsh.exe', { env, platform }));
98
+ if (!interpreter) throw new Error('Required interpreter: ' + plan.interpreter);
99
+ const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'hopdeck-provider-')));
100
+ try {
101
+ const file = path.join(dir, platform === 'win32' ? 'install.ps1' : 'install.sh');
102
+ await download(plan.url, file);
103
+ const args = platform === 'win32'
104
+ ? ['-NoLogo', '-NoProfile', '-Command', "$ErrorActionPreference='Stop'; & ([ScriptBlock]::Create([IO.File]::ReadAllText($env:HOPDECK_INSTALL_SCRIPT)))"] : [file];
105
+ return await run(interpreter, args, { env: { ...env, ...(id === 'codex' ? { CODEX_NON_INTERACTIVE: '1' } : {}), HOPDECK_INSTALL_SCRIPT: file } });
106
+ } finally {
107
+ // The random directory belongs to this invocation; never remove a computed parent.
108
+ if (path.dirname(dir) === fs.realpathSync(os.tmpdir()) && path.basename(dir).startsWith('hopdeck-provider-')) fs.rmSync(dir, { recursive: true, force: true });
109
+ }
110
+ }
111
+
112
+ async function chooseProvider({ ask, T, output = process.stdout }) {
113
+ output.write('\n » Hopdeck\n\n ' + T.setupChoose + '\n ' + T.setupChoices + '\n');
114
+ return ask((key) => key === '1' ? 'claude' : key === '2' ? 'codex' : key === '\x1b' || /^[qQ]$/.test(key) ? null : undefined);
115
+ }
116
+
117
+ async function ensureProvider({ id, config, save, ask, T, env = process.env, input = process.stdin, output = process.stdout,
118
+ find = () => findProvider(id, { env }), install = () => installProvider(id, { env }), run = runCommand }) {
119
+ const info = installerFor(id), interactive = canPrompt({ env, input, output });
120
+ let bin = find(), approved = false;
121
+ if (!bin && !interactive) { output.write(T.setupUnavailable(info.label, id) + '\n'); return false; }
122
+ while (!bin) {
123
+ if (!approved) {
124
+ output.write('\n » Hopdeck\n\n ' + T.setupMissing(info.label) + '\n ' + T.setupInstallInfo + '\n ' + T.setupSource(info.url) + '\n\n ' + T.setupInstallKeys + '\n');
125
+ approved = await ask((key) => /^[\r\n]+$/.test(key) || /^[syi]$/i.test(key) ? true : key === '\x1b' || /^[nq]$/i.test(key) ? false : undefined);
126
+ if (!approved) { output.write(T.setupCancelled + '\n'); return false; }
127
+ }
128
+ try {
129
+ output.write('\n ' + T.setupInstalling(info.label) + '\n');
130
+ const code = await install(); if (code === 130) return false; if (code !== 0) throw new Error('Installer exit: ' + code);
131
+ bin = find(); if (!bin || await run(bin, ['--version'], { env, stdio: 'ignore', timeout: 15000 }) !== 0) throw new Error('Installed command unavailable');
132
+ config.providerLoginPending = true; save(); output.write('\n ' + T.setupInstalled(info.label) + '\n');
133
+ } catch (error) {
134
+ bin = null; output.write('\n ' + T.setupFailed(info.label) + '\n ' + clean(error.message).slice(0, 300) + '\n ' + T.setupRetryKeys + '\n');
135
+ if (!await ask((key) => /^[rR]$/.test(key) ? true : /^[\r\n]+$/.test(key) || key === '\x1b' ? false : undefined)) return false;
136
+ }
137
+ }
138
+ if (!config.providerLoginPending || !interactive) return true;
139
+ try { if (await run(bin, info.status, { env, stdio: 'ignore', timeout: 15000 }) === 0) { config.providerLoginPending = false; save(); return true; } } catch { /* ask the CLI to authenticate */ }
140
+ while (true) {
141
+ output.write('\n ' + T.setupLoginInfo(info.label) + '\n ' + T.setupLoginKeys + '\n');
142
+ const choice = await ask((key) => /^[\r\n]+$/.test(key) ? 'login' : /^[mM]$/.test(key) ? 'later' : key === '\x1b' ? 'quit' : undefined);
143
+ if (choice !== 'login') return choice === 'later';
144
+ let code = 1; try { code = await run(bin, info.login, { env }); } catch { /* preserve pending login */ }
145
+ if (code === 130) return false;
146
+ if (code === 0) { config.providerLoginPending = false; save(); output.write(T.setupLoginDone + '\n'); return true; }
147
+ output.write(T.setupLoginFailed + '\n');
148
+ }
149
+ }
150
+
151
+ module.exports = { installerFor, canPrompt, findProvider, downloadInstaller, runCommand, installProvider, chooseProvider, ensureProvider };
package/lib/provider.js CHANGED
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
  const path = require('path');
3
3
  const os = require('os');
4
+ const fs = require('fs');
4
5
 
5
6
  // Hopdeck options precede the options forwarded to the selected CLI.
6
7
  function parseProvider(argv, fallback = 'claude') {
@@ -12,12 +13,20 @@ function parseProvider(argv, fallback = 'claude') {
12
13
  return { id, args };
13
14
  }
14
15
 
15
- const selected = parseProvider(require.main && /hopdeck\.js$/.test(require.main.filename) ? process.argv.slice(2) : [], process.env.HOPDECK_PROVIDER || 'claude');
16
+ const argv = require.main && /hopdeck\.js$/.test(require.main.filename) ? process.argv.slice(2) : [];
17
+ let preferred = null;
18
+ try {
19
+ const value = JSON.parse(fs.readFileSync(process.env.HOPDECK_CONFIG || path.join(os.homedir(), '.hopdeck.json'), 'utf8')).defaultProvider;
20
+ if (['claude', 'codex'].includes(value)) preferred = value;
21
+ } catch { /* first run */ }
22
+ const explicit = !!process.env.HOPDECK_PROVIDER || argv[0] === '--provider' || !!argv[0]?.startsWith('--provider=');
23
+ const selected = parseProvider(argv, process.env.HOPDECK_PROVIDER || preferred || 'claude');
16
24
  const isCodex = selected.id === 'codex';
17
25
  // Child Hopdeck instances (including tmux panes) inherit the selected provider.
18
26
  process.env.HOPDECK_PROVIDER = selected.id;
19
27
  module.exports = {
20
28
  ...selected, isCodex, parseProvider,
29
+ explicit, preferred,
21
30
  label: isCodex ? 'Codex' : 'Claude',
22
31
  configFile: path.join(os.homedir(), isCodex ? '.hopdeck-codex.json' : '.hopdeck.json'),
23
32
  launchArgs: (session, extra = []) => [...(session ? (isCodex ? ['resume', session.id] : ['--resume', session.id]) : []), ...extra],
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hopdeck",
3
- "version": "1.5.6",
3
+ "version": "1.6.0",
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",
@@ -43,7 +43,7 @@
43
43
  "wsl"
44
44
  ],
45
45
  "scripts": {
46
- "test": "node --test test/unit.test.js test/e2e.test.js test/ui.test.js test/codex.test.js",
46
+ "test": "node --test test/unit.test.js test/e2e.test.js test/ui.test.js test/codex.test.js test/setup.test.js",
47
47
  "doctor": "node bin/hopdeck.js doctor",
48
48
  "screenshots": "node scripts/screenshots.js",
49
49
  "demo": "node scripts/demo.js"