1134 Commits
Author SHA1 Message Date
weishu b2eeb97d27 fix: handle abort signal before and during codex spawn
Add checks to gracefully handle abort signals:
- Check if abort is already signaled before attempting spawn
- Check if abort caused the spawn error instead of rejecting
2025-12-24 17:56:51 +08:00
weishu 2b3fa635f6 fix: constrain session disabled banner width to max-w-content 2025-12-24 17:56:37 +08:00
weishu eee4489b0f docs: update all README files with comprehensive documentation
Update documentation across the project to reflect current state of codebase:
- cli/README.md: Add all commands (codex, gemini, daemon subcommands, doctor, mcp),
  configuration options, storage locations, and source structure references
- server/README.md: Add complete HTTP API reference, Socket.IO events, Telegram bot
  features, core logic descriptions, and source structure
- web/README.md: Add all routes, feature descriptions, authentication flow, data
  fetching, real-time updates, and source structure
- README.md: Improve feature list clarity, add HTTPS exposure instructions in
  quickstart, add multi-agent support section
2025-12-24 17:56:07 +08:00
weishu 852c7f4c4e Licenses 2025-12-24 17:35:19 +08:00
weishu 2a10ce9675 feat: add support for user message events from Codex
Add sendUserMessage() method to ApiSessionClient and CodexSession to handle
user_message events from Codex. Updates CodexConversionResult type and
convertCodexEvent() to process user_message payloads, with test coverage.
2025-12-24 17:24:16 +08:00
weishu 7f2a36117c feat: add Spinner and LoadingState components for unified loading UX
Introduces two reusable loading components to standardize loading states:
- Spinner: Base spinner with accessibility support (role, aria-label)
- LoadingState: Semantic loading indicator combining spinner and label

Updates loading patterns across the app:
- Full-screen/block loading now uses LoadingState (App, router, files, file)
- Inline button loading states show spinner + text with aria-busy
- Message list loading replaced with MessageSkeleton component
- Removes duplicate SpinnerIcon definition from PermissionFooter

Improves UX and accessibility:
- Loading screens centered and full-height
- Consistent ellipsis character (…)
- Semantic accessibility (role="status", aria-live, aria-busy)
- Adds CSS variables for banner styling
2025-12-24 17:23:39 +08:00
weishu 9b9f792ff6 fix: navigate to parent path generically in useAppGoBack instead of hardcoded /sessions 2025-12-24 16:26:20 +08:00
weishu a2edd88d93 refactor: rename normalizedMessagesCount to renderedMessagesCount for clarity 2025-12-24 15:37:21 +08:00
weishu 0bb5dcc086 fix: add 300ms debounce to sync banner display
Debounce the sync banner to only show if sync takes longer than 300ms.
This prevents the banner from flashing on quick syncs while still showing
for slower operations.

Changes:
- Added DEBOUNCE_MS constant (300ms)
- Changed doStartSync to delay banner display by 300ms
- Changed endSync to immediately clear all timeouts
- Renamed endSyncTimeoutRef to startDelayTimeoutRef (now for debounce)
2025-12-24 15:10:00 +08:00
weishu baaf02daf5 fix: prevent sync banner from flashing on session switches
Added isFirstConnectRef to distinguish between first SSE connection
(page load) and subsequent reconnects (session switches). Only the
first connection forces the banner to show; subsequent connects use
non-forced mode which only displays the banner when returning from
background within 30s, eliminating unwanted banner flashes on
session changes.
2025-12-24 15:10:00 +08:00
weishu 3e4b8ddc64 refactor: remove non-allinone build scripts and fix npm publish build command
Remove build:cli:exe and build:cli:exe:all scripts since building executables
without web assets serves no practical purpose. Update npm publish script to use
build:single-exe:all which includes embedded web assets in published packages.
2025-12-24 15:04:26 +08:00
weishu 6078c136bb style: unify button and link colors to black/white theme 2025-12-24 14:49:25 +08:00
weishu 85c2dc10ea feat: add npx/bunx binary distribution support
Adds infrastructure for distributing Hapi via npm as a scoped package
(@twsxtd/hapi) with platform-specific optional dependencies. This enables
installation via `npx @twsxtd/hapi` or `bunx @twsxtd/hapi`.

- Add bin/hapi.js wrapper script for platform detection and binary selection
- Create npm/ directory structure for platform-specific packages (darwin-{arm64,x64},
  linux-{arm64,x64}, win32-x64)
- Add scripts/prepare-npm-packages.ts to generate platform-specific package.json files
  and copy binaries to npm packages
- Add scripts/publish-npm.ts for automated publishing of platform packages
- Update package.json with new scoped name, bin entry, optionalDependencies, and
  prepack/publish scripts
- Update .gitignore to ignore generated npm packages and build outputs
- Update .npmignore to only include bin/hapi.js wrapper, excluding source and build files
2025-12-24 14:39:05 +08:00
weishu bb9c5b66d3 refactor(telegram): remove interactive features and simplify to notifications only
Remove all interactive features from the Telegram bot that are now handled by the
Telegram Mini App. The bot now serves a single purpose: sending notifications for
permission requests and ready events.

Changes:
- bot.ts: Remove /help command and message handler, simplify /start to show Mini App link
- callbacks.ts: Remove all callback handlers except APPROVE and DENY for permissions
- sessionView.ts: Remove detail views and settings, keep only notification formatting
- renderer.ts: Remove session/machine list rendering, keep utility functions

This reduces the codebase by ~1000 lines (58% reduction) while preserving notification
functionality that the Mini App cannot provide.
2025-12-24 14:23:01 +08:00
weishu 6d401fb9ec feat: add syncing banner and smart scroll behavior for chat thread
Implement two key UX improvements:

1. Syncing banner with visibility tracking:
   - New useSyncingState hook manages syncing state with safety timeout
   - Banner shows when SSE connects/reconnects
   - Auto-hides after 10s to prevent stuck spinner
   - Smart visibility detection to suppress banner when returning from background

2. Smart scroll behavior for chat thread:
   - Only auto-scrolls when user is near bottom (<120px threshold)
   - Shows "X new messages" indicator when user is reading history
   - Smooth scroll to bottom with indicator button
   - Resets state on session change

Files:
- New: useSyncingState hook for syncing state management
- New: SyncingBanner component for non-blocking indicator
- Modified: App.tsx integrates syncing with SSE handling
- Modified: HappyThread implements smart scroll with dynamic autoScroll
- Modified: index.css adds spinner and bounce-in animations
2025-12-24 14:05:55 +08:00
weishu 61ae777c3d refactor(telegram): simplify notifications and remove emoji
Remove Switch and Message notifications, update Ready notification to
use agent flavor from session metadata, and remove emoji from button
text and titles to align with happy-cli notification style.
2025-12-24 13:46:30 +08:00
weishu c09b870fe7 refactor(test): simplify keyboard input handling and extract type definitions
Remove reliance on key.name and key.sequence in favor of using input directly.
Extract TTY type definitions for clarity and add scoping constraints to prevent
variable shadowing. Update AGENTS.md documentation for accuracy.
2025-12-24 13:34:55 +08:00
weishu 1a23bfa430 refactor: remove custom executable support and simplify Claude CLI resolution
Remove support for custom executable paths and bundled Claude versions, including
deprecated environment variables HAPI_USE_BUNDLED_CLAUDE and HAPI_USE_GLOBAL_CLAUDE.
This simplifies the codebase to rely only on the global Claude CLI installation.

Updates Claude Code spawning logic to remove special handling for .js/.cjs files,
adds configurable BUN_BE_BUN environment variable handling, and streamlines path
resolution to throw an error when Claude Code CLI is not found on PATH.
2025-12-24 13:20:06 +08:00
weishu 8f804c57bf refactor: remove client-side session ID management
Remove proactive session ID generation and onSessionFound callback. Let Claude
handle session creation automatically via the SessionStart hook instead. This
simplifies the API contract and delegates session lifecycle management to Claude.
2025-12-24 10:35:20 +08:00
weishu a455cd8297 feat: add automatic CLI_API_TOKEN generation for the server
Implement secure auto-generation of CLI_API_TOKEN to eliminate mandatory
environment variable requirement. Token is generated once and persisted to
~/.hapi/settings.json for use by CLI on the same machine.

Changes:
- New cliApiToken.ts module with secure 256-bit token generation
- Configuration now accepts token from env, file, or generates on-demand
- Server displays prominently on first run, saves to settings
- CLI auth status command provides discovery hints for all scenarios
- Settings file parse errors fail fast to prevent data loss
2025-12-23 23:16:35 +08:00
weishu 706814653e fix: add friendly error messages for failed binary spawning
Added helpful error messages with cause preservation when spawning codex, gemini, or other CLI tools fails because the binary is not found in PATH. This follows the existing error handling pattern from claudeLocal.ts.
2025-12-23 20:20:51 +08:00
weishu bf7ae6fdd6 refactor(test): migrate useSwitchControls test from react-test-renderer to ink render 2025-12-23 18:43:09 +08:00
weishu 322c50e5a9 refactor(codex): extract config building and support CLI overrides in remote mode
This refactoring introduces CLI argument overrides for sandbox and approval policy settings in remote mode, allowing users to specify security constraints via `--sandbox` and `--ask-for-approval` flags.

Changes:
- Add `CodexCliOverrides` type and `parseCodexCliOverrides()` utility to parse CLI flags like `--sandbox`, `-s`, `--ask-for-approval`, `-a`, along with convenience flags (`--full-auto`, `--dangerously-bypass-approvals-and-sandbox`)
- Extract complex start config building logic into `buildCodexStartConfig()` function with proper approval policy and sandbox resolution based on permission mode
- Thread `codexCliOverrides` through the session/loop/launcher chain and apply overrides only when permission mode is 'default'
- Update `codexRemoteLauncher` to use the new config builder and display appropriate warnings based on whether overrides are present
- Add comprehensive tests for both parsing and config building functions
2025-12-23 18:43:01 +08:00
weishu a2bdc73236 refactor(web): unify max-width constraints with tailwind content class
Adds maxWidth.content: '720px' to tailwind.config.ts for centralized width management across the web app. Replaces all hardcoded max-w-[720px] references with the new max-w-content class. Adds missing max-width constraints to file.tsx, files.tsx, and SessionList.tsx. Moves border-b dividers from outer full-width divs to inner max-w-content divs for consistent visual hierarchy.
2025-12-23 18:40:51 +08:00
weishu 2bff252e6a refactor: migrate unpack-tools script from CommonJS to TypeScript 2025-12-23 18:09:12 +08:00
weishu 92996667d5 refactor: remove CommonJS ripgrep launcher and spawn binary directly
Replace the ripgrep_launcher.cjs intermediary with direct binary execution.
This simplifies the ripgrep module by spawning the binary directly instead
of going through a Node.js subprocess wrapper. Add platform-specific binary
path resolution to handle both Unix and Windows environments.
2025-12-23 18:09:12 +08:00
weishu eafd4d12a9 feat: add session cleanup script with flexible filtering options
Add cleanup-sessions.ts script that enables deletion of sessions from the database with support for multiple filtering strategies:
- Message count filtering (delete sessions with fewer than N messages)
- Path pattern matching with glob support
- Orphaned session detection (sessions whose path no longer exists)
- Optional confirmation prompt with --force flag to skip

Includes 'clean-session' npm script for convenient invocation.
2025-12-23 17:45:15 +08:00
weishu 7f9145b6de feat: add token-based authentication to session hooks
Implement hook token validation to secure session start requests.
Each hook server generates a unique token that must be provided
in the x-hapi-hook-token header. Updates hook-forwarder command
to support both positional and named arguments for port and token.
2025-12-23 16:02:04 +08:00
weishu 61d3a1bed1 feat: implement session tracking via Claude hooks
Adds a dedicated hook server infrastructure to receive Claude SessionStart
notifications. This allows the CLI to track session ID changes (new sessions,
resume, compact, fork, etc.) without relying on file watchers.

Changes:
- Add SessionFound callback system to AgentSessionBase for session tracking
- Create hook server that listens for POST requests from Claude's hooks
- Generate temporary settings files with hook command configuration
- Implement session hook forwarder CLI command to relay hook data
- Integrate hook server into runClaude with proper cleanup
- Pass hookSettingsPath through local and remote execution paths
- Update SDK query builder to support --settings flag
2025-12-23 16:02:04 +08:00
weishu e637f2bb27 refactor(web): simplify NewSession component layout with divided sections
Replace Card wrapper with a flex column layout using dividers for better visual separation and simpler structure.
2025-12-23 15:53:42 +08:00
weishu 422018299c refactor(web): redesign SessionList component with enhanced session metadata
Replace Card-based layout with semantic button elements for better accessibility and keyboard navigation. Add session metadata fields (flavor, activeAt, modelMode) and implement helper functions to format session information including agent flavor, model mode, and relative last-seen timestamps. Update hover styles and add focus-visible indicators.
2025-12-23 14:17:15 +08:00
weishu f81e585eef refactor(daemon): use mtime-based version detection instead of string comparison
Replace CLI version string comparison with file modification time (mtime) based detection. This provides a more reliable way to detect when the CLI binary has been updated, especially for bun-compiled executables where package.json may not be accessible.

Changes:
- Add getInstalledCliMtimeMs() utility to check CLI binary or package.json mtime
- Store startedWithCliMtimeMs in daemon state on startup
- Use mtime comparison in version check loop for daemon auto-restart
- Move version flag handling to early CLI startup before daemon initialization
- Fix machine active state merging to prefer newer activeAt timestamp

This improves daemon restart behavior when CLI is updated via package managers.
2025-12-23 13:14:15 +08:00
weishu c8f7a23f2f feat(web): add continue hint in HappyComposer when switching to remote mode
When switching from local mode to remote mode, the placeholder text now
suggests users can type "continue" to resume interrupted tasks. This helps
users understand they can continue where they left off after experiencing
permission prompts that were stuck in the terminal during local mode.
2025-12-23 11:13:37 +08:00
weishu 88cce9c28d refactor: remove CommonJS launchers and use claude command directly
Remove local Claude launcher scripts and refactor to invoke the global
claude command from PATH. This simplifies the launcher logic and removes
the need to maintain separate CommonJS entry points.

Changes:
- Delete cli/scripts/claude_local_launcher.cjs, claude_remote_launcher.cjs,
  and claude_version_utils.cjs
- Update claudeLocal to spawn 'claude' command directly instead of using
  a launcher script
- Remove runtimePath dependency and launcher existence checks
- Add DISABLE_AUTOUPDATER environment variable for local mode
- Improve error messages when claude command is not found
- Add shell option for Windows compatibility in process spawning
- Remove unused imports from claudeLocal and index files
2025-12-23 10:21:50 +08:00
weishu f132a7dc79 feat(codex): implement CLI argument passthrough for codex
Collect unknown CLI arguments from index.ts and pass them through the execution chain (runCodex → loop → CodexSession → codexLocalLauncher → codexLocal), similar to how claude already works. This enables users to pass CLI arguments like --model and --sandbox to the underlying codex process.

Filter out the 'resume' subcommand which is managed internally by hapi, while allowing other CLI arguments to pass through. Add warning log in remote mode when CLI args are ignored since remote mode uses message-based configuration instead. Include unit tests for the resume filtering logic.
2025-12-23 09:06:08 +08:00
weishu 0128792495 refactor: remove thinking state tracking from local launcher 2025-12-23 08:25:44 +08:00
weishu 93810689ad refactor(ui): extract switch controls logic into reusable hook and terminal restoration utility
Extracts duplicated exit/switch confirmation handling from CodexDisplay and RemoteModeDisplay into a custom useSwitchControls hook. Centralizes terminal state restoration (raw mode, keyboard protocol cleanup) into a restoreTerminalState utility function used across codex modules. Improves code reusability and maintainability.
2025-12-22 23:12:24 +08:00
weishu 360e3a9919 refactor: extract session and loop logic into reusable agent base classes 2025-12-22 23:12:24 +08:00
weishu aef3ed367b refactor(web): move message loading header into HappyThread with infinite scroll
Move the message loading header UI and infinite scroll logic from SessionChat into HappyThread component. This improves component isolation and adds IntersectionObserver-based automatic loading with proper scroll position preservation and error handling.
2025-12-22 21:45:34 +08:00
weishu 999ee64852 refactor(web): unify session creation into single page with path history 2025-12-22 21:45:11 +08:00
weishu 4290f539bd refactor(codex): extract session management and launcher logic into separate modules
Reorganized runCodex.ts to improve maintainability by extracting:
- CodexSession class for session lifecycle management
- CodexLocalLauncher and CodexRemoteLauncher for mode-specific initialization
- CodexEventConverter for MCP message handling and UI buffer updates
- CodexSessionScanner for resume file discovery
- emitReadyIfIdle utility for ready event emission

Added codexSessionId field to metadata schema for session tracking.
Updated UI components to work with refactored architecture.
2025-12-22 19:14:47 +08:00
weishu 0c16b7b215 feat(web): improve token refresh handling with automatic 401 retry and focus-based refresh 2025-12-22 18:29:32 +08:00
weishu 439778c875 fix(web): enable auto-scroll and add key prop to HappyThread component 2025-12-22 18:11:07 +08:00
weishu 0aab06ca47 fix(cli): resolve path alias with bun link using bunfig.toml configuration
When the cli package is symlinked via `bun link`, tsconfig.json's `rootDir: ".."`
interferes with the `@/*` path alias resolution at runtime. Add bunfig.toml to
explicitly configure path aliases for Bun's runtime to fix the module resolution error.
2025-12-22 16:44:27 +08:00
weishu d057daabfe chore: migrate cli distribution from npm to bun executable
Migrate HAPI CLI from npm-based distribution to Bun single-executable format:
- Remove npm bin wrappers (bin/happy.mjs, bin/happy-mcp.mjs)
- Simplify package.json: remove npm publish config (exports, main, module, types, files, publishConfig)
- Update bin entry to point to TypeScript source (src/index.ts)
- Migrate shebang from Node to Bun (#!/usr/bin/env bun)
- Simplify build scripts: remove npm-specific steps (pkgroll, prepublishOnly, release-it)
- Update spawnHappyCLI to support compiled binaries and development TypeScript mode
- Update daemon/doctor diagnostics for new process detection logic
- Production: use `bun build --compile` for single-executable releases
- Development: run TypeScript directly via `bun src/index.ts` or `tsx src/index.ts`
2025-12-22 16:44:20 +08:00
weishu fd94a684dc fix(cli): improve error message categorization for better UX
- Connection errors (ECONNREFUSED, ETIMEDOUT, ENOTFOUND, "Network Error") show
  a friendly message with the server URL and network troubleshooting hints
- Authentication errors (401, 403, "unauthorized", "forbidden") suggest running
  `hapi auth login` to help users resolve auth issues
- Use case-insensitive matching (toLowerCase) to reliably catch error message
  variants
2025-12-22 12:34:52 +08:00
weishu f16ccb2759 fix(web): handle null values in permissionMode and modelMode using nullish coalescing
The settings popup in HappyComposer did not show any option selected when
permissionMode or modelMode was null, since destructuring defaults only
handle undefined, not null. This fix uses the ?? operator to properly
handle both null and undefined cases, falling back to 'default' in both.
2025-12-22 12:25:01 +08:00
weishu aacab0be51 feat(web): add auto-focus to composer input on desktop devices only
Adds touch device detection via media query (pointer: coarse) to prevent
triggering virtual keyboard on mobile. Input auto-focus is now conditional
on desktop environments where it improves keyboard-based interactions.
2025-12-22 09:46:03 +08:00
weishu dbcbc93ad0 feat: improve codex permission elicitation with parameter extraction and reason support
- Add robust parameter extraction helpers in codexMcpClient
- Implement buildElicitationResult to construct properly formatted MCP responses
- Support dynamic requested schemas with fallback handling
- Add reason/explanation tracking through permission decision flow
- Improve type safety with explicit extraction and validation
2025-12-22 09:27:20 +08:00
weishu 6505c58bf3 feat: make Telegram optional and unify user authentication with owner ID
- Make TELEGRAM_BOT_TOKEN and ALLOWED_CHAT_IDS optional environment variables
- Add telegramEnabled flag to conditionally initialize the bot on startup
- Introduce persistent owner ID for unified user identity across web and Telegram auth
- Update Telegram bot to accept configuration in constructor instead of using global config
- Handle empty allowlist by showing chat ID prompt on /start command
- Use owner ID instead of Telegram user ID for API authentication
- Add conditional Telegram support checks in auth routes with clear error messages
- Update documentation to explain optional Telegram configuration and binding workflow
- Rename telegramUserId to userId in auth middleware for clarity
2025-12-22 08:52:51 +08:00