Skip to content

feat: fallback session titles from the first prompt - #31

Merged
rubenperezrial merged 12 commits into
mainfrom
feat/session-title-fallback
Oct 5, 2026
Merged

rubenperezrial merged 12 commits into
mainfrom
feat/session-title-fallback

Conversation

@rubenperezrial

Copy link
Copy Markdown

Por qué

Todas las sesiones creadas desde Telegram aparecían como New session - <ISO>. El servidor de OpenCode asigna ese título por defecto y su agente title solo lo sustituye una vez, tras el primer mensaje; si esa llamada falla, el error se ignora y no se reintenta (issues upstream #30662, #31042, #13710; caso documentado con modelos del proveedor opencode/opencode-go). El bot no puede arreglar el upstream, así que añade un fallback propio.

Qué incluye

1. Fallback en el bot. Cuando el bot crea una sesión y al terminar el primer turno el título sigue siendo el default del servidor, el bot lo actualiza con el contenido del primer mensaje del usuario (primera línea, saneada, máx. 64 chars).

Cubre las 3 vías de creación de sesión del bot:

  • src/bot/handlers/prompt.ts — auto-creación al primer mensaje sin sesión activa.
  • src/bot/commands/new-command.ts — /new + primer mensaje.
  • src/bot/callbacks/command-catalog-callback-handler.ts — comandos del catálogo.

Helpers puros en src/app/utils/session-title.ts (isDefaultSessionTitle, deriveTitleFromPrompt con corte en palabra y sin partir pares surrogate) y estado en memoria en src/app/services/session-title-fallback-service.ts. El intento se dispara al quedar idle la sesión (event-subscription-service.ts), de modo que si OpenCode sí generó un título propio, el suyo se conserva.

2. Script de backfill scripts/backfill-session-titles.ts (dry-run por defecto) para renombrar sesiones ya existentes que siguen con el título default usando su primer mensaje de usuario.

Decisión: no pisar títulos propios

  • Sesiones con título propio (generado por OpenCode o renombrado a mano) no se tocan nunca: al aplicar el pendiente se relee el título y, si ya no es default, se descarta.
  • Solo se programa para sesiones creadas por el bot en la ejecución actual; las preexistentes adjuntadas no se renombran por escribir en ellas.
  • El script, igualmente, solo actúa sobre títulos default.
  • Si el título de OpenCode llega más tarde, gana el suyo (mejor).

Verificación

  • Tests nuevos: tests/app/utils/session-title.test.ts, tests/app/services/session-title-fallback-service.test.ts, tests/bot/services/session-title-fallback-idle.test.ts, tests/scripts/backfill-session-titles.test.ts; adaptados tests/bot/handlers/prompt.test.ts, tests/bot/commands/new.test.ts, tests/bot/commands/commands.test.ts.
  • Suite completa y gate: bun run check → EXIT=0 (2015 pass / 3 skip / 0 fail, 179 ficheros), eslint limpio.
  • Backfill: bun run scripts/backfill-session-titles.ts --dry-run real contra el servidor local (6 GET, 0 PATCH; títulos derivados recalculados 5/5 coincidentes); --apply validado contra servidor falso (solo PATCH a default, errores por sesión continúan). --apply no se ha ejecutado en real.
  • E2E del hook idle con SDK real interceptando fetch; regex contra 5 títulos default reales del servidor: 5/5 match; regresión de surrogate cubierta por test.

Notas

Adds a keyboard row above the agent/context grid that switches to the other project in one tap. Target: the project the last switch moved away from (settings.swapProject), falling back to the most recently active other project. The press is allowed while the session is busy: it detaches the running session instead of blocking. i18n for all locales and PRODUCT.md updated.
The project list can return entries without a name (cached session directories), which made the swap confirmation show the full worktree path.
The bottom keyboard now shows a single model button carrying the active thinking-effort variant; the separate variant button is gone. Tapping it opens the model list as before, and picking a model still opens the variant picker after the confirmation. Picking the already-active model now re-opens the variant picker with the current variant marked instead of silently resetting it to default; when the model offers no variant choice, a toast explains it. Also updated tests and PRODUCT.md.
The provider browser callback handler was defined twice with identical bodies; the second definition silently won at runtime. Keep a single copy.
- saved sessions: bottom-keyboard "Sessions" button with a menu to
  bookmark the current session (per project), open a bookmarked one, or
  drop it; bookmarks live in settings.json
- prompt queue: the per-message menu now works while the session is busy,
  a dispatch skipped by a busy re-mark is retried instead of stranding the
  queue, and abort / project switch report the prompts they discard; the
  queued-button icon becomes an hourglass
- project swap: lands on the target project's most recent session and
  releases the detached session's local busy and run state
… project swap

- adopt the session variant when present; otherwise keep the effective variant (same model) or resolve the model's configured default
- resolve the effective variant centrally (getStoredModel/getCurrentVariant share resolveVariant), also for the prompt
- drop the synthetic Default row from the variant picker; a lone real variant is still offered when it is not the active one
- tests: session adoption, resolution regressions (real config), variant menu (mocked and real-catalog chains)
- let the ⭐ button and the saved-menu callbacks through the busy guard
- bookmarking/dropping entries are local; opening another session detaches the active run (same semantics as the project swap)
- tests: busy-guard matrix with real modules and handler integration
- strip trailing commas (string-aware) before JSON.parse; warn once when the config cannot be loaded
- keeps config-based variant defaults (reasoningEffort) working with real-world opencode.jsonc files
- tests: mixed JSONC fixture, invalid-config warn-once, adversarial string/URL cases
@rubenperezrial

Copy link
Copy Markdown
Author

--apply escribe sin releer el título (TOCTOU) — severidad baja, latente

Dónde: scripts/backfill-session-titles.ts:156 (el filtro de sesiones default se calcula una sola vez sobre el snapshot de session.list) y scripts/backfill-session-titles.ts:185-189 (el session.update se emite sin volver a mirar el título actual). El script solo llama a session.list y session.messages; no hace ningún session.get por sesión antes de escribir.

Qué pasa: si el título de una sesión deja de ser default entre el LIST y su PATCH, --apply pisa ese título bueno con el derivado. El escenario real es una sesión en vuelo cuyo agente title de OpenCode termina mientras corre el script (o un /rename manual del usuario durante la ejecución): para las 5 sesiones que hay ahora mismo en el servidor están todas paradas desde el 2026-09-26, así que hoy la carrera no se dispararía, pero el hueco queda para cualquier ejecución futura.

Por qué es un defecto y no una preferencia: el criterio del cambio es no pisar títulos propios, y el propio cuerpo de la PR afirma «el script, igualmente, solo actúa sobre títulos default». La mitad del bot sí lo respeta —session-title-fallback-service.ts:70-86 relee con session.get y descarta si el título ya no es default—, así que dentro de la misma PR las dos mitades se comportan distinto y el script es la que se salta la comprobación justo en el momento de escribir.

Reproducción (servidor falso; el snapshot se sirve con ses_race aún default y el título bueno se aplica justo después de serializar la respuesta):

GET  /session?roots=true&limit=1000   -> ses_race: "New session - 2026-10-01T10:00:00.000Z"
                                         (el título real pasa a "Titulo generado por el agente title de OpenCode")
GET  /session/ses_race/message
PATCH /session/ses_race  {"title":"prompt derivado que pisara el titulo bueno"}   <-- pisa el título bueno

Salida real del script con --apply: exit=0, título final de ses_race = "prompt derivado que pisara el titulo bueno". Con --dry-run el mismo escenario da 0 escrituras y los títulos intactos, así que el fallo es exclusivo de --apply.

Arreglo barato: antes del session.update, releer la sesión (session.get) y saltar si !isDefaultSessionTitle(session.title), igual que hace el servicio del bot; o usar el título devuelto por ese get como comprobación y contabilizarlo como skipped.

No bloquea el merge: el modo por defecto (--dry-run) es seguro y el caso real actual no se dispara. Lo señalo solo para que la garantía de «no pisar títulos propios» sea igual de cierta en el script que en el fallback del bot.

@rubenperezrial

rubenperezrial commented Sep 30, 2026 •

Copy link
Copy Markdown
Author

↪️ En respuesta a tu comentario de TOCTOU (issuecomment-5921527924):

Resuelto en 20b299f (fix: re-check the session title before the backfill update): --apply relee con session.get justo antes del session.update (scripts/backfill-session-titles.ts:189-204), salta con skipped (title changed to "...") si el título ya no es default, y el re-read no se emite en --dry-run. Verificado contra servidor falso: con ses_race renombrada entre LIST y PATCH ya no sale ningún PATCH para ella (solo para la otra default), renamed: 1 + skipped: 1 (no text: 0, title changed: 1, errors: 0) = default: 2; --dry-run hace 0 re-reads y 0 escrituras. bun test --isolate tests/scripts/backfill-session-titles.test.ts 7/7 y bash scripts/run-tests.sh 2016 pass / 0 fail.

@rubenperezrial
rubenperezrial changed the base branch from feat/session-select-last-response to main October 5, 2026 15:33
@rubenperezrial
rubenperezrial merged commit e387be9 into main Oct 5, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant