From 9195e9f5c0dbe837cedcc63376bc0505646a2c07 Mon Sep 17 00:00:00 2001 From: OnPoint-Dev-Tools Date: Mon, 16 Nov 2026 17:24:45 -0500 Subject: [PATCH 01/25] feat: add OpenTUI terminal UI and shared TUI core Move the legacy TUI's UI-independent code (agent process bridge, event parser, SSH remote quoting, Live UI protocol types, event reducer, state modules, and the logo text) into the new @onpoint-dev-tools/crewcoder-tui-core package. The legacy crewcoder-tui keeps working on top of it and stays published separately. Add @onpoint-dev-tools/crewcoder-opentui (React on OpenTUI 0.9.2, Node >=26.4): - split-footer mode: settled transcript is written once, in order, into the terminal's native scrollback; streaming replies commit finished rows live - centered welcome screen with the big wordmark (composer only on small windows), then a chat layout with the composer pinned to the bottom - Gotham background across the whole window via OSC 11, restored on exit - footer components vendored from termcn (MIT) with fixes, including removal of a global "y" key handler that approved tool calls while typing Switch the crewcoder umbrella to crewcoder-opentui as an optionalDependency so headless VPS and sandbox installs succeed without native binaries. A bare crewcoder now explains how to continue when there is no terminal, the TUI is not installed, or Node.js is too old. Update release checks, the publish workflow order, CI (Node 26 job), and docs. --- .github/workflows/sdk-check.yml | 19 + .github/workflows/sdk-release.yml | 26 +- AGENTS.md | 27 +- README.md | 22 +- crewcoder-opentui/AGENTS.md | 109 +++++ crewcoder-opentui/CLAUDE.md | 1 + crewcoder-opentui/LICENSE | 191 ++++++++ crewcoder-opentui/README.md | 113 +++++ crewcoder-opentui/THIRD_PARTY_NOTICES.md | 32 ++ crewcoder-opentui/docs/SCROLLBACK.md | 125 ++++++ crewcoder-opentui/docs/TERMCN.md | 58 +++ crewcoder-opentui/package.json | 53 +++ crewcoder-opentui/src/App.tsx | 155 +++++++ crewcoder-opentui/src/args.ts | 43 ++ crewcoder-opentui/src/cli.tsx | 66 +++ crewcoder-opentui/src/components/Home.tsx | 52 +++ .../src/components/ui/spinner.tsx | 46 ++ .../src/components/ui/tool-approval.tsx | 116 +++++ .../src/components/ui/tool-call.tsx | 128 ++++++ crewcoder-opentui/src/components/ui/types.ts | 94 ++++ crewcoder-opentui/src/footer-layout.ts | 106 +++++ crewcoder-opentui/src/footer-sizer.ts | 39 ++ crewcoder-opentui/src/hooks/use-animation.ts | 77 ++++ crewcoder-opentui/src/hooks/use-motion.ts | 16 + crewcoder-opentui/src/hooks/use-theme.ts | 19 + crewcoder-opentui/src/keybindings.ts | 49 ++ .../src/lib/terminal-themes/default.ts | 53 +++ .../src/providers/theme-provider.tsx | 101 +++++ crewcoder-opentui/src/scrollback-writer.ts | 246 +++++++++++ crewcoder-opentui/src/session-controller.ts | 158 +++++++ crewcoder-opentui/src/terminal-background.ts | 27 ++ crewcoder-opentui/src/tests/app.test.tsx | 203 +++++++++ crewcoder-opentui/src/tests/fake-bridge.ts | 51 +++ .../src/tests/footer-layout.test.ts | 95 ++++ .../src/tests/footer-sizer.test.ts | 40 ++ .../src/tests/keybindings-args.test.ts | 39 ++ .../src/tests/scrollback-writer.test.ts | 108 +++++ .../src/tests/session-controller.test.ts | 120 +++++ .../src/tests/terminal-background.test.ts | 26 ++ .../src/tests/transcript.test.ts | 61 +++ crewcoder-opentui/src/theme.ts | 58 +++ crewcoder-opentui/src/transcript.ts | 110 +++++ crewcoder-opentui/tsconfig.build.json | 4 + crewcoder-opentui/tsconfig.json | 10 + crewcoder-opentui/vitest.config.ts | 22 + crewcoder-tui-core/LICENSE | 191 ++++++++ crewcoder-tui-core/README.md | 51 +++ crewcoder-tui-core/package.json | 51 +++ .../src/bridge/crewcoder-process.ts | 0 .../src/bridge/event-parser.ts | 0 .../src/bridge/live-ui-protocol.ts | 0 .../src/bridge/remote-connection.ts | 0 .../src/state/effort-levels.ts | 0 .../src/state/event-reducer.ts | 0 .../src/state/git-status.ts | 0 .../src/state/image-attachment.ts | 0 .../src/state/tui-store.ts | 0 .../src/state/usage.ts | 0 .../src/tests/event-reducer.test.ts | 0 .../src/tests/image-attachment.test.ts | 0 .../src/tests/live-ui-protocol.test.ts | 0 .../src/tests/remote-connection.test.ts | 0 .../src/tests/tui-store.test.ts | 0 .../src/tests/usage.test.ts | 0 .../src/theme/logo.ts | 0 crewcoder-tui-core/tsconfig.build.json | 4 + crewcoder-tui-core/tsconfig.json | 8 + crewcoder-tui-core/vitest.config.ts | 9 + crewcoder-tui/AGENTS.md | 28 +- crewcoder-tui/README.md | 15 +- crewcoder-tui/docs/CLI_LAUNCH.md | 10 +- crewcoder-tui/package.json | 10 +- .../src/bridge/live-ui-controller.ts | 2 +- crewcoder-tui/src/bridge/live-ui-frame.ts | 2 +- crewcoder-tui/src/bridge/live-ui-gate.ts | 2 +- crewcoder-tui/src/bridge/live-ui-host.ts | 2 +- crewcoder-tui/src/bridge/live-ui-registry.ts | 2 +- crewcoder-tui/src/bridge/live-ui-runtime.ts | 2 +- .../src/bridge/live-ui-session-store.ts | 2 +- crewcoder-tui/src/components/App.ts | 12 +- .../src/components/ApprovalOverlay.ts | 2 +- crewcoder-tui/src/components/Composer.ts | 6 +- crewcoder-tui/src/components/EffortOverlay.ts | 4 +- .../src/components/ExtensionUiOverlay.ts | 2 +- crewcoder-tui/src/components/Header.ts | 4 +- crewcoder-tui/src/components/MainViewport.ts | 6 +- crewcoder-tui/src/components/RightSidebar.ts | 2 +- .../src/components/SessionsOverlay.ts | 2 +- crewcoder-tui/src/components/StatusBar.ts | 4 +- crewcoder-tui/src/components/TaskWidget.ts | 2 +- crewcoder-tui/src/tests/app-home.test.ts | 6 +- crewcoder-tui/src/tests/app-input.test.ts | 2 +- crewcoder-tui/src/tests/app-live-ui.test.ts | 6 +- crewcoder-tui/src/tests/app-why.test.ts | 2 +- .../src/tests/checkpoint-settings.test.ts | 4 +- .../src/tests/composer-history.test.ts | 4 +- crewcoder-tui/src/tests/composer.test.ts | 2 +- crewcoder-tui/src/tests/diff-viewer.test.ts | 2 +- .../src/tests/extension-ui-overlay.test.ts | 2 +- crewcoder-tui/src/tests/goal-command.test.ts | 2 +- crewcoder-tui/src/tests/header.test.ts | 4 +- crewcoder-tui/src/tests/image-wiring.test.ts | 4 +- .../src/tests/live-ui-controller.test.ts | 2 +- crewcoder-tui/src/tests/live-ui-frame.test.ts | 2 +- crewcoder-tui/src/tests/live-ui-host.test.ts | 2 +- .../src/tests/live-ui-registry.test.ts | 2 +- .../src/tests/live-ui-runtime.test.ts | 2 +- .../src/tests/live-ui-trust-gate.test.ts | 2 +- crewcoder-tui/src/tests/main-viewport.test.ts | 4 +- .../src/tests/picker-overlay.test.ts | 2 +- .../src/tests/provider-defaults.test.ts | 4 +- .../src/tests/remote-status-bar.test.ts | 2 +- crewcoder-tui/src/tests/right-sidebar.test.ts | 4 +- .../src/tests/sessions-overlay.test.ts | 2 +- crewcoder-tui/src/tests/set-budget.test.ts | 2 +- crewcoder-tui/src/tests/status-bar.test.ts | 4 +- .../src/tests/tool-image-results.test.ts | 6 +- .../src/tests/transcript-containment.test.ts | 2 +- .../src/tests/worker-identity-command.test.ts | 4 +- crewcoder-tui/src/tui/component.ts | 2 +- crewcoder-tui/src/tui/tui.ts | 6 +- docs/INSTALLATION.md | 40 +- docs/RELEASING.md | 2 +- lib/launcher.js | 90 +++- package-lock.json | 417 +++++++++++++++++- package.json | 8 +- scripts/check-crewcoder-package.cjs | 13 +- scripts/check-sdk-release.cjs | 20 +- test/codex-progress-boundaries.test.ts | 4 +- test/codex-public-progress.test.ts | 4 +- test/launcher.test.js | 78 +++- test/release.test.js | 21 +- test/tool-mode-tui.test.ts | 4 +- tsconfig.json | 1 + 134 files changed, 4379 insertions(+), 170 deletions(-) create mode 100644 crewcoder-opentui/AGENTS.md create mode 100644 crewcoder-opentui/CLAUDE.md create mode 100644 crewcoder-opentui/LICENSE create mode 100644 crewcoder-opentui/README.md create mode 100644 crewcoder-opentui/THIRD_PARTY_NOTICES.md create mode 100644 crewcoder-opentui/docs/SCROLLBACK.md create mode 100644 crewcoder-opentui/docs/TERMCN.md create mode 100644 crewcoder-opentui/package.json create mode 100644 crewcoder-opentui/src/App.tsx create mode 100644 crewcoder-opentui/src/args.ts create mode 100644 crewcoder-opentui/src/cli.tsx create mode 100644 crewcoder-opentui/src/components/Home.tsx create mode 100644 crewcoder-opentui/src/components/ui/spinner.tsx create mode 100644 crewcoder-opentui/src/components/ui/tool-approval.tsx create mode 100644 crewcoder-opentui/src/components/ui/tool-call.tsx create mode 100644 crewcoder-opentui/src/components/ui/types.ts create mode 100644 crewcoder-opentui/src/footer-layout.ts create mode 100644 crewcoder-opentui/src/footer-sizer.ts create mode 100644 crewcoder-opentui/src/hooks/use-animation.ts create mode 100644 crewcoder-opentui/src/hooks/use-motion.ts create mode 100644 crewcoder-opentui/src/hooks/use-theme.ts create mode 100644 crewcoder-opentui/src/keybindings.ts create mode 100644 crewcoder-opentui/src/lib/terminal-themes/default.ts create mode 100644 crewcoder-opentui/src/providers/theme-provider.tsx create mode 100644 crewcoder-opentui/src/scrollback-writer.ts create mode 100644 crewcoder-opentui/src/session-controller.ts create mode 100644 crewcoder-opentui/src/terminal-background.ts create mode 100644 crewcoder-opentui/src/tests/app.test.tsx create mode 100644 crewcoder-opentui/src/tests/fake-bridge.ts create mode 100644 crewcoder-opentui/src/tests/footer-layout.test.ts create mode 100644 crewcoder-opentui/src/tests/footer-sizer.test.ts create mode 100644 crewcoder-opentui/src/tests/keybindings-args.test.ts create mode 100644 crewcoder-opentui/src/tests/scrollback-writer.test.ts create mode 100644 crewcoder-opentui/src/tests/session-controller.test.ts create mode 100644 crewcoder-opentui/src/tests/terminal-background.test.ts create mode 100644 crewcoder-opentui/src/tests/transcript.test.ts create mode 100644 crewcoder-opentui/src/theme.ts create mode 100644 crewcoder-opentui/src/transcript.ts create mode 100644 crewcoder-opentui/tsconfig.build.json create mode 100644 crewcoder-opentui/tsconfig.json create mode 100644 crewcoder-opentui/vitest.config.ts create mode 100644 crewcoder-tui-core/LICENSE create mode 100644 crewcoder-tui-core/README.md create mode 100644 crewcoder-tui-core/package.json rename {crewcoder-tui => crewcoder-tui-core}/src/bridge/crewcoder-process.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/bridge/event-parser.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/bridge/live-ui-protocol.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/bridge/remote-connection.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/state/effort-levels.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/state/event-reducer.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/state/git-status.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/state/image-attachment.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/state/tui-store.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/state/usage.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/tests/event-reducer.test.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/tests/image-attachment.test.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/tests/live-ui-protocol.test.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/tests/remote-connection.test.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/tests/tui-store.test.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/tests/usage.test.ts (100%) rename {crewcoder-tui => crewcoder-tui-core}/src/theme/logo.ts (100%) create mode 100644 crewcoder-tui-core/tsconfig.build.json create mode 100644 crewcoder-tui-core/tsconfig.json create mode 100644 crewcoder-tui-core/vitest.config.ts diff --git a/.github/workflows/sdk-check.yml b/.github/workflows/sdk-check.yml index 86b917b..5c8ddae 100644 --- a/.github/workflows/sdk-check.yml +++ b/.github/workflows/sdk-check.yml @@ -6,6 +6,8 @@ on: - "crewcoder-agent/**" - "crewcoder-client/**" - "crewcoder-tui/**" + - "crewcoder-tui-core/**" + - "crewcoder-opentui/**" - "crewcoder-sdk/**" - "bin/**" - "lib/**" @@ -23,6 +25,8 @@ on: - "crewcoder-agent/**" - "crewcoder-client/**" - "crewcoder-tui/**" + - "crewcoder-tui-core/**" + - "crewcoder-opentui/**" - "crewcoder-sdk/**" - "bin/**" - "lib/**" @@ -50,3 +54,18 @@ jobs: cache: npm - run: npm ci --ignore-scripts - run: npm run release:check:sdk + + opentui: + # OpenTUI's native layer needs Node.js >=26.4, so its renderer tests run on a + # separate runtime from the Node 22 packages. + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: 26 + cache: npm + - run: npm ci --ignore-scripts + - run: npm run test -w @onpoint-dev-tools/crewcoder-tui-core + - run: npm run typecheck -w @onpoint-dev-tools/crewcoder-opentui + - run: npm run test -w @onpoint-dev-tools/crewcoder-opentui diff --git a/.github/workflows/sdk-release.yml b/.github/workflows/sdk-release.yml index 3c096bf..b5e02a3 100644 --- a/.github/workflows/sdk-release.yml +++ b/.github/workflows/sdk-release.yml @@ -42,7 +42,9 @@ jobs: run: npm install --global npm@11.8.0 - run: npm ci --ignore-scripts - run: npm run build -w @onpoint-dev-tools/crewcoder-agent + - run: npm run build -w @onpoint-dev-tools/crewcoder-tui-core - run: npm run build -w @onpoint-dev-tools/crewcoder-tui + - run: npm run build -w @onpoint-dev-tools/crewcoder-opentui - run: npm run build -w @onpoint-dev-tools/crewcoder-client - run: npm run build -w @onpoint-dev-tools/crewcoder-sdk - name: Verify explicit publish gates @@ -59,7 +61,17 @@ jobs: fi - name: Verify published agent runtime run: node scripts/wait-for-npm-package.cjs @onpoint-dev-tools/crewcoder-agent crewcoder-agent/package.json - - name: Publish terminal UI + - name: Publish TUI core + run: | + PACKAGE_VERSION="$(node -p "require('./crewcoder-tui-core/package.json').version")" + if npm view "@onpoint-dev-tools/crewcoder-tui-core@${PACKAGE_VERSION}" version >/dev/null 2>&1; then + echo "TUI core ${PACKAGE_VERSION} is already published; continuing the partial release." + else + npm publish -w @onpoint-dev-tools/crewcoder-tui-core --access public --provenance + fi + - name: Verify published TUI core + run: node scripts/wait-for-npm-package.cjs @onpoint-dev-tools/crewcoder-tui-core crewcoder-tui-core/package.json + - name: Publish legacy terminal UI run: | PACKAGE_VERSION="$(node -p "require('./crewcoder-tui/package.json').version")" if npm view "@onpoint-dev-tools/crewcoder-tui@${PACKAGE_VERSION}" version >/dev/null 2>&1; then @@ -67,8 +79,18 @@ jobs: else npm publish -w @onpoint-dev-tools/crewcoder-tui --access public --provenance fi - - name: Verify published terminal UI + - name: Verify published legacy terminal UI run: node scripts/wait-for-npm-package.cjs @onpoint-dev-tools/crewcoder-tui crewcoder-tui/package.json + - name: Publish OpenTUI terminal UI + run: | + PACKAGE_VERSION="$(node -p "require('./crewcoder-opentui/package.json').version")" + if npm view "@onpoint-dev-tools/crewcoder-opentui@${PACKAGE_VERSION}" version >/dev/null 2>&1; then + echo "OpenTUI terminal UI ${PACKAGE_VERSION} is already published; continuing the partial release." + else + npm publish -w @onpoint-dev-tools/crewcoder-opentui --access public --provenance + fi + - name: Verify published OpenTUI terminal UI + run: node scripts/wait-for-npm-package.cjs @onpoint-dev-tools/crewcoder-opentui crewcoder-opentui/package.json - name: Publish browser client run: | PACKAGE_VERSION="$(node -p "require('./crewcoder-client/package.json').version")" diff --git a/AGENTS.md b/AGENTS.md index 2a1d273..f837024 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -55,9 +55,11 @@ Update corresponding Docs `crewcoder-agent/docs/*`, `crewcoder-tui/docs/*`, and ## CLI umbrella package -The public root `crewcoder` package is the one-command installer and launcher for both scoped runtime packages. Its `crewcoder` and `crew` bins must open `@onpoint-dev-tools/crewcoder-tui` with no arguments and forward argument-bearing invocations to `@onpoint-dev-tools/crewcoder-agent`. Never restore the `cc` alias because it shadows the standard Unix C compiler command. Keep both runtime dependencies in the root package and publish the umbrella only after those exact versions exist on npm. +The public root `crewcoder` package is the one-command installer and launcher. Its `crewcoder` and `crew` bins open `@onpoint-dev-tools/crewcoder-opentui` with no arguments and forward argument-bearing invocations to `@onpoint-dev-tools/crewcoder-agent`. Never restore the `cc` alias because it shadows the standard Unix C compiler command. The agent is a required dependency; `crewcoder-opentui` is an **optionalDependency** because it needs Node.js >=26.4 and OpenTUI native binaries, and headless VPS/sandbox installs must succeed without it. Do not make it required. For a bare call, `lib/launcher.js` refuses with guidance (legacy UI and agent commands) when there is no interactive terminal, the TUI is not installed, or Node.js is below the TUI's `engines.node` floor; it adds `--disable-warning=ExperimentalWarning` only for the TUI child. Publish the umbrella only after the exact pinned versions exist on npm. -The scoped agent package still provides `crewcoder`, `crew`, and `crewcoder-agent`; the scoped TUI package provides `crewcoder-tui` for independent development and packaging. +`@onpoint-dev-tools/crewcoder-tui` is the legacy custom-renderer UI. It is published separately for users who prefer it and must not be an umbrella dependency. Both UIs share `@onpoint-dev-tools/crewcoder-tui-core` (bridge, event parser, reducer, state); keep UI-independent code there instead of duplicating it. See `crewcoder-opentui/README.md` for the OpenTUI preview's ported and missing features. + +The scoped agent package still provides `crewcoder`, `crew`, and `crewcoder-agent`; its own bare invocation launches the legacy `crewcoder-tui` from `PATH`. The scoped TUI packages provide `crewcoder-tui` and `crewcoder-opentui` for independent installs. ## MonoRepo DIR @@ -65,10 +67,18 @@ CODING AGENT - /home/aura/my-cmd/CrewCoder-Mono/crewcoder/crewcoder-agent -TUI +TUI (OpenTUI, launched by the umbrella; Node.js >=26.4) + +- /home/aura/my-cmd/CrewCoder-Mono/crewcoder/crewcoder-opentui + +Legacy TUI - /home/aura/my-cmd/CrewCoder-Mono/crewcoder/crewcoder-tui +Shared TUI runtime (bridge, reducer, state) + +- /home/aura/my-cmd/CrewCoder-Mono/crewcoder/crewcoder-tui-core + SDK - /home/aura/my-cmd/CrewCoder-Mono/crewcoder/crewcoder-sdk @@ -209,9 +219,7 @@ crewcoder/ ├── tsconfig.json └── src/ ├── cli.ts - ├── bridge/ - │ ├── crewcoder-process.ts - │ └── event-parser.ts + ├── bridge/ # live-ui-*.ts; agent bridge lives in crewcoder-tui-core ├── components/ │ ├── App.ts │ ├── CommandPalette.ts @@ -227,11 +235,6 @@ crewcoder/ │ ├── markdown-renderer.ts │ ├── modal-view.ts │ └── path-suggestions.ts - ├── state/ - │ ├── effort-levels.ts - │ ├── event-reducer.ts - │ ├── tui-store.ts - │ └── usage.ts ├── tests/ │ ├── app-home.test.ts │ ├── app-input.test.ts @@ -276,7 +279,7 @@ crewcoder/ - Durable `/goal` behavior belongs to CrewCoder's detached supervisor (`goal-store.ts` / `goal-runner.ts`), not provider adapters. When `goals.checkModel` is configured, its same-provider tool-free verifier verdict is authoritative; verifier failures must pause rather than fall back to maker self-grading. Goals wait durably for explicit approvals. - Crew task sidebar labels are session-local presentation numbers that restart at `1` and remain stable across status sorting. Crew task tools and persisted dependency edges must continue using project-wide durable task IDs. - CI transports (`action.yml`, the GitLab template, and `scripts/run-ci.sh`) must preserve `run --ci` stdout JSON and exit codes. `crewcoder hook install` may only update its managed marker block, must back up unrelated hooks before an explicit force replacement, and must refuse shared/global hook paths outside the repository. -- Coordinated releases use `npm run release -- ` to bump the umbrella, agent, browser client, and SDK together while preserving the independent TUI version. Keep `scripts/release.cjs` synchronized with those manifests, exact internal dependency pins, runtime version constants, generated version API baselines, the root lockfile, and the protected npm publishing workflow. Automatic API baseline refreshes may only change the client and SDK `api/version.d.ts` files. +- Coordinated releases use `npm run release -- ` to bump the umbrella, agent, browser client, and SDK together while preserving the independent `crewcoder-tui`, `crewcoder-tui-core`, and `crewcoder-opentui` versions (publish order: agent, tui-core, both TUIs, client, SDK, umbrella). Keep `scripts/release.cjs` synchronized with those manifests, exact internal dependency pins, runtime version constants, generated version API baselines, the root lockfile, and the protected npm publishing workflow. Automatic API baseline refreshes may only change the client and SDK `api/version.d.ts` files. - Validate provider stream changes with package-local checks using isolated env: `CREWCODER_HOME=/tmp/.crewcoder npm run typecheck -w @onpoint-dev-tools/crewcoder-agent` `env -u OPENCODE_API_KEY CREWCODER_HOME=/tmp/.crewcoder npm test -w @onpoint-dev-tools/crewcoder-agent` diff --git a/README.md b/README.md index 83e0552..f5f16d7 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,7 @@ This directory is an npm-workspaces monorepo for the CrewCoder Packages. The roo ## Install CrewCoder -Requires Node.js 22 or newer. The `crewcoder` umbrella package includes both the CrewCoder agent and terminal UI. +Requires Node.js 22 or newer for the agent. The terminal UI that bare `crewcoder` opens ([`crewcoder-opentui`](crewcoder-opentui/README.md), a preview built on OpenTUI) needs Node.js 26.4 or newer and is an optional part of the install: on older Node.js, unsupported platforms, or headless machines, `crewcoder` still installs and every agent command works. The original UI stays available as the [legacy `crewcoder-tui`](crewcoder-tui/README.md) package on Node.js 22+. ### Try it with npx @@ -34,7 +34,7 @@ Requires Node.js 22 or newer. The `crewcoder` umbrella package includes both the npx crewcoder ``` -`npx` downloads CrewCoder into npm's cache and launches the TUI without creating a persistent global installation. +`npx` downloads CrewCoder into npm's cache and launches the TUI without creating a persistent global installation. Without Node.js 26.4+ or an interactive terminal, it prints how to continue instead. ### Install globally @@ -73,24 +73,29 @@ The scoped packages remain available separately for development and custom packa ```sh npm install --global @onpoint-dev-tools/crewcoder-agent -npm install --global @onpoint-dev-tools/crewcoder-tui +npm install --global @onpoint-dev-tools/crewcoder-tui # legacy UI, Node.js 22+ +npm install --global @onpoint-dev-tools/crewcoder-opentui # OpenTUI UI, Node.js 26.4+ ``` -Installing only `@onpoint-dev-tools/crewcoder-agent` does not install the TUI. Most CLI users should install the `crewcoder` umbrella package. See the [installation guide](docs/INSTALLATION.md) for install and update details. +Installing only `@onpoint-dev-tools/crewcoder-agent` does not install a TUI; its own bare `crewcoder` opens `crewcoder-tui` when that is on `PATH`. Most CLI users should install the `crewcoder` umbrella package. See the [installation guide](docs/INSTALLATION.md) for install and update details. ## Packages | Package | npm name | Runs on | What it is | Install command | |---|---|---|---|---| -| CrewCoder umbrella | `crewcoder` | Node.js 22+ terminal | Recommended CLI package containing both the agent and TUI. | +| CrewCoder umbrella | `crewcoder` | Node.js 22+ (TUI: 26.4+) | Recommended CLI package: the agent plus the optional OpenTUI terminal UI. | `npm install --global crewcoder` | | [`crewcoder-agent`](https://github.com/OnPoint-Dev-Tools/crewcoder/tree/main/crewcoder-agent) | [`@onpoint-dev-tools/crewcoder-agent`](https://www.npmjs.com/package/@onpoint-dev-tools/crewcoder-agent) | Node.js 22+ / standalone binary | The agent harness: evented agent loop, providers, local tools, durable sessions, goals, crews, extensions, ACP and fleet servers, and the `crewcoder` / `crew` CLI. | `npm install --global @onpoint-dev-tools/crewcoder-agent` | -| [`crewcoder-tui`](https://github.com/OnPoint-Dev-Tools/crewcoder/tree/main/crewcoder-tui) | [`@onpoint-dev-tools/crewcoder-tui`](https://www.npmjs.com/package/@onpoint-dev-tools/crewcoder-tui) | Node.js 22+ terminal | Custom terminal UI (no Ink/React/blessed/curses) driven by the agent's JSON event stream, locally or over SSH. | `npm install --global @onpoint-dev-tools/crewcoder-tui` | +| [`crewcoder-opentui`](https://github.com/OnPoint-Dev-Tools/crewcoder/tree/main/crewcoder-opentui) | [`@onpoint-dev-tools/crewcoder-opentui`](https://www.npmjs.com/package/@onpoint-dev-tools/crewcoder-opentui) | Node.js 26.4+ terminal | Preview terminal UI built on OpenTUI and React; opened by bare `crewcoder`. Not yet at parity with the legacy UI. | `npm install --global @onpoint-dev-tools/crewcoder-opentui` | +| [`crewcoder-tui`](https://github.com/OnPoint-Dev-Tools/crewcoder/tree/main/crewcoder-tui) | [`@onpoint-dev-tools/crewcoder-tui`](https://www.npmjs.com/package/@onpoint-dev-tools/crewcoder-tui) | Node.js 22+ terminal | Legacy custom terminal UI (no Ink/React/blessed/curses) driven by the agent's JSON event stream, locally or over SSH. | `npm install --global @onpoint-dev-tools/crewcoder-tui` | +| [`crewcoder-tui-core`](https://github.com/OnPoint-Dev-Tools/crewcoder/tree/main/crewcoder-tui-core) | [`@onpoint-dev-tools/crewcoder-tui-core`](https://www.npmjs.com/package/@onpoint-dev-tools/crewcoder-tui-core) | Node.js 22+ | Shared, UI-independent TUI runtime: agent process bridge, event parser, reducer, and state. | Installed by both TUIs | | [`crewcoder-sdk`](https://github.com/OnPoint-Dev-Tools/crewcoder/tree/main/crewcoder-sdk) | [`@onpoint-dev-tools/crewcoder-sdk`](https://www.npmjs.com/package/@onpoint-dev-tools/crewcoder-sdk) | Node.js 22+ host process | Supported TypeScript API for embedding CrewCoder in-process, plus an authenticated fleet client for remote runners. | `npm install --global @onpoint-dev-tools/crewcoder-sdk` | | [`crewcoder-client`](https://github.com/OnPoint-Dev-Tools/crewcoder/tree/main/crewcoder-client) | [`@onpoint-dev-tools/crewcoder-client`](https://www.npmjs.com/package/@onpoint-dev-tools/crewcoder-client) | Browsers, Electron renderers, webviews | Browser-safe client for authenticated CrewCoder runners. Web-platform APIs only: no Node.js imports, no local files, no tool execution, no stored provider credentials. | `npm install --global @onpoint-dev-tools/crewcoder-client` | Package READMEs: [agent](https://github.com/OnPoint-Dev-Tools/crewcoder/blob/main/crewcoder-agent/README.md) · -[tui](https://github.com/OnPoint-Dev-Tools/crewcoder/blob/main/crewcoder-tui/README.md) · +[opentui](https://github.com/OnPoint-Dev-Tools/crewcoder/blob/main/crewcoder-opentui/README.md) · +[tui (legacy)](https://github.com/OnPoint-Dev-Tools/crewcoder/blob/main/crewcoder-tui/README.md) · +[tui-core](https://github.com/OnPoint-Dev-Tools/crewcoder/blob/main/crewcoder-tui-core/README.md) · [sdk](https://github.com/OnPoint-Dev-Tools/crewcoder/blob/main/crewcoder-sdk/README.md) · [client](https://github.com/OnPoint-Dev-Tools/crewcoder/blob/main/crewcoder-client/README.md) @@ -168,7 +173,8 @@ Run one workspace directly: ```sh npm run dev -w @onpoint-dev-tools/crewcoder-agent npm run typecheck -w @onpoint-dev-tools/crewcoder-sdk -npm run dev -w @onpoint-dev-tools/crewcoder-tui +npm run dev -w @onpoint-dev-tools/crewcoder-tui # legacy UI +mise exec node@26 -- npm run dev -w @onpoint-dev-tools/crewcoder-opentui # OpenTUI UI, Node.js 26.4+ ``` ## TypeScript SDK and browser client diff --git a/crewcoder-opentui/AGENTS.md b/crewcoder-opentui/AGENTS.md new file mode 100644 index 0000000..249b522 --- /dev/null +++ b/crewcoder-opentui/AGENTS.md @@ -0,0 +1,109 @@ +# AGENTS.md + +## Project + +This package is `@onpoint-dev-tools/crewcoder-opentui`, CrewCoder's OpenTUI + React +terminal UI and the UI that the `crewcoder` umbrella's bare invocation launches. +`@onpoint-dev-tools/crewcoder-tui` is the separately published legacy UI; do not +delete or deprecate it without the owner's decision. + +crewcoder and crewcode are two different apps. Everything here is CrewCoder. + +## Runtime boundary + +- `engines.node` is `>=26.4.0` because OpenTUI loads its native layer through Node FFI. + The umbrella launcher reads that exact field; keep it a simple `>=x.y.z` range and keep + `scripts/check-sdk-release.cjs` in sync if it changes. +- This package must stay an **optionalDependency** of the umbrella and must never become a + dependency of `crewcoder-agent`, `crewcoder-sdk`, `crewcoder-client`, or + `crewcoder-tui-core`. Headless VPS/sandbox installs must not pull OpenTUI native binaries. +- Pin `@opentui/*` to exact versions; they are pre-1.0. + +## Shared runtime + +Bridge, event parsing, reducer, and state live in `@onpoint-dev-tools/crewcoder-tui-core` +and are shared with the legacy UI. Do not copy them into this package or reimplement the +agent loop here. Event rendering must follow the guardrails in +[`crewcoder-tui/AGENTS.md`](../crewcoder-tui/AGENTS.md#event-rendering-guardrails): +thinking stays a separate block, user `background` renders muted and separate from typed +text, approvals are live control-channel state resolved through the bridge. + +## Native scrollback (split-footer) + +The renderer runs in `split-footer` with `externalOutputMode: "capture-stdout"`; never +switch back to the alternate screen. The transcript belongs in the terminal's native +scrollback, written by `ScrollbackWriter`; the React tree renders only the footer. See +`docs/SCROLLBACK.md`. + +- Write each block exactly once and in order. Track committed blocks by identity (the + reducer trims and re-slices `state.blocks`), never by index. +- Only `streaming` blocks (the last assistant/thinking block of an active run) may commit + rows early, and always hold back the last row. This relies on the reducer appending to + them only; if a block type starts changing in place, classify it `live` in `blockPhase`. +- The first `live` block stops the writer. With no active run every block is `final`. +- Keep commits chunked under the OpenTUI per-commit cell limit. +- `attachScrollback` must run before the footer mounts so `pending` is current on render. +- The welcome screen shows only while `isHome` (no blocks, not running) and sizes the + footer from `renderer.terminalHeight`, never `useTerminalDimensions()` (that is the + footer's own size in split-footer mode). Keep the big logo centered; it is the owner's + landing identity. Below 70 columns or when too short, show only the composer; do not + bring back the compact or mini logo (owner rejected them). +- After the first message the composer must stay pinned to the bottom with the Gotham + background across the whole window. Preserve the mechanisms in `docs/SCROLLBACK.md` + "Footer geometry": OSC 11/111 written outside the renderer lifetime, the welcome + transition sized before writing and writes deferred until `footerSettled`, fresh-screen + `leadingRows` padding, `RESERVED_ROWS`, `trailingNewline` on final commits, and all + other sizing after `writer.sync`. Footer sizing never lives in a React effect. +- Verify layout changes in a real terminal (detached `tmux` on its own socket with a fake + agent via `CREWCODER_BIN`); the test renderer does not model split-footer scrolling. +- Footer rows are fixed height (`height={1}`, `wrapMode="none"`, `flexShrink={0}`) and + `footerModel().rows` must equal what `App` renders; update both together. + +## termcn components + +Footer components are vendored from termcn and owned here (`docs/TERMCN.md`, +`THIRD_PARTY_NOTICES.md`). Do not run `npx shadcn add` into this package: its `@/` aliases +break the tsc/NodeNext build. When vendoring or updating a component: + +- Remove global `useKeyboard` handlers. Upstream `tool-approval` approved on a bare `y` + while the user typed; keys go through `DEFAULT_APP_KEYBINDINGS` in `App`. +- Set `flexDirection="row"` on inline rows (OpenTUI defaults to column, unlike Ink). +- Replace hardcoded colors with theme tokens and stop timers when idle. +- Never default an unknown approval risk to a level; map the agent's + `safe | review | dangerous` explicitly (`riskLevel`). +- Record changes in the file header and the `docs/TERMCN.md` table. + +## Code rules + +- `App.tsx` stays presentational. Session behavior belongs in `SessionController`; + display conversion and block phases belong in the pure `transcript.ts`. +- Route every key check through `DEFAULT_APP_KEYBINDINGS` / `matchesAction`; never compare + key names inline. +- Agent text must pass through `normalize()` before rendering. +- Unported slash commands must report that they are unavailable; never send them to the + agent as prompts. +- The composer `` is uncontrolled; clear it through the ref after submit. A + controlled `value=""` does not reset it because the prop never changes. + +## Verification + +```bash +mise exec node@26 -- npm run typecheck -w @onpoint-dev-tools/crewcoder-opentui +mise exec node@26 -- npm test -w @onpoint-dev-tools/crewcoder-opentui +``` + +Tests that protect current behavior: + +```txt +src/tests/session-controller.test.ts run/resume/follow-up/approval/abort/new, unported commands +src/tests/transcript.test.ts row mapping, block phases, control stripping +src/tests/scrollback-writer.test.ts order, single commit, streaming hold-back, live blocking, trimmed arrays +src/tests/footer-layout.test.ts footer row math, reserved rows, approval height, streaming tail, home logo rule +src/tests/footer-sizer.test.ts welcome transition, after-write sizing, settled detection +src/tests/terminal-background.test.ts OSC 11/111 and color validation +src/tests/app.test.tsx scrollback + footer end to end; bare "y" never approves; abort, quit; + welcome screen centered, left on first prompt, restored by /new +src/tests/keybindings-args.test.ts chord matching, overrides, CLI flags +``` + +See `README.md` for what is implemented and what is not yet ported. diff --git a/crewcoder-opentui/CLAUDE.md b/crewcoder-opentui/CLAUDE.md new file mode 100644 index 0000000..43c994c --- /dev/null +++ b/crewcoder-opentui/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/crewcoder-opentui/LICENSE b/crewcoder-opentui/LICENSE new file mode 100644 index 0000000..dbb44a0 --- /dev/null +++ b/crewcoder-opentui/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2026 OnPoint Dev Tools and CrewCoder contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/crewcoder-opentui/README.md b/crewcoder-opentui/README.md new file mode 100644 index 0000000..29018d1 --- /dev/null +++ b/crewcoder-opentui/README.md @@ -0,0 +1,113 @@ +# CrewCoder OpenTUI + +`@onpoint-dev-tools/crewcoder-opentui` is CrewCoder's terminal UI built on +[OpenTUI](https://github.com/anomalyco/opentui) with React. Bare `crewcoder` from the +`crewcoder` umbrella package opens it. + +> **Preview.** This UI is not at feature parity with the legacy +> [`crewcoder-tui`](../crewcoder-tui/README.md) yet. Prefer the legacy UI if you rely on +> the commands listed under [Not yet ported](#not-yet-ported). + +## Requirements + +- **Node.js 26.4 or newer.** OpenTUI loads its native renderer through Node's FFI, which + is not available in older releases. Node marks FFI as experimental; the umbrella + launcher hides that runtime warning, but running `crewcoder-opentui` directly prints it. +- A platform with an OpenTUI native build: Linux x64/arm64 (glibc and musl), macOS + x64/arm64, Windows x64/arm64. +- An interactive terminal. + +The umbrella lists this package as an **optional** dependency, so `npm i -g crewcoder` still +succeeds on Node 22, on other platforms, and in headless sandboxes or VPS images. There, +bare `crewcoder` prints guidance instead of starting, and agent commands +(`crewcoder run ...`) work normally. + +## Usage + +```bash +crewcoder # via the umbrella package +crewcoder-opentui # this package directly +crewcoder-opentui --remote me@vps --remote-cwd /workspace [--remote-bin ] +``` + +| Key | Action | +|---|---| +| Enter | Send the prompt. While a run is active it is queued as a follow-up to that run. | +| Escape | Abort the active run. | +| Ctrl+Y / Ctrl+N | Approve / deny the pending tool approval. | +| Ctrl+C | Quit. | + +Keys come from `DEFAULT_APP_KEYBINDINGS` in `src/keybindings.ts`; there is no user +override file yet. + +Implemented now: + +- **Welcome screen**: a fresh or `/new` session opens on the big CrewCoder wordmark + centered in the terminal with the composer beneath it, like the legacy landing page. + Windows too small for the wordmark (under 70 columns, or too short) show only the + composer. The logo text is shared with the legacy UI through + `@onpoint-dev-tools/crewcoder-tui-core/theme/logo` and drawn with OpenTUI renderables in + static bold primary (the legacy color pulse is not ported). +- **Chat layout**: after the first message the composer is pinned to the bottom of the + terminal with the transcript growing upward above it, and the whole window, scrollback + included, uses the Gotham background (OSC 11, restored on exit). Idle, the row above the + composer shows the key hints. +- **Native scrollback transcript** (OpenTUI `split-footer`): settled blocks are written to + the terminal's own scrollback, in order and exactly once, and streaming replies commit + each finished row as it arrives. Terminal scrolling, search, and copy work on it, and it + stays visible after quitting. A footer below holds only what is still changing. See + [`docs/SCROLLBACK.md`](docs/SCROLLBACK.md). +- Footer components from [termcn](https://www.termcn.dev): running tools (`ToolCall`), the + pending approval card with risk level and arguments (`ToolApproval`), and the working + spinner (`Spinner`), themed in Gotham. Several upstream issues are fixed in our copies, + including a global `y` key that approved tool calls while typing. See + [`docs/TERMCN.md`](docs/TERMCN.md). +- Transcript blocks for user (with muted `background` context), assistant, thinking, tool, + approval, compaction, image, error, and system. Tool output is clamped to 12 lines. Text + is normalized to `\n` and stripped of terminal control sequences. +- Other structured blocks (goals, crews, review summaries, live UI, ...) render as a + labeled placeholder instead of being dropped. +- New runs, automatic resume of the current session, live follow-ups, approval + decisions, and abort, all through the shared `crewcoder-tui-core` bridge. +- `/new` and `/stop`. +- Remote SSH mode, using the same bridge as the legacy UI. +- Gotham colors (`#0c1014` background, `#195466` border, `#33859e` primary) as termcn + theme tokens in `src/theme.ts`. + +## Not yet ported + +Every other slash command (they report that they are unavailable instead of being sent +as prompts), the command palette, provider/model/effort/mode pickers, `/sessions` +resume, themes, the right sidebar, markdown and syntax highlighting in the transcript, +image attachments and terminal graphics, extension UI questions, compaction preview, +Live UI, assistant throughput metadata, and the crew/goal views (these show as one-line +placeholders while live and as labeled rows in scrollback). + +## Architecture + +```txt +src/cli.tsx argument parsing, split-footer renderer, React root +src/App.tsx the footer: welcome screen, or live blocks, approval card, spinner, composer, status +src/components/Home.tsx the centered welcome screen +src/footer-sizer.ts footer height and the welcome-screen transition, in step with commits +src/terminal-background.ts OSC 11 / OSC 111 theme background +src/scrollback-writer.ts commits settled blocks to native scrollback (OpenTUI surfaces) +src/footer-layout.ts pure footer model and row count for renderer.footerHeight +src/session-controller.ts owns TuiState + bridge; subscribe/getVersion for useSyncExternalStore +src/transcript.ts pure block -> display row, and block lifecycle phase +src/keybindings.ts DEFAULT_APP_KEYBINDINGS and chord matching +src/theme.ts Gotham as termcn theme tokens +src/components/ui/, src/hooks/, src/providers/, src/lib/ vendored termcn (see docs/TERMCN.md) +@onpoint-dev-tools/crewcoder-tui-core bridge, event parser, reducer, state (shared with legacy) +``` + +## Development + +```bash +mise exec node@26 -- npm run typecheck -w @onpoint-dev-tools/crewcoder-opentui +mise exec node@26 -- npm test -w @onpoint-dev-tools/crewcoder-opentui +mise exec node@26 -- npm run build -w @onpoint-dev-tools/crewcoder-opentui +``` + +Tests use OpenTUI's headless test renderer (`@opentui/react/test-utils`) and fail fast +with an explicit message on Node.js older than 26.4. diff --git a/crewcoder-opentui/THIRD_PARTY_NOTICES.md b/crewcoder-opentui/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..99e8498 --- /dev/null +++ b/crewcoder-opentui/THIRD_PARTY_NOTICES.md @@ -0,0 +1,32 @@ +# Third-party notices + +## termcn + +Files under `src/components/ui/`, `src/hooks/`, `src/providers/`, and `src/lib/terminal-themes/` +(compiled into `dist/`) are vendored from [termcn](https://github.com/shadcn-labs/termcn) +at commit `5a02dae79542add57ba392d2b51785138d0c3b6e`, some with local modifications +described in each file header. termcn is distributed under the MIT License: + +```text +MIT License + +Copyright (c) 2026 Aniket Pawar + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +``` diff --git a/crewcoder-opentui/docs/SCROLLBACK.md b/crewcoder-opentui/docs/SCROLLBACK.md new file mode 100644 index 0000000..197eef7 --- /dev/null +++ b/crewcoder-opentui/docs/SCROLLBACK.md @@ -0,0 +1,125 @@ +# Split-footer scrollback + +`crewcoder-opentui` runs OpenTUI in `split-footer` screen mode. The conversation is +written into the terminal's **native scrollback** above a small footer, the same model as +the legacy UI's scrollback transcript. Terminal scrolling, search, selection, and copy all +work on the transcript, and it stays on screen after you quit. The UI never switches to the +alternate screen. + +```txt +┌ terminal ───────────────────────────────┐ +│ YOU │ native scrollback, written once, +│ fix the tests │ in order, by ScrollbackWriter +│ │ +│ CREW CODER │ +│ Line 1 of the reply … │ finished rows of a streaming reply +├─────────────────────────────────────────┤ ← footer (React, resized per frame) +│ Line 12 of a │ streaming tail: the row still changing +│ ⠧ Working · escape to abort │ termcn Spinner +│ ╭─────────────────────────────────────╮ │ +│ │ Send a follow-up to the running turn│ │ composer +│ ╰─────────────────────────────────────╯ │ +│ provider · model · mode · session │ status +└─────────────────────────────────────────┘ +``` + +## How blocks reach scrollback + +`src/scrollback-writer.ts` (`ScrollbackWriter`) is synced on every state change via +`attachScrollback(controller, writer)`. Each reducer block is classified by +`blockPhase()` in `src/transcript.ts`: + +| Phase | Blocks | Written | +|---|---|---| +| `final` | user, system, error, finished tools, resolved approvals, … | whole, once | +| `streaming` | the last `assistant`/`thinking` block while a run is active | every finished row as text arrives; the last row is held back | +| `live` | running tools, pending approvals, pending extension questions, running compaction/validation/background jobs, active crews, Live UI | not yet; shown in the footer | + +The first `live` block stops the writer: nothing after it is written until it becomes final, +so scrollback is never out of order. When no run is active every block is `final`, so a tool +left `running` by a crashed agent cannot hold the transcript back. + +Rules the writer depends on: + +- **Identity, not index.** Committed blocks are tracked in a `WeakSet` because the reducer + trims `state.blocks` to the last 500 entries and re-slices the array. +- **Append-only streaming.** Committing rows before a block is final is only safe because the + reducer only appends to the last assistant/thinking block. If that ever changes, those + blocks must become `live`. +- **Bounded commits.** Each commit stays under about 200,000 cells (OpenTUI rejects commits + above about 349,000), so very long replies are committed in chunks. +- A blank spacer row separates blocks. A streaming block that disappears (for example after + `/new`) is dropped; rows already written stay in the terminal. + +## Theme background + +OpenTUI paints only the footer; the transcript above it is the terminal's own scrollback. +Like the legacy UI, `src/terminal-background.ts` sets the terminal's default background to +Gotham with OSC 11 at startup and restores it with OSC 111 on quit and on process exit, so +the whole window, scrollback included, carries the theme. These are written outside the +renderer's lifetime because `capture-stdout` turns stdout writes made while it runs into +plain scrollback text. Only a `#rrggbb` value may reach the escape sequence. + +## Footer geometry + +OpenTUI's inline split footer has rules the layout depends on (read from +`@opentui/core` 0.9.2 and confirmed in a real terminal): + +- The footer sits directly below the last committed row and moves down as rows are + committed, until it reaches the bottom of the terminal. +- Shrinking the footer keeps its **top** row; growing it while at the bottom moves the top up. +- A resize requested during a render, or while commits are queued, is deferred. +- After a block's final commit the scrollback cursor must be on a new line + (`trailingNewline`), or the footer sits one row higher. + +How the UI works with them: + +- **Welcome screen.** While the session is empty and idle (`isHome`) the footer is + `renderer.terminalHeight` tall. Any block, even an error, ends it. Use + `renderer.terminalHeight`, not `useTerminalDimensions()`, which reports the footer's own + size in split-footer mode. +- **Leaving it.** `prepareFooterForWrites` shrinks the full-height footer before anything + is written, and `attachScrollback` writes nothing until `footerSettled` reports the + resize applied. Writing earlier committed the first message with no room above the + footer, so it scrolled straight into history. +- **Bottom-pinned composer.** On a fresh screen the writer first commits + `terminalHeight - footerRows` blank rows (`leadingRows`), pushing the footer to the bottom. + New rows then land just above the composer and older ones scroll up, a chat layout. The + cost is one screen of blank lines in history before the first message. +- **Stable height.** `footerModel()` always reserves the streaming-tail row and the + working/hints row (`RESERVED_ROWS`), so a turn finishing never shrinks the footer. + Otherwise the footer is the approval card (`toolApprovalHeight`), up to three running + tools plus a "more" row, up to two other live blocks, the composer (3), and the status + line (1). After a temporary growth (approval card, tools) the shrink can leave a gap under + the status line until the next committed rows push the footer back down. +- **Ordering.** Only the welcome transition is sized before writing; all other sizing + (`applyFooterHeight`) runs right after `writer.sync`, in the same synchronous step, and on + terminal resize. Sizing from the previous sync's pending blocks over-counts and made the + footer grow then shrink, ending one row off the bottom. + +Every footer row is fixed-height (`height={1}`, `wrapMode="none"`, `flexShrink={0}`) so the +computed height matches the layout. The streaming tail shows the end of the last logical +line, truncated from the left; it always contains the row still being held back. + +## Verification + +- `src/tests/scrollback-writer.test.ts`: ordering, single commit, streaming row hold-back, + live blocks holding later ones, trimmed arrays, dropped streaming blocks, fresh-screen + padding. +- `src/tests/footer-layout.test.ts`, `src/tests/footer-sizer.test.ts`: footer row math, + reserved rows, the welcome transition, settled detection, the streaming tail. +- `src/tests/terminal-background.test.ts`: OSC 11/111 and color validation. +- `src/tests/app.test.tsx`: end to end through the test renderer's captured scrollback. +- **Real terminal check.** The test renderer does not model split-footer scrolling, so + layout changes must be checked in a real emulator: run the built CLI inside a detached + `tmux` session (separate socket) with `CREWCODER_BIN` pointing at a fake agent that + streams JSON events, send keys, and `tmux capture-pane -p -S -`. The transcript must be + in history exactly once and in order, the status line must be the bottom row after a + turn, and `ESC[?1049h` must never appear. + +## Not yet done + +Markdown and syntax highlighting in scrollback (OpenTUI's `MarkdownRenderable` streams by +committed block and needs a tree-sitter client), assistant throughput metadata, images, and +terminal resize reflow of rows already written (they stay as the terminal wrapped them, +like any other scrollback). diff --git a/crewcoder-opentui/docs/TERMCN.md b/crewcoder-opentui/docs/TERMCN.md new file mode 100644 index 0000000..514aa01 --- /dev/null +++ b/crewcoder-opentui/docs/TERMCN.md @@ -0,0 +1,58 @@ +# termcn components + +Footer components come from [termcn](https://www.termcn.dev) (MIT, +[shadcn-labs/termcn](https://github.com/shadcn-labs/termcn)), a shadcn-style registry with +`@opentui/react` variants. As with shadcn, the source is **copied into this package and owned +here**; there is no runtime termcn dependency. Attribution is in +[`THIRD_PARTY_NOTICES.md`](../THIRD_PARTY_NOTICES.md). + +## What is vendored + +| File | Registry item | Changes | +|---|---|---| +| `src/components/ui/types.ts` | `opentui/types` | none | +| `src/hooks/use-theme.ts` | `opentui/use-theme` | none | +| `src/hooks/use-motion.ts` | `opentui/use-motion` | none | +| `src/providers/theme-provider.tsx` | `opentui/theme-provider` | none | +| `src/lib/terminal-themes/default.ts` | `opentui/theme-default` | none | +| `src/components/ui/spinner.tsx` | `opentui/spinner` | none | +| `src/hooks/use-animation.ts` | `ink/use-animation` | Ink import and screen-reader check removed (see below) | +| `src/components/ui/tool-call.tsx` | `opentui/tool-call` | see file header | +| `src/components/ui/tool-approval.tsx` | `opentui/tool-approval` | see file header | + +Upstream commit: `5a02dae79542add57ba392d2b51785138d0c3b6e`. The Gotham theme +(`src/theme.ts`) is CrewCoder's own, expressed as termcn `Theme` tokens. + +## Upstream problems found and fixed in our copies + +- **`tool-approval` approved on a bare `y`.** It registered a global `useKeyboard` for + `y`/`n`/`a`, so typing a prompt containing "y" while an approval was pending would approve + the tool call. Our copy has no key handling; `App` routes the configured `approve`/`deny` + chords (`DEFAULT_APP_KEYBINDINGS`) and passes their labels as hints. It also had an + auto-deny timer (removed) and defaulted unknown risk to LOW (removed). +- **`tool-call` and `thinking-block` toggle on every Enter/Space** through global + `useKeyboard`, which fires while typing in the composer. Our `tool-call` takes a controlled + `collapsed` prop; `thinking-block` is not used. +- **Inline rows collapse in OpenTUI.** Upstream rows are `` with no + `flexDirection`. Ink defaults to row; OpenTUI (Yoga) defaults to column, so side-by-side + text stacked and vanished inside one-row boxes. Our copies set `flexDirection="row"`. +- **`opentui/spinner` depends on `ink/use-animation`**, which imports `ink`. Our + `use-animation` is the same hook without the Ink import. +- `text-input` was evaluated and **not** adopted: it hand-parses keys (no paste, single + characters only) through a global `useKeyboard`. The composer uses OpenTUI's native + ``. + +## Adding another component + +`npx shadcn add @termcn/opentui/` writes `@/…` alias imports, which do not resolve in +this package's tsc/NodeNext build (no bundler). Copy components by hand instead: + +1. Fetch `https://www.termcn.dev/r/opentui/.json` and its `registryDependencies`. +2. Write each file to its `target` path under `src/`, rewriting `@/x` imports to relative + `.js` specifiers. +3. Review it before use: remove global `useKeyboard` handlers and hardcoded key names (route + keys through `DEFAULT_APP_KEYBINDINGS`), set `flexDirection="row"` on inline rows, replace + hardcoded colors with theme tokens, and check for timers that run when idle. +4. Record the changes in the file header and in the table above, and add tests that render + it through `@opentui/react/test-utils`. +5. Add any new npm dependency with an exact version. diff --git a/crewcoder-opentui/package.json b/crewcoder-opentui/package.json new file mode 100644 index 0000000..46619a8 --- /dev/null +++ b/crewcoder-opentui/package.json @@ -0,0 +1,53 @@ +{ + "name": "@onpoint-dev-tools/crewcoder-opentui", + "version": "0.1.0", + "private": false, + "description": "CrewCoder terminal UI built on OpenTUI and React, connected to crewcoder-agent through the shared crewcoder-tui-core bridge.", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/OnPoint-Dev-Tools/crewcoder.git", + "directory": "crewcoder-opentui" + }, + "bugs": "https://github.com/OnPoint-Dev-Tools/crewcoder/issues", + "homepage": "https://github.com/OnPoint-Dev-Tools/crewcoder#readme", + "type": "module", + "files": [ + "dist", + "LICENSE", + "README.md", + "THIRD_PARTY_NOTICES.md" + ], + "engines": { + "node": ">=26.4.0" + }, + "publishConfig": { + "access": "public", + "provenance": true + }, + "bin": { + "crewcoder-opentui": "./dist/cli.js" + }, + "scripts": { + "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"", + "predev": "npm run build -w @onpoint-dev-tools/crewcoder-tui-core", + "dev": "tsx src/cli.tsx", + "prebuild": "npm run build -w @onpoint-dev-tools/crewcoder-tui-core", + "build": "tsc -p tsconfig.build.json", + "pretypecheck": "npm run build -w @onpoint-dev-tools/crewcoder-tui-core", + "typecheck": "tsc -p tsconfig.json --noEmit", + "pretest": "npm run build -w @onpoint-dev-tools/crewcoder-tui-core", + "test": "vitest run", + "start": "node dist/cli.js" + }, + "dependencies": { + "@onpoint-dev-tools/crewcoder-tui-core": "0.1.0", + "@opentui/core": "0.9.2", + "@opentui/react": "0.9.2", + "cli-spinners": "3.4.0", + "react": "^19.3.1" + }, + "devDependencies": { + "@types/react": "^19.3.0" + } +} diff --git a/crewcoder-opentui/src/App.tsx b/crewcoder-opentui/src/App.tsx new file mode 100644 index 0000000..5cc49c3 --- /dev/null +++ b/crewcoder-opentui/src/App.tsx @@ -0,0 +1,155 @@ +import os from "node:os"; +import type { InputRenderable } from "@opentui/core"; +import { useKeyboard, useRenderer, useTerminalDimensions } from "@opentui/react"; +import { useRef, useSyncExternalStore, type ReactNode } from "react"; +import { Spinner } from "./components/ui/spinner.js"; +import { ToolApproval, type RiskLevel } from "./components/ui/tool-approval.js"; +import { ToolCall } from "./components/ui/tool-call.js"; +import { Home } from "./components/Home.js"; +import { footerModel, isHome, shortenPath, streamingTail } from "./footer-layout.js"; +import { useTheme } from "./hooks/use-theme.js"; +import { actionLabel, matchesAction, type KeyLike } from "./keybindings.js"; +import type { ScrollbackWriter } from "./scrollback-writer.js"; +import type { SessionController } from "./session-controller.js"; +import { toneColor } from "./theme.js"; +import { blockToRow } from "./transcript.js"; + +export type AppProps = { + controller: SessionController; + scrollback: Pick; + onQuit: () => void; +}; + +/** + * The split footer. Settled transcript lives in native scrollback (see + * ScrollbackWriter); this renders only what is still changing, plus the + * composer and status line. The footer height is set outside React by + * applyFooterHeight, in step with scrollback commits. + */ +export function App({ controller, scrollback, onQuit }: AppProps): ReactNode { + useSyncExternalStore(controller.subscribe, controller.getVersion); + const renderer = useRenderer(); + // In split-footer mode these are the footer's own dimensions; the hook also + // re-renders on resize, so renderer.terminalHeight below stays current. + const { width } = useTerminalDimensions(); + const theme = useTheme(); + const inputRef = useRef(null); + const state = controller.state; + const model = footerModel(scrollback.pending, state.running); + const home = isHome(state.blocks, state.running); + + useKeyboard((key: KeyLike) => { + if (matchesAction(key, "quit")) onQuit(); + else if (model.approval && matchesAction(key, "approve")) controller.resolvePendingApproval(true); + else if (model.approval && matchesAction(key, "deny")) controller.resolvePendingApproval(false); + else if (matchesAction(key, "abort")) controller.abort(); + }); + + const submit = (value: string): void => { + controller.submit(value); + // The input is uncontrolled; clear the native buffer after each submission. + if (inputRef.current) inputRef.current.value = ""; + }; + + const status = [ + state.provider, + state.model, + state.mode, + state.sessionId === "new" ? "new session" : state.sessionId + ].join(" · "); + + const composer = ( + + + + ); + + if (home) { + return ( + + + + ); + } + + return ( + + {/* Takes the free space so the live region and composer sit at the bottom. */} + + {model.other.map((block, index) => { + const row = blockToRow(block); + return ( + + {`${row.label} · ${firstLine(row.text)}`} + + ); + })} + {model.tools.map((tool, index) => ( + + + + ))} + {model.hiddenTools > 0 ? ( + {`… ${model.hiddenTools} more running`} + ) : null} + {/* Reserved row (RESERVED_ROWS): the streaming tail, or empty. */} + + {model.streaming ? streamingTail(blockToRow(model.streaming).text, width) : ""} + + {model.approval ? ( + + ) : null} + {/* Reserved row (RESERVED_ROWS): the working spinner, or key hints when idle. */} + {model.working ? ( + + + + ) : ( + + {`${actionLabel("abort")} abort · ${actionLabel("approve")} approve · ${actionLabel("deny")} deny · ${actionLabel("quit")} quit`} + + )} + {composer} + {status} + + ); +} + +/** Map the agent's ApprovalRisk (`safe | review | dangerous`) onto termcn's levels. */ +const RISK_LEVELS: Readonly> = { safe: "low", review: "medium", dangerous: "high" }; + +export function riskLevel(value: string | undefined): RiskLevel | undefined { + // hasOwn guards against prototype keys such as "constructor" in agent data. + return value !== undefined && Object.hasOwn(RISK_LEVELS, value) ? RISK_LEVELS[value] : undefined; +} + +/** `provider · model · cwd`, with the cwd shortened so the line fits and stays centered. */ +function homeInfo(provider: string, model: string, cwd: string, remoteTarget: string | undefined, width: number): string { + const prefix = `${provider} · ${model} · `; + const location = remoteTarget ? `${remoteTarget}:${cwd}` : cwd; + const room = Math.max(8, width - 2 - prefix.length); + return `${prefix}${shortenPath(location, room, remoteTarget ? undefined : os.homedir())}`; +} + +function firstLine(text: string): string { + return text.split("\n", 1)[0] ?? ""; +} diff --git a/crewcoder-opentui/src/args.ts b/crewcoder-opentui/src/args.ts new file mode 100644 index 0000000..b16735a --- /dev/null +++ b/crewcoder-opentui/src/args.ts @@ -0,0 +1,43 @@ +export type ParsedArgs = { remote?: string; remoteCwd?: string; remoteBin?: string; help: boolean }; + +export const USAGE = `CrewCoder OpenTUI (preview) + +Usage: + crewcoder-opentui + crewcoder-opentui --remote --remote-cwd [--remote-bin ] + +Remote agent: + --remote user@vps Run the CrewCoder backend through SSH + --remote-cwd /workspace Remote project directory (defaults to ~) + --remote-bin Remote CrewCoder binary (defaults to ~/crewcoder-runner/crewcoder) + +Requires Node.js >=26.4. The legacy UI remains available as crewcoder-tui +(npm i -g @onpoint-dev-tools/crewcoder-tui). +`; + +const VALUE_FLAGS = { + "--remote": "remote", + "--remote-cwd": "remoteCwd", + "--remote-bin": "remoteBin" +} as const satisfies Record; + +export function parseArgs(values: readonly string[]): ParsedArgs { + const result: ParsedArgs = { help: false }; + for (let index = 0; index < values.length; index++) { + const value = values[index] ?? ""; + if (value === "--help" || value === "-h") { + result.help = true; + continue; + } + const [flag, inline] = value.includes("=") ? [value.slice(0, value.indexOf("=")), value.slice(value.indexOf("=") + 1)] : [value, undefined]; + if (!isValueFlag(flag)) throw new Error(`Unknown argument: ${value}`); + const next = inline ?? values[++index]; + if (!next) throw new Error(`${flag} requires a value`); + result[VALUE_FLAGS[flag]] = next; + } + return result; +} + +function isValueFlag(flag: string): flag is keyof typeof VALUE_FLAGS { + return Object.hasOwn(VALUE_FLAGS, flag); +} diff --git a/crewcoder-opentui/src/cli.tsx b/crewcoder-opentui/src/cli.tsx new file mode 100644 index 0000000..ca5f727 --- /dev/null +++ b/crewcoder-opentui/src/cli.tsx @@ -0,0 +1,66 @@ +#!/usr/bin/env node +import { CrewCoderProcessBridge } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/crewcoder-process"; +import { createCliRenderer } from "@opentui/core"; +import { createRoot } from "@opentui/react"; +import { App } from "./App.js"; +import { parseArgs, USAGE } from "./args.js"; +import { footerModel } from "./footer-layout.js"; +import { applyFooterHeight, footerSettled, prepareFooterForWrites } from "./footer-sizer.js"; +import { ThemeProvider } from "./providers/theme-provider.js"; +import { attachScrollback, ScrollbackWriter } from "./scrollback-writer.js"; +import { SessionController } from "./session-controller.js"; +import { applyTerminalBackground } from "./terminal-background.js"; +import { gothamTheme } from "./theme.js"; + +async function main(): Promise { + const parsed = parseArgs(process.argv.slice(2)); + if (parsed.help) { + process.stdout.write(USAGE); + return; + } + // Remote mode is resolved by the shared bridge from these variables. + if (parsed.remote) process.env.CREWCODER_REMOTE = parsed.remote; + if (parsed.remoteCwd) process.env.CREWCODER_REMOTE_CWD = parsed.remoteCwd; + if (parsed.remoteBin) process.env.CREWCODER_REMOTE_BIN = parsed.remoteBin; + + const controller = new SessionController(new CrewCoderProcessBridge()); + // Before the renderer starts capturing stdout; restored on every exit path. + const resetBackground = applyTerminalBackground(process.stdout, gothamTheme.colors.background); + process.once("exit", resetBackground); + // Split footer: settled transcript goes to the terminal's native scrollback, + // and only the live region, composer, and status stay in the footer. + const renderer = await createCliRenderer({ + exitOnCtrlC: false, + screenMode: "split-footer", + externalOutputMode: "capture-stdout", + backgroundColor: gothamTheme.colors.background, + // Open at full height: a fresh session starts on the welcome screen. + footerHeight: Math.max(footerModel([], false).rows, process.stdout.rows || 0), + onDestroy: () => controller.dispose() + }); + // Pad a fresh screen so the conversation footer starts at the bottom (see ScrollbackWriter). + const scrollback = new ScrollbackWriter(renderer, gothamTheme, () => renderer.terminalHeight - footerModel([], true).rows); + const sizeFooter = (): void => applyFooterHeight(renderer, controller.state, scrollback); + attachScrollback(controller, scrollback, { + prepare: () => prepareFooterForWrites(renderer, controller.state), + size: sizeFooter, + settled: () => footerSettled(renderer) + }); + renderer.on("resize", sizeFooter); + const quit = (): void => { + scrollback.dispose(); + renderer.destroy(); + resetBackground(); + process.exit(0); + }; + createRoot(renderer).render( + + + + ); +} + +main().catch((error: unknown) => { + process.stderr.write(`crewcoder-opentui: ${error instanceof Error ? error.message : String(error)}\n`); + process.exit(1); +}); diff --git a/crewcoder-opentui/src/components/Home.tsx b/crewcoder-opentui/src/components/Home.tsx new file mode 100644 index 0000000..048e2d1 --- /dev/null +++ b/crewcoder-opentui/src/components/Home.tsx @@ -0,0 +1,52 @@ +import { bigCrewCodeLogoLines } from "@onpoint-dev-tools/crewcoder-tui-core/theme/logo"; +import type { ReactNode } from "react"; +import { homeComposerWidth, homeLogo } from "../footer-layout.js"; +import { useTheme } from "../hooks/use-theme.js"; + +export type HomeProps = { + width: number; + height: number; + /** Muted identity line under the tip, e.g. `provider · model · cwd`. */ + info: string; + /** Right-aligned key hint under the composer, e.g. `^C quit`. */ + hint: string; + /** The composer, rendered centered at the home width. */ + composer: ReactNode; +}; + +/** + * The fresh-session welcome screen: the CrewCoder logo centered in a footer + * that fills the terminal, with the composer beneath it, mirroring the legacy + * landing page. It disappears as soon as the session has any block. On windows + * too small for the wordmark only the composer is shown. + */ +export function Home({ width, height, info, hint, composer }: HomeProps): ReactNode { + const theme = useTheme(); + const logo = homeLogo(width, height, bigCrewCodeLogoLines); + const composerWidth = homeComposerWidth(width); + + return ( + + {logo ? ( + <> + {logo.map((line, index) => ( + + {line} + + ))} + + + ) : null} + + {composer} + {hint} + + + + Tip + Type your first request below and press Enter + + {info} + + ); +} diff --git a/crewcoder-opentui/src/components/ui/spinner.tsx b/crewcoder-opentui/src/components/ui/spinner.tsx new file mode 100644 index 0000000..f719019 --- /dev/null +++ b/crewcoder-opentui/src/components/ui/spinner.tsx @@ -0,0 +1,46 @@ +/* @jsxImportSource @opentui/react */ +import cliSpinners from "cli-spinners"; +import type { SpinnerName } from "cli-spinners"; + +import { useAnimation } from "../../hooks/use-animation.js"; +import { useTheme } from "../../hooks/use-theme.js"; + +type OpenTUIBoxProps = Record; + +export type SpinnerType = SpinnerName; + +export const spinnerNames = Object.keys(cliSpinners) as SpinnerName[]; + +export interface SpinnerProps extends OpenTUIBoxProps { + type?: SpinnerType; + label?: string; + color?: string; + fps?: number; + frames?: string[]; +} + +export const Spinner = ({ + type = "dots", + label, + color, + fps = 12, + frames: customFrames, + ...props +}: SpinnerProps) => { + const theme = useTheme(); + const builtin = cliSpinners[type] ?? cliSpinners.dots; + const useCustomFrames = customFrames !== undefined; + const frames = useCustomFrames ? customFrames : builtin.frames; + const frame = useAnimation( + useCustomFrames ? fps : { intervalMs: builtin.interval } + ); + const icon = frames[frame % frames.length]; + const resolvedColor = color ?? theme.colors.primary; + + return ( + + {icon} + {label ? {label} : null} + + ); +}; diff --git a/crewcoder-opentui/src/components/ui/tool-approval.tsx b/crewcoder-opentui/src/components/ui/tool-approval.tsx new file mode 100644 index 0000000..2d1da45 --- /dev/null +++ b/crewcoder-opentui/src/components/ui/tool-approval.tsx @@ -0,0 +1,116 @@ +/* @jsxImportSource @opentui/react */ +// Vendored from termcn (opentui/tool-approval). CrewCoder changes: +// - Inline rows set flexDirection="row": OpenTUI (Yoga) defaults to column, +// unlike Ink, so upstream rows stacked and collapsed inside height-1 boxes. +// - No global useKeyboard. Upstream approved on any bare `y` keypress, which +// would approve a tool call while the user typed a prompt. The caller routes +// configured key chords and passes their labels as hints. +// - No auto-deny timer; approvals wait for an explicit decision. +// - `risk` has no default: an unknown risk shows no badge instead of claiming +// LOW RISK. +// - One-line, non-wrapping rows with a bounded argument list, so the height is +// deterministic (see toolApprovalHeight) for split-footer sizing. +import { useTheme } from "../../hooks/use-theme.js"; + +export type RiskLevel = "low" | "medium" | "high"; + +export interface ToolApprovalProps { + name: string; + description?: string; + args?: Record; + risk?: RiskLevel; + approveHint: string; + denyHint: string; + maxArgs?: number; +} + +const DEFAULT_MAX_ARGS = 3; + +/** Rows the card occupies, including its border. Must match the layout below. */ +export const toolApprovalHeight = ({ description, args, maxArgs = DEFAULT_MAX_ARGS }: Pick): number => { + const argCount = args ? Object.keys(args).length : 0; + const argRows = argCount === 0 ? 0 : 1 + Math.min(argCount, maxArgs) + (argCount > maxArgs ? 1 : 0); + return 2 + 1 + 1 + (description ? 1 : 0) + argRows + 1; +}; + +export const ToolApproval = ({ + name, + description, + args, + risk, + approveHint, + denyHint, + maxArgs = DEFAULT_MAX_ARGS, +}: ToolApprovalProps) => { + const theme = useTheme(); + const muted = theme.colors.mutedForeground; + const riskColor: Record = { + high: theme.colors.error, + low: theme.colors.success, + medium: theme.colors.warning, + }; + const entries = args ? Object.entries(args) : []; + const shown = entries.slice(0, maxArgs); + + return ( + + + + Tool Approval Required + + {risk ? ( + + {`[${risk.toUpperCase()} RISK]`} + + ) : null} + + + + Tool: + + {name} + + + {description ? ( + {description} + ) : null} + + {entries.length > 0 ? ( + + Arguments: + {shown.map(([k, v]) => ( + + {`${k}:`} + {oneLine(v)} + + ))} + {entries.length > maxArgs ? ( + {`… ${entries.length - maxArgs} more`} + ) : null} + + ) : null} + + + + {`[${approveHint}] Approve`} + + + {`[${denyHint}] Deny`} + + + + ); +}; + +const oneLine = (value: unknown): string => { + const text = typeof value === "string" ? value : JSON.stringify(value) ?? String(value); + return text.replace(/\s+/g, " "); +}; diff --git a/crewcoder-opentui/src/components/ui/tool-call.tsx b/crewcoder-opentui/src/components/ui/tool-call.tsx new file mode 100644 index 0000000..dd22882 --- /dev/null +++ b/crewcoder-opentui/src/components/ui/tool-call.tsx @@ -0,0 +1,128 @@ +/* @jsxImportSource @opentui/react */ +// Vendored from termcn (opentui/tool-call). CrewCoder changes: +// - Inline rows set flexDirection="row": OpenTUI (Yoga) defaults to column, +// unlike Ink, so upstream rows stacked instead of sitting side by side. +// - No global useKeyboard (it toggled every instance on Enter/Space, including +// while typing in the composer); `collapsed` is controlled by the caller. +// - The spinner and elapsed timer only run while the tool is running. +// - Theme tokens replace hardcoded #666. +import { useEffect, useState } from "react"; + +import { useTheme } from "../../hooks/use-theme.js"; + +export type ToolCallStatus = "pending" | "running" | "success" | "error"; + +export interface ToolCallProps { + name: string; + args?: Record; + status: ToolCallStatus; + result?: unknown; + duration?: number; + collapsible?: boolean; + collapsed?: boolean; +} + +const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]; + +export const ToolCall = ({ + name, + args, + status, + result, + duration, + collapsible = true, + collapsed = true, +}: ToolCallProps) => { + const theme = useTheme(); + const [elapsed, setElapsed] = useState(0); + const [frame, setFrame] = useState(0); + const muted = theme.colors.mutedForeground; + + useEffect(() => { + if (status !== "running") { + return; + } + const startedAt = Date.now(); + const id = setInterval(() => { + setFrame((f) => f + 1); + setElapsed(Date.now() - startedAt); + }, Math.round(1000 / 12)); + return () => clearInterval(id); + }, [status]); + + const statusIcon = () => { + switch (status) { + case "pending": { + return ○; + } + case "running": { + return {SPINNER_FRAMES[frame % SPINNER_FRAMES.length] ?? "⠋"}; + } + case "success": { + return ✓; + } + case "error": { + return ✗; + } + } + }; + + let durationText: string | null; + if (duration === undefined) { + durationText = status === "running" ? `${elapsed}ms` : null; + } else { + durationText = `${duration}ms`; + } + + let nameColor: string; + if (status === "error") { + nameColor = theme.colors.error; + } else if (status === "success") { + nameColor = theme.colors.success; + } else if (status === "running") { + nameColor = theme.colors.primary; + } else { + nameColor = muted; + } + + return ( + + + {statusIcon()} + + {status !== "pending" ? {name} : name} + + {durationText && ( + {`(${durationText})`} + )} + {collapsible && {collapsed ? "▶" : "▼"}} + + + {!collapsed && ( + + {args && Object.keys(args).length > 0 && ( + + Args: + {Object.entries(args).map(([k, v]) => ( + + {`${k}:`} + {JSON.stringify(v)} + + ))} + + )} + {result !== undefined && ( + + Result: + + {typeof result === "string" + ? result + : JSON.stringify(result, null, 2)} + + + )} + + )} + + ); +}; diff --git a/crewcoder-opentui/src/components/ui/types.ts b/crewcoder-opentui/src/components/ui/types.ts new file mode 100644 index 0000000..b18ddff --- /dev/null +++ b/crewcoder-opentui/src/components/ui/types.ts @@ -0,0 +1,94 @@ +import type { ReactNode } from "react"; + +export type BorderStyle = "single" | "double" | "rounded" | "heavy"; + +export interface ColorTokens { + primary: string; + primaryForeground: string; + secondary: string; + secondaryForeground: string; + accent: string; + accentForeground: string; + success: string; + successForeground: string; + warning: string; + warningForeground: string; + error: string; + errorForeground: string; + info: string; + infoForeground: string; + background: string; + foreground: string; + muted: string; + mutedForeground: string; + border: string; + focusRing: string; + selection: string; + selectionForeground: string; +} + +export interface SpacingTokens { + 0: number; + 1: number; + 2: number; + 3: number; + 4: number; + 6: number; + 8: number; +} + +export interface TypographyTokens { + bold: boolean; + sm: string; + base: string; + lg: string; + xl: string; +} + +export interface BorderTokens { + style: BorderStyle; + color: string; + focusColor: string; +} + +export interface Theme { + name: string; + colors: ColorTokens; + spacing: SpacingTokens; + typography: TypographyTokens; + border: BorderTokens; +} + +export interface MotionContextValue { + reduced: boolean; +} + +export interface UnicodeContextValue { + unicode: boolean; +} + +export interface ThemeContextValue { + setTheme: (theme: Theme) => void; + theme: Theme; +} + +export interface ThemeProviderProps { + children: ReactNode; + theme?: Theme; +} + +export interface MotionProviderProps { + children: ReactNode; + reducedMotion?: boolean; +} + +export interface UnicodeProviderProps { + children: ReactNode; + unicode?: boolean; +} + +export interface AutoThemeProviderProps { + children: ReactNode; + darkTheme: Theme; + lightTheme: Theme; +} diff --git a/crewcoder-opentui/src/footer-layout.ts b/crewcoder-opentui/src/footer-layout.ts new file mode 100644 index 0000000..245022f --- /dev/null +++ b/crewcoder-opentui/src/footer-layout.ts @@ -0,0 +1,106 @@ +import type { TuiEventBlock } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; +import { toolApprovalHeight } from "./components/ui/tool-approval.js"; + +type ApprovalBlock = Extract; +type ToolBlock = Extract; +type StreamingBlock = Extract; + +export const MAX_FOOTER_TOOLS = 3; +export const MAX_FOOTER_OTHER = 2; +export const COMPOSER_ROWS = 3; +export const STATUS_ROWS = 1; +/** + * Rows every conversation footer keeps: the streaming-tail row and the + * working/hints row. Reserving them keeps the footer the same height whether a + * turn is running or idle, because OpenTUI shrinks a split footer by keeping + * its top row, which would leave blank rows under the status line. + */ +export const RESERVED_ROWS = 2; + +/** What the split footer shows for the blocks not yet in scrollback. */ +export type FooterModel = { + approval?: ApprovalBlock; + tools: ToolBlock[]; + hiddenTools: number; + streaming?: StreamingBlock; + other: TuiEventBlock[]; + working: boolean; + rows: number; +}; + +export function footerModel(pending: readonly TuiEventBlock[], running: boolean): FooterModel { + const approval = pending.find((block): block is ApprovalBlock => block.type === "approval" && block.status === "pending"); + const runningTools = pending.filter((block): block is ToolBlock => block.type === "tool" && block.status === "running"); + const tools = runningTools.slice(0, MAX_FOOTER_TOOLS); + const hiddenTools = runningTools.length - tools.length; + const last = pending.at(-1); + const streaming = running && (last?.type === "assistant" || last?.type === "thinking") ? last : undefined; + const other = pending + .filter((block) => block !== approval && block !== streaming && !runningTools.includes(block as ToolBlock)) + .slice(0, MAX_FOOTER_OTHER); + const rows = + (approval ? toolApprovalHeight({ description: approval.text, args: approval.args }) : 0) + + tools.length + (hiddenTools > 0 ? 1 : 0) + + other.length + + RESERVED_ROWS + + COMPOSER_ROWS + + STATUS_ROWS; + return { approval, tools, hiddenTools, streaming, other, working: running, rows }; +} + +/** + * The centered welcome screen shows while the session is empty and idle; the + * footer then fills the terminal. Any block (even an error from an unported + * command) ends it, so nothing written to scrollback is hidden behind it. + */ +export function isHome(blocks: readonly TuiEventBlock[], running: boolean): boolean { + return !running && blocks.length === 0; +} + +/** + * Footer height: the welcome screen fills the terminal; in a conversation the + * footer is just its content (live region, composer, status), pinned to the + * bottom by the writer's leading padding. + */ +export function footerHeight(options: { home: boolean; contentRows: number; terminalHeight: number }): number { + return options.home ? Math.max(options.contentRows, options.terminalHeight) : options.contentRows; +} + +export const HOME_COMPOSER_MIN_WIDTH = 24; + +/** Composer width on the home screen: 62% of the terminal, like the legacy landing page. */ +export function homeComposerWidth(width: number): number { + // Clamp last so a terminal narrower than the floor never gets a wider composer. + return Math.min(width, Math.max(HOME_COMPOSER_MIN_WIDTH, Math.floor(width * 0.62))); +} + +/** Rows the welcome screen needs below the logo: gap, composer (3), hint, gap, tip, info. */ +export const HOME_BODY_ROWS = 8; + +/** + * The big block wordmark, or nothing. Smaller logo variants are not used: when + * the wordmark does not fit (narrower than 70 columns, or too short to keep the + * composer whole), the welcome screen shows only the composer. + */ +export function homeLogo(width: number, height: number, logo: readonly string[]): readonly string[] | undefined { + const logoWidth = Math.max(0, ...logo.map((line) => line.length)); + const fits = width >= Math.max(70, logoWidth + 2) && height >= logo.length + HOME_BODY_ROWS + 2; + return fits ? logo : undefined; +} + +/** + * Fit a path into `max` columns: abbreviate the local home directory as `~` + * (pass no home for remote paths), then keep the end, which names the project. + */ +export function shortenPath(path: string, max: number, home?: string): string { + const local = home && (path === home || path.startsWith(`${home}/`)) ? `~${path.slice(home.length)}` : path; + if (local.length <= max) return local; + return max <= 1 ? "…" : `…${local.slice(local.length - max + 1)}`; +} + +/** The end of the last logical line, which always contains the not-yet-committed row. */ +export function streamingTail(text: string, width: number): string { + const tail = text.slice(text.lastIndexOf("\n") + 1); + const room = Math.max(1, width - 1); + return tail.length > room ? `…${tail.slice(tail.length - room + 1)}` : tail; +} diff --git a/crewcoder-opentui/src/footer-sizer.ts b/crewcoder-opentui/src/footer-sizer.ts new file mode 100644 index 0000000..5c87ec6 --- /dev/null +++ b/crewcoder-opentui/src/footer-sizer.ts @@ -0,0 +1,39 @@ +import type { TuiEventBlock } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; +import { footerHeight, footerModel, isHome } from "./footer-layout.js"; + +export type FooterHost = { footerHeight: number; readonly terminalHeight: number; readonly height: number }; + +type FooterState = { readonly blocks: readonly TuiEventBlock[]; readonly running: boolean }; +type FooterScrollback = { readonly pending: readonly TuiEventBlock[] }; + +/** Set the split-footer height for the current state; see attachScrollback for ordering. */ +export function applyFooterHeight(host: FooterHost, state: FooterState, scrollback: FooterScrollback): void { + const rows = footerHeight({ + home: isHome(state.blocks, state.running), + contentRows: footerModel(scrollback.pending, state.running).rows, + terminalHeight: host.terminalHeight + }); + if (host.footerHeight !== rows) host.footerHeight = rows; +} + +/** + * Before writing: if the session just left the welcome screen, shrink the + * full-height footer to the conversation footer first. Only this transition is + * handled here; other sizing waits until after the write, because sizing from + * the previous sync's pending blocks over-counts (a just-finished reply would + * briefly grow the footer, and a footer that grows then shrinks ends up one row + * off the bottom, since OpenTUI shrinks a split footer by keeping its top row). + */ +export function prepareFooterForWrites(host: FooterHost, state: FooterState): void { + if (isHome(state.blocks, state.running) || host.footerHeight < host.terminalHeight) return; + const rows = footerModel([], state.running).rows; + if (host.footerHeight !== rows) host.footerHeight = rows; +} + +/** + * Whether the renderer has applied the requested footer height. In split-footer + * mode `height` is the footer region, updated only when the resize is applied. + */ +export function footerSettled(host: FooterHost): boolean { + return host.height === Math.min(host.footerHeight, host.terminalHeight); +} diff --git a/crewcoder-opentui/src/hooks/use-animation.ts b/crewcoder-opentui/src/hooks/use-animation.ts new file mode 100644 index 0000000..47e0962 --- /dev/null +++ b/crewcoder-opentui/src/hooks/use-animation.ts @@ -0,0 +1,77 @@ +// Adapted from termcn's Ink `use-animation` (the OpenTUI spinner's registry entry +// points at the Ink hook). Ink's screen-reader check is removed; reduced motion +// from `use-motion` (NO_MOTION=1 or CI=true) still stops the animation. +import * as React from "react"; + +import { useMotion } from "./use-motion.js"; + +type Subscriber = (tick: number) => void; +const pool = new Map< + number, + { id: ReturnType; subs: Set; tick: number } +>(); + +const subscribe = (milliseconds: number, subscriber: Subscriber) => { + if (!pool.has(milliseconds)) { + const entry = { + id: null as unknown as ReturnType, + subs: new Set(), + tick: 0, + }; + + entry.id = setInterval(() => { + entry.tick += 1; + for (const sub of entry.subs) { + sub(entry.tick); + } + }, milliseconds); + + pool.set(milliseconds, entry); + } + + pool.get(milliseconds)?.subs.add(subscriber); +}; + +const unsubscribe = (milliseconds: number, subscriber: Subscriber) => { + const entry = pool.get(milliseconds); + if (!entry) { + return; + } + + entry.subs.delete(subscriber); + if (entry.subs.size === 0) { + clearInterval(entry.id); + pool.delete(milliseconds); + } +}; + +export interface UseAnimationOptions { + intervalMs: number; + isActive?: boolean; +} + +export const useAnimation = ( + rate: number | UseAnimationOptions = 12 +): number => { + const [frame, setFrame] = React.useState(0); + const { reduced } = useMotion(); + const milliseconds = + typeof rate === "number" ? Math.round(1000 / rate) : rate.intervalMs; + const isActive = + (typeof rate === "number" ? true : (rate.isActive ?? true)) && + !reduced; + + React.useEffect(() => { + if (!isActive) { + setFrame(0); + return; + } + + const callback: Subscriber = (tick) => setFrame(tick); + subscribe(milliseconds, callback); + + return () => unsubscribe(milliseconds, callback); + }, [isActive, milliseconds]); + + return frame; +}; diff --git a/crewcoder-opentui/src/hooks/use-motion.ts b/crewcoder-opentui/src/hooks/use-motion.ts new file mode 100644 index 0000000..c6678bc --- /dev/null +++ b/crewcoder-opentui/src/hooks/use-motion.ts @@ -0,0 +1,16 @@ +import * as React from "react"; + +import type { MotionContextValue } from "../components/ui/types.js"; + +const getEnv = (name: string): string | undefined => + typeof process !== "undefined" && process.env ? process.env[name] : undefined; + +export const isReducedMotion = (): boolean => + getEnv("NO_MOTION") === "1" || getEnv("CI") === "true"; + +export const MotionContext = React.createContext({ + reduced: isReducedMotion(), +}); + +export const useMotion = (): MotionContextValue => + React.useContext(MotionContext); diff --git a/crewcoder-opentui/src/hooks/use-theme.ts b/crewcoder-opentui/src/hooks/use-theme.ts new file mode 100644 index 0000000..04a439b --- /dev/null +++ b/crewcoder-opentui/src/hooks/use-theme.ts @@ -0,0 +1,19 @@ +import * as React from "react"; + +import { defaultTheme } from "../lib/terminal-themes/default.js"; +import type { + Theme, + ThemeContextValue, +} from "../components/ui/types.js"; + +export const ThemeContext = React.createContext({ + setTheme: () => { + // The default context keeps useTheme provider-optional. + }, + theme: defaultTheme, +}); + +export const useTheme = (): Theme => React.useContext(ThemeContext).theme; + +export const useThemeUpdater = (): ((theme: Theme) => void) => + React.useContext(ThemeContext).setTheme; diff --git a/crewcoder-opentui/src/keybindings.ts b/crewcoder-opentui/src/keybindings.ts new file mode 100644 index 0000000..09899a1 --- /dev/null +++ b/crewcoder-opentui/src/keybindings.ts @@ -0,0 +1,49 @@ +export type AppAction = "abort" | "quit" | "approve" | "deny"; + +export type KeyLike = { + name: string; + ctrl: boolean; + meta: boolean; + shift: boolean; +}; + +/** + * Default key chords per action. Keep key checks routed through this table so + * bindings stay configurable instead of being hardcoded at call sites. + */ +export const DEFAULT_APP_KEYBINDINGS: Readonly> = { + abort: ["escape"], + quit: ["ctrl+c"], + approve: ["ctrl+y"], + deny: ["ctrl+n"] +}; + +export function matchesAction( + key: KeyLike, + action: AppAction, + bindings: Readonly> = DEFAULT_APP_KEYBINDINGS +): boolean { + return bindings[action].some((chord) => matchesChord(key, chord)); +} + +/** Short human label for the first chord of an action, e.g. `^Y`. */ +export function actionLabel( + action: AppAction, + bindings: Readonly> = DEFAULT_APP_KEYBINDINGS +): string { + const parts = (bindings[action][0] ?? "").split("+"); + const key = parts.pop() ?? ""; + const prefix = parts.map((modifier) => MODIFIER_LABELS[modifier] ?? `${modifier}+`).join(""); + return `${prefix}${key.length === 1 ? key.toUpperCase() : key}`; +} + +const MODIFIER_LABELS: Readonly> = { ctrl: "^", meta: "M-", shift: "S-" }; + +function matchesChord(key: KeyLike, chord: string): boolean { + const parts = chord.toLowerCase().split("+"); + const name = parts.pop(); + return name === key.name.toLowerCase() + && parts.includes("ctrl") === key.ctrl + && parts.includes("meta") === key.meta + && parts.includes("shift") === key.shift; +} diff --git a/crewcoder-opentui/src/lib/terminal-themes/default.ts b/crewcoder-opentui/src/lib/terminal-themes/default.ts new file mode 100644 index 0000000..233326c --- /dev/null +++ b/crewcoder-opentui/src/lib/terminal-themes/default.ts @@ -0,0 +1,53 @@ +import type { Theme } from "../../components/ui/types.js"; + +export const defaultTheme: Theme = { + border: { + color: "#4B5563", + focusColor: "#8B5CF6", + style: "rounded", + }, + colors: { + accent: "#8B5CF6", + accentForeground: "#FFFFFF", + background: "#000000", + border: "#4B5563", + error: "#EF4444", + errorForeground: "#FFFFFF", + + focusRing: "#8B5CF6", + foreground: "#FFFFFF", + info: "#3B82F6", + infoForeground: "#FFFFFF", + muted: "#374151", + mutedForeground: "#9CA3AF", + primary: "#7C3AED", + primaryForeground: "#FFFFFF", + + secondary: "#6B7280", + secondaryForeground: "#FFFFFF", + selection: "#7C3AED", + selectionForeground: "#FFFFFF", + success: "#10B981", + + successForeground: "#FFFFFF", + warning: "#F59E0B", + warningForeground: "#000000", + }, + name: "default", + spacing: { + 0: 0, + 1: 1, + 2: 2, + 3: 3, + 4: 4, + 6: 6, + 8: 8, + }, + typography: { + base: "", + bold: true, + lg: "bold", + sm: "dim", + xl: "bold", + }, +}; diff --git a/crewcoder-opentui/src/providers/theme-provider.tsx b/crewcoder-opentui/src/providers/theme-provider.tsx new file mode 100644 index 0000000..59e61da --- /dev/null +++ b/crewcoder-opentui/src/providers/theme-provider.tsx @@ -0,0 +1,101 @@ +/* @jsxImportSource @opentui/react */ +import * as React from "react"; + +import { ThemeContext } from "../hooks/use-theme.js"; +import { defaultTheme } from "../lib/terminal-themes/default.js"; +import type { + AutoThemeProviderProps, + Theme, + ThemeProviderProps, +} from "../components/ui/types.js"; + +export type { + AutoThemeProviderProps, + BorderStyle, + BorderTokens, + ColorTokens, + SpacingTokens, + Theme, + ThemeProviderProps, + TypographyTokens, +} from "../components/ui/types.js"; + +const getEnv = (name: string): string | undefined => + typeof process !== "undefined" && process.env ? process.env[name] : undefined; + +export const detectColorScheme = (): "dark" | "light" => { + const colorFgBg = getEnv("COLORFGBG"); + if (colorFgBg) { + const parts = colorFgBg.split(";"); + const background = Number.parseInt(parts.at(-1) ?? "0", 10); + if (!Number.isNaN(background)) { + return background <= 6 ? "dark" : "light"; + } + } + + const termBackground = getEnv("TERM_BACKGROUND"); + if (termBackground === "light") { + return "light"; + } + if (termBackground === "dark") { + return "dark"; + } + + return "dark"; +}; + +export const ThemeProvider = ({ + children, + theme = defaultTheme, +}: ThemeProviderProps) => { + const [currentTheme, setCurrentTheme] = React.useState(theme); + + React.useEffect(() => { + setCurrentTheme(theme); + }, [theme]); + + const themeValue = React.useMemo( + () => ({ setTheme: setCurrentTheme, theme: currentTheme }), + [currentTheme] + ); + + return ( + {children} + ); +}; + +export const AutoThemeProvider = ({ + children, + darkTheme, + lightTheme, +}: AutoThemeProviderProps) => { + const scheme = detectColorScheme(); + return ( + + {children} + + ); +}; + +export const createTheme = ( + overrides: Partial & { name: string } +): Theme => ({ + ...defaultTheme, + ...overrides, + border: { + ...defaultTheme.border, + ...overrides.border, + }, + colors: { + ...defaultTheme.colors, + ...overrides.colors, + }, + spacing: { + ...defaultTheme.spacing, + ...overrides.spacing, + }, + typography: { + ...defaultTheme.typography, + ...overrides.typography, + }, +}); diff --git a/crewcoder-opentui/src/scrollback-writer.ts b/crewcoder-opentui/src/scrollback-writer.ts new file mode 100644 index 0000000..5484c72 --- /dev/null +++ b/crewcoder-opentui/src/scrollback-writer.ts @@ -0,0 +1,246 @@ +import { BoxRenderable, TextRenderable, bold, fg, t, type ScrollbackSurface } from "@opentui/core"; +import type { TuiEventBlock } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; +import type { Theme } from "./components/ui/types.js"; +import { bodyColor, toneColor } from "./theme.js"; +import { blockPhase, blockToRow } from "./transcript.js"; + +/** The renderer surface the writer needs; satisfied by a split-footer `CliRenderer`. */ +export type ScrollbackHost = { + createScrollbackSurface(options?: { startOnNewLine?: boolean }): ScrollbackSurface; +}; + +type ActiveBlock = { + block: TuiEventBlock; + surface: ScrollbackSurface; + body: TextRenderable; + text: string; + committedRows: number; +}; + +export type ScrollbackSource = { + readonly state: { readonly blocks: readonly TuiEventBlock[]; readonly running: boolean }; + subscribe(listener: () => void): () => void; +}; + +/** Keeps the split footer sized; see attachScrollback. */ +export type FooterControl = { + /** Before writing: only the welcome-screen to conversation transition (see prepareFooterForWrites). */ + prepare(): void; + /** After writing: set the footer height for the current state. */ + size(): void; + /** Whether the renderer has applied the requested height yet. */ + settled(): boolean; +}; + +const RETRY_MS = 16; + +/** + * Sync the writer on every state change. Attach before mounting the footer so + * `writer.pending` is current whenever React renders. + * + * Leaving the welcome screen, the footer is shrunk before writing, and nothing + * is written until the renderer has applied that size. OpenTUI defers a resize requested mid-render, and + * defers it again while commits are queued; a shrinking footer also keeps its + * top row. Writing before the resize applied made the first message (leaving + * the full-height welcome screen) commit with no room above the footer, so it + * scrolled straight into history and the composer floated mid-screen. The + * footer is sized again after writing to pick up the exact live content. + */ +export function attachScrollback(source: ScrollbackSource, writer: ScrollbackWriter, footer?: FooterControl): () => void { + let retry: ReturnType | undefined; + let stopped = false; + const sync = (): void => { + if (stopped) return; + if (retry !== undefined) clearTimeout(retry); + retry = undefined; + footer?.prepare(); + if (footer && !footer.settled()) { + retry = setTimeout(sync, RETRY_MS); + return; + } + writer.sync(source.state.blocks, source.state.running); + footer?.size(); + }; + sync(); + const unsubscribe = source.subscribe(sync); + return () => { + stopped = true; + if (retry !== undefined) clearTimeout(retry); + unsubscribe(); + }; +} + +/** Upper bound on cells per commit; OpenTUI rejects commits above ~349k cells. */ +const MAX_COMMIT_CELLS = 200_000; + +/** + * Writes settled transcript blocks into the terminal's native scrollback above + * the split footer, in order, exactly once. + * + * Blocks are tracked by identity rather than index because the reducer trims + * `state.blocks` to its last 500 entries. A streaming assistant/thinking block + * commits every finished row as text arrives and keeps only its last, still + * changing row back. The first `live` block (running tool, pending approval, + * ...) stops the writer so scrollback never goes out of order; it and every + * later block are returned as pending for the footer to show. + */ +export class ScrollbackWriter { + private readonly host: ScrollbackHost; + private readonly theme: Theme; + private readonly committed = new WeakSet(); + private active: ActiveBlock | undefined; + private wroteBlock = false; + private readonly leadingRows: () => number; + private pendingBlocks: readonly TuiEventBlock[] = []; + + /** + * `leadingRows` is the number of blank rows to write before the first block on + * a fresh screen. OpenTUI's inline split footer sits directly under the last + * committed row and only reaches the bottom of the terminal once rows push it + * there; padding the screen first pins the composer to the bottom from the + * first message, with the transcript growing upward above it (a chat layout). + */ + constructor(host: ScrollbackHost, theme: Theme, leadingRows: () => number = () => 0) { + this.host = host; + this.theme = theme; + this.leadingRows = leadingRows; + } + + /** Blocks not fully in scrollback yet, in transcript order. */ + get pending(): readonly TuiEventBlock[] { + return this.pendingBlocks; + } + + sync(blocks: readonly TuiEventBlock[], running: boolean): readonly TuiEventBlock[] { + if (this.active && !blocks.includes(this.active.block)) this.dropActive(); + if (blocks.length === 0) { + // An empty session shows the welcome screen; the next block starts a fresh screen. + this.wroteBlock = false; + } + const pending: TuiEventBlock[] = []; + let held = false; + blocks.forEach((block, index) => { + if (this.committed.has(block)) return; + if (held) { + pending.push(block); + return; + } + const phase = blockPhase(block, index === blocks.length - 1, running); + if (phase === "final") { + this.writeFinal(block); + return; + } + if (phase === "streaming") this.stream(block); + pending.push(block); + held = true; + }); + this.pendingBlocks = pending; + return pending; + } + + dispose(): void { + this.dropActive(); + } + + private writeFinal(block: TuiEventBlock): void { + const active = this.active?.block === block ? this.active : this.open(block); + this.active = undefined; + try { + this.update(active); + this.commitThrough(active, active.surface.height, true); + } finally { + active.surface.destroy(); + } + this.committed.add(block); + } + + private stream(block: TuiEventBlock): void { + if (!this.active) this.active = this.open(block); + const active = this.active; + this.update(active); + // The last row can still grow or rewrap as text arrives; hold it back. + this.commitThrough(active, active.surface.height - 1); + } + + private open(block: TuiEventBlock): ActiveBlock { + this.writeBlankRows(this.wroteBlock ? 1 : this.leadingRows()); + this.wroteBlock = true; + const row = blockToRow(block); + const surface = this.host.createScrollbackSurface({ startOnNewLine: true }); + try { + const column = new BoxRenderable(surface.renderContext, { flexDirection: "column", width: "100%" }); + column.add(new TextRenderable(surface.renderContext, { + content: t`${bold(fg(toneColor(this.theme, row.tone))(row.label))}`, + width: "100%", + wrapMode: "word" + })); + const body = new TextRenderable(surface.renderContext, { + content: "", + width: "100%", + wrapMode: "word", + fg: bodyColor(this.theme, row.tone) + }); + column.add(body); + if (row.detail) { + column.add(new TextRenderable(surface.renderContext, { + content: row.detail, + width: "100%", + wrapMode: "word", + fg: this.theme.colors.mutedForeground + })); + } + surface.root.add(column); + return { block, surface, body, text: "", committedRows: 0 }; + } catch (error) { + surface.destroy(); + throw error; + } + } + + private update(active: ActiveBlock): void { + const text = blockToRow(active.block).text; + if (text !== active.text) { + active.body.content = text; + active.text = text; + } + active.surface.render(); + } + + /** + * `final` ends the block's last commit with a newline. Without it OpenTUI's + * scrollback cursor stays at the end of the last text row, and the split + * footer, which sits just below that cursor, rises one row off the bottom + * whenever a turn finishes. + */ + private commitThrough(active: ActiveBlock, endRow: number, final = false): void { + const chunk = Math.max(1, Math.floor(MAX_COMMIT_CELLS / Math.max(1, active.surface.width))); + if (final && active.committedRows >= endRow) { + // Everything was streamed already; still end the block on a new line. + active.surface.commitRows(endRow, endRow, { trailingNewline: true }); + return; + } + while (active.committedRows < endRow) { + const next = Math.min(endRow, active.committedRows + chunk); + active.surface.commitRows(active.committedRows, next, final && next === endRow ? { trailingNewline: true } : undefined); + active.committedRows = next; + } + } + + private writeBlankRows(count: number): void { + const rows = Math.max(0, Math.floor(count)); + if (rows === 0) return; + const surface = this.host.createScrollbackSurface({ startOnNewLine: true }); + try { + surface.root.add(new TextRenderable(surface.renderContext, { content: "", width: "100%", height: rows })); + surface.render(); + surface.commitRows(0, Math.max(rows, surface.height)); + } finally { + surface.destroy(); + } + } + + private dropActive(): void { + this.active?.surface.destroy(); + this.active = undefined; + } +} diff --git a/crewcoder-opentui/src/session-controller.ts b/crewcoder-opentui/src/session-controller.ts new file mode 100644 index 0000000..df06566 --- /dev/null +++ b/crewcoder-opentui/src/session-controller.ts @@ -0,0 +1,158 @@ +import type { + CrewCoderEventHandler, + CrewCoderProcessOptions, + CrewCoderResumeOptions +} from "@onpoint-dev-tools/crewcoder-tui-core/bridge/crewcoder-process"; +import type { CrewCoderJsonEvent } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/event-parser"; +import { applyCrewCoderEvent } from "@onpoint-dev-tools/crewcoder-tui-core/state/event-reducer"; +import { createInitialState, type TuiEventBlock, type TuiState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; + +/** The subset of `CrewCoderProcessBridge` the OpenTUI shell drives. */ +export type SessionBridge = { + readonly running: boolean; + run(options: CrewCoderProcessOptions, onEvent: CrewCoderEventHandler): () => void; + resume(options: CrewCoderResumeOptions, onEvent: CrewCoderEventHandler): () => void; + followUp(message: string): boolean; + resolveApproval(approvalId: string, approved: boolean, reason?: string): boolean; + stop(): void; +}; + +type PendingApproval = Extract; + +/** + * Owns the shared TUI state and the agent bridge for one terminal session. + * React subscribes through `subscribe`/`getVersion`; the reducer mutates + * `state` in place, so every change bumps `version` to trigger a render. + */ +export class SessionController { + readonly state: TuiState; + private readonly bridge: SessionBridge; + private readonly listeners = new Set<() => void>(); + private version = 0; + + constructor(bridge: SessionBridge, state: TuiState = createInitialState()) { + this.bridge = bridge; + this.state = state; + // The legacy help tip refers to slash commands this preview does not ship yet. + this.state.blocks = []; + } + + subscribe = (listener: () => void): (() => void) => { + this.listeners.add(listener); + return () => this.listeners.delete(listener); + }; + + getVersion = (): number => this.version; + + /** Start, resume, or queue a follow-up for the active run. */ + submit(input: string): void { + const text = input.trim(); + if (!text) return; + if (text.startsWith("/")) { + this.runCommand(text); + this.notify(); + return; + } + if (this.bridge.running) { + if (this.bridge.followUp(text)) { + this.state.blocks.push({ type: "user", text, background: ["Queued follow-up for the running turn."] }); + } else { + this.state.blocks.push({ type: "error", text: "Could not queue follow-up for the active run." }); + } + this.notify(); + return; + } + this.startRun(text); + } + + /** Resolve the most recent pending approval over the live control channel. */ + resolvePendingApproval(approved: boolean): boolean { + const pending = this.pendingApproval(); + if (!pending?.id || !this.bridge.running) return false; + const reason = approved ? "Approved from OpenTUI control channel." : "Denied from OpenTUI control channel."; + const resolved = this.bridge.resolveApproval(pending.id, approved, reason); + if (!resolved) this.state.blocks.push({ type: "error", text: `Could not ${approved ? "approve" : "deny"} ${pending.id}.` }); + this.notify(); + return resolved; + } + + pendingApproval(): PendingApproval | undefined { + for (let index = this.state.blocks.length - 1; index >= 0; index--) { + const block = this.state.blocks[index]; + if (block?.type === "approval" && block.status === "pending") return block; + } + return undefined; + } + + /** Abort the active run. Returns false when nothing was running. */ + abort(): boolean { + if (!this.bridge.running && !this.state.running) return false; + this.bridge.stop(); + this.state.running = false; + this.state.blocks.push({ type: "system", text: "Request aborted." }); + this.notify(); + return true; + } + + dispose(): void { + this.bridge.stop(); + this.listeners.clear(); + } + + private startRun(prompt: string): void { + this.state.blocks.push({ type: "user", text: prompt }); + this.state.running = true; + const onEvent = (event: CrewCoderJsonEvent): void => { + applyCrewCoderEvent(this.state, event); + this.notify(); + }; + const shared = { + prompt, + provider: this.state.provider, + mode: this.state.mode, + worker: this.state.worker, + model: this.state.model, + systemPrompt: this.state.systemPrompt, + effort: this.state.effort, + cwd: this.state.cwd, + approval: this.state.fullAccess ? "full-access" as const : "review" as const, + budget: this.state.tokenBudget, + externalDirectories: this.state.externalDirectories + }; + this.notify(); + if (this.state.sessionId && this.state.sessionId !== "new") { + this.bridge.resume({ ...shared, sessionId: this.state.sessionId }, onEvent); + return; + } + this.bridge.run(shared, onEvent); + } + + private runCommand(command: string): void { + const name = command.split(/\s+/, 1)[0]; + if (name === "/new") { + this.bridge.stop(); + this.state.sessionId = "new"; + this.state.blocks = []; + this.state.running = false; + this.state.changedFiles = []; + this.state.usage = { turns: 0 }; + this.state.externalDirectories = []; + this.state.tokenBudget = undefined; + this.state.fullAccess = false; + return; + } + if (name === "/stop") { + if (!this.abort()) this.state.blocks.push({ type: "system", text: "Nothing is running." }); + return; + } + this.state.blocks.push({ + type: "error", + text: `${name} is not available in the OpenTUI preview yet. Use the legacy UI (crewcoder-tui) or the agent CLI for it.` + }); + } + + private notify(): void { + this.version += 1; + for (const listener of this.listeners) listener(); + } +} diff --git a/crewcoder-opentui/src/terminal-background.ts b/crewcoder-opentui/src/terminal-background.ts new file mode 100644 index 0000000..218e301 --- /dev/null +++ b/crewcoder-opentui/src/terminal-background.ts @@ -0,0 +1,27 @@ +/** + * Theme the whole terminal, not just the footer. In split-footer mode the + * transcript lives in the terminal's native scrollback, which OpenTUI does not + * paint, so it would show the terminal's default background. Like the legacy + * UI, set the terminal's default background with OSC 11 while running and + * restore it with OSC 111 on exit. + * + * Write these outside the renderer's lifetime: in `capture-stdout` mode, + * stdout writes made while it runs become plain scrollback text. + */ +export type TerminalWriter = { write(chunk: string): unknown }; + +const HEX_COLOR = /^#[0-9a-f]{6}$/i; + +/** Returns the reset function, which is safe to call more than once. */ +export function applyTerminalBackground(out: TerminalWriter, color: string): () => void { + // Only a plain #rrggbb may reach an escape sequence; anything else could + // inject terminal controls once themes become user-configurable. + if (!HEX_COLOR.test(color)) return () => {}; + out.write(`\x1b]11;${color}\x07`); + let reset = false; + return () => { + if (reset) return; + reset = true; + out.write("\x1b]111\x07"); + }; +} diff --git a/crewcoder-opentui/src/tests/app.test.tsx b/crewcoder-opentui/src/tests/app.test.tsx new file mode 100644 index 0000000..89f3ebb --- /dev/null +++ b/crewcoder-opentui/src/tests/app.test.tsx @@ -0,0 +1,203 @@ +import { testRender } from "@opentui/react/test-utils"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { App, riskLevel } from "../App.js"; +import { applyFooterHeight, footerSettled, prepareFooterForWrites } from "../footer-sizer.js"; +import { ThemeProvider } from "../providers/theme-provider.js"; +import { attachScrollback, ScrollbackWriter } from "../scrollback-writer.js"; +import { SessionController } from "../session-controller.js"; +import { gothamTheme } from "../theme.js"; +import { FakeBridge } from "./fake-bridge.js"; + +type Setup = Awaited>; +let active: Setup | undefined; + +afterEach(async () => { + await active?.dispose(); + active = undefined; +}); + +async function renderApp(): Promise<{ setup: Setup; bridge: FakeBridge; onQuit: ReturnType; scrollbackText: () => Promise }> { + const bridge = new FakeBridge(); + const controller = new SessionController(bridge); + const onQuit = vi.fn(); + // The writer needs the renderer, which testRender creates; give it a late-bound host. + let setup: Setup | undefined; + const writer = new ScrollbackWriter({ createScrollbackSurface: (options) => setup!.renderer.createScrollbackSurface(options) }, gothamTheme); + setup = await testRender( + + + , + { width: 80, height: 24, screenMode: "split-footer", externalOutputMode: "capture-stdout", footerHeight: 4 } + ); + attachScrollback(controller, writer, { prepare: () => prepareFooterForWrites(setup!.renderer, controller.state), size: () => applyFooterHeight(setup!.renderer, controller.state, writer), settled: () => footerSettled(setup!.renderer) }); + active = setup; + await setup.renderOnce(); + const scrollbackText = async (): Promise => { + await setup!.renderOnce(); + return setup!.externalOutput.takeText(); + }; + return { setup, bridge, onQuit, scrollbackText }; +} + +describe("OpenTUI split-footer App", () => { + it("writes the conversation to native scrollback and keeps only the live tail in the footer", async () => { + const { setup, bridge, scrollbackText } = await renderApp(); + + await setup.mockInput.typeText("hello crew"); + setup.mockInput.pressEnter(); + expect(bridge.runs).toEqual([expect.objectContaining({ prompt: "hello crew" })]); + + bridge.emit({ type: "agent_start", sessionId: "s-9" }); + bridge.emit({ type: "thinking_delta", text: "considering" }); + bridge.emit({ type: "assistant_delta", text: "hi there" }); + const footer = await setup.waitForFrame((text) => text.includes("Working")); + expect(footer).toContain("hi there"); + expect(footer).toContain("s-9"); + + bridge.emit({ type: "agent_end" }); + const committed = await scrollbackText(); + expect(committed).toContain("YOU"); + expect(committed).toContain("hello crew"); + expect(committed).toContain("THINKING"); + expect(committed).toContain("considering"); + expect(committed).toContain("CREW CODER"); + expect(committed).toContain("hi there"); + const idle = await setup.waitForFrame((text) => !text.includes("Working")); + expect(idle).not.toContain("hi there"); + }); + + it("shows a pending approval card and resolves it only with the configured chord", async () => { + const { setup, bridge } = await renderApp(); + await setup.mockInput.typeText("clean"); + setup.mockInput.pressEnter(); + bridge.emit({ type: "approval_required", approvalId: "a-1", toolName: "bash", risk: "dangerous", reason: "rm -r build", args: { command: "rm -r build" } }); + + const frame = await setup.waitForFrame((text) => text.includes("Tool Approval Required")); + expect(frame).toContain("[HIGH RISK]"); + expect(frame).toContain("bash"); + expect(frame).toContain("[^Y] Approve"); + expect(frame).toContain("[^N] Deny"); + + // Upstream termcn approved on a bare "y"; typing it in the composer must not approve. + await setup.mockInput.typeText("yes y"); + await setup.renderOnce(); + expect(bridge.approvals).toEqual([]); + + setup.mockInput.pressKey("y", { ctrl: true }); + await setup.renderOnce(); + expect(bridge.approvals).toEqual([{ id: "a-1", approved: true }]); + }); + + it("shows running tools in the footer and commits them once they finish", async () => { + const { setup, bridge, scrollbackText } = await renderApp(); + await setup.mockInput.typeText("test"); + setup.mockInput.pressEnter(); + bridge.emit({ type: "tool_execution_start", toolName: "bash", toolCallId: "t1", args: { command: "npm test" } }); + + const frame = await setup.waitForFrame((text) => text.includes("bash")); + expect(frame).toContain("Working"); + expect(await scrollbackText()).not.toContain("TOOL bash"); + + bridge.emit({ type: "tool_execution_end", toolName: "bash", toolCallId: "t1", result: "all green" }); + bridge.emit({ type: "agent_end" }); + expect(await scrollbackText()).toContain("TOOL bash"); + }); + + it("aborts the running request on escape and quits on ctrl+c", async () => { + const { setup, bridge, onQuit } = await renderApp(); + await setup.mockInput.typeText("long"); + setup.mockInput.pressEnter(); + await setup.renderOnce(); + + setup.mockInput.pressEscape(); + // A lone ESC is delivered after the parser's escape-sequence timeout. + await vi.waitFor(() => expect(bridge.stops).toBe(1), { timeout: 2_000 }); + + setup.mockInput.pressKey("c", { ctrl: true }); + expect(onQuit).toHaveBeenCalledTimes(1); + }); +}); + +describe("welcome screen", () => { + it("centers the logo with the composer on a fresh session and leaves on the first prompt", async () => { + const { setup, bridge } = await renderApp(); + const frame = await setup.waitForFrame((text) => text.includes("Type your first request")); + const lines = frame.split("\n"); + const logoRow = lines.findIndex((line) => line.includes("██████")); + + expect(logoRow).toBeGreaterThan(0); + // Centered horizontally: equal margins within one column. + const logoLine = lines[logoRow] ?? ""; + const left = logoLine.length - logoLine.trimStart().length; + const right = logoLine.length - logoLine.trimEnd().length; + expect(Math.abs(left - right)).toBeLessThanOrEqual(1); + // Centered vertically: blank rows above the logo. + expect(lines.slice(0, logoRow).every((line) => line.trim() === "")).toBe(true); + expect(frame).toContain("Ask CrewCoder"); + expect(frame).toContain("^C quit"); + + await setup.mockInput.typeText("hello"); + setup.mockInput.pressEnter(); + expect(bridge.runs).toHaveLength(1); + const after = await setup.waitForFrame((text) => text.includes("Working")); + expect(after).not.toContain("██████"); + }); + + it("shows only the composer, no logo, on a small window", async () => { + const bridge = new FakeBridge(); + const controller = new SessionController(bridge); + let setup: Setup | undefined; + const writer = new ScrollbackWriter({ createScrollbackSurface: (options) => setup!.renderer.createScrollbackSurface(options) }, gothamTheme); + setup = await testRender( + + {}} /> + , + { width: 60, height: 24, screenMode: "split-footer", externalOutputMode: "capture-stdout", footerHeight: 4 } + ); + attachScrollback(controller, writer, { prepare: () => prepareFooterForWrites(setup!.renderer, controller.state), size: () => applyFooterHeight(setup!.renderer, controller.state, writer), settled: () => footerSettled(setup!.renderer) }); + active = setup; + const frame = await setup.waitForFrame((text) => text.includes("Type your first request")); + + expect(frame).not.toContain("█"); + expect(frame).not.toContain("┏┓"); + expect(frame).not.toContain("CREW CODER"); + expect(frame).toContain("Ask CrewCoder"); + }); + + it("keeps the composer at the bottom of the terminal during a short conversation", async () => { + const { setup, bridge } = await renderApp(); + await setup.mockInput.typeText("hi"); + setup.mockInput.pressEnter(); + bridge.emit({ type: "agent_end" }); + // Require the composer: a frame captured mid-resize is unpainted and matches nothing. + const frame = await setup.waitForFrame((text) => text.includes("Ask CrewCoder") && !text.includes("Type your first request") && !text.includes("Working")); + const lines = frame.split("\n").filter((line, index, all) => index < all.length - 1 || line.trim() !== ""); + + // The status line is the last row of the 24-row terminal, the composer just above it. + expect(setup.renderer.footerHeight).toBeGreaterThan(4); + expect(lines.at(-1)).toContain("claude"); + expect(lines.at(-3)).toContain("Ask CrewCoder"); + }); + + it("returns to the welcome screen after /new", async () => { + const { setup, bridge } = await renderApp(); + await setup.mockInput.typeText("hi"); + setup.mockInput.pressEnter(); + bridge.emit({ type: "agent_end" }); + await setup.waitForFrame((text) => !text.includes("Type your first request")); + + await setup.mockInput.typeText("/new"); + setup.mockInput.pressEnter(); + await setup.waitForFrame((text) => text.includes("Type your first request")); + }); +}); + +describe("riskLevel", () => { + it("maps agent approval risks and ignores unknown or prototype keys", () => { + expect(riskLevel("safe")).toBe("low"); + expect(riskLevel("review")).toBe("medium"); + expect(riskLevel("dangerous")).toBe("high"); + expect(riskLevel("constructor")).toBeUndefined(); + expect(riskLevel(undefined)).toBeUndefined(); + }); +}); diff --git a/crewcoder-opentui/src/tests/fake-bridge.ts b/crewcoder-opentui/src/tests/fake-bridge.ts new file mode 100644 index 0000000..54088ba --- /dev/null +++ b/crewcoder-opentui/src/tests/fake-bridge.ts @@ -0,0 +1,51 @@ +import type { CrewCoderEventHandler, CrewCoderProcessOptions, CrewCoderResumeOptions } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/crewcoder-process"; +import type { CrewCoderJsonEvent } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/event-parser"; +import type { SessionBridge } from "../session-controller.js"; + +/** Records bridge calls and lets tests push agent events into the active run. */ +export class FakeBridge implements SessionBridge { + running = false; + runs: CrewCoderProcessOptions[] = []; + resumes: CrewCoderResumeOptions[] = []; + followUps: string[] = []; + approvals: Array<{ id: string; approved: boolean }> = []; + stops = 0; + private handler: CrewCoderEventHandler | undefined; + + run(options: CrewCoderProcessOptions, onEvent: CrewCoderEventHandler): () => void { + this.runs.push(options); + return this.attach(onEvent); + } + + resume(options: CrewCoderResumeOptions, onEvent: CrewCoderEventHandler): () => void { + this.resumes.push(options); + return this.attach(onEvent); + } + + followUp(message: string): boolean { + this.followUps.push(message); + return this.running; + } + + resolveApproval(approvalId: string, approved: boolean): boolean { + this.approvals.push({ id: approvalId, approved }); + return this.running; + } + + stop(): void { + this.stops += 1; + this.running = false; + } + + emit(event: CrewCoderJsonEvent): void { + if (!this.handler) throw new Error("No active run to emit into."); + this.handler(event); + if (event.type === "agent_end" || event.type === "process_exit") this.running = false; + } + + private attach(onEvent: CrewCoderEventHandler): () => void { + this.running = true; + this.handler = onEvent; + return () => this.stop(); + } +} diff --git a/crewcoder-opentui/src/tests/footer-layout.test.ts b/crewcoder-opentui/src/tests/footer-layout.test.ts new file mode 100644 index 0000000..1c4c808 --- /dev/null +++ b/crewcoder-opentui/src/tests/footer-layout.test.ts @@ -0,0 +1,95 @@ +import type { TuiEventBlock } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; +import { describe, expect, it } from "vitest"; +import { toolApprovalHeight } from "../components/ui/tool-approval.js"; +import { COMPOSER_ROWS, footerModel, footerHeight, HOME_BODY_ROWS, homeComposerWidth, homeLogo, isHome, shortenPath, MAX_FOOTER_TOOLS, RESERVED_ROWS, STATUS_ROWS, streamingTail } from "../footer-layout.js"; + +const tool = (id: string): TuiEventBlock => ({ type: "tool", id, name: "bash", status: "running" }); + +describe("footerModel", () => { + it("keeps the reserved tail and working rows so idle and running heights match", () => { + expect(footerModel([], false).rows).toBe(RESERVED_ROWS + COMPOSER_ROWS + STATUS_ROWS); + expect(footerModel([], true).rows).toBe(footerModel([], false).rows); + expect(footerModel([{ type: "assistant", text: "hi" }], true).rows).toBe(footerModel([], false).rows); + }); + + it("adds a working row, the streaming tail, and bounded running tools", () => { + const pending = [tool("1"), tool("2"), tool("3"), tool("4"), tool("5"), { type: "assistant", text: "hi" } satisfies TuiEventBlock]; + const model = footerModel(pending, true); + + expect(model.tools).toHaveLength(MAX_FOOTER_TOOLS); + expect(model.hiddenTools).toBe(2); + expect(model.streaming?.type).toBe("assistant"); + expect(model.rows).toBe(MAX_FOOTER_TOOLS + 1 + RESERVED_ROWS + COMPOSER_ROWS + STATUS_ROWS); + }); + + it("sizes a pending approval card from its content", () => { + const approval: TuiEventBlock = { type: "approval", id: "a", toolName: "bash", text: "rm build", args: { command: "rm -r build" }, status: "pending" }; + const model = footerModel([approval], true); + + expect(model.approval).toBe(approval); + expect(model.rows).toBe(toolApprovalHeight({ description: "rm build", args: { command: "rm -r build" } }) + RESERVED_ROWS + COMPOSER_ROWS + STATUS_ROWS); + }); + + it("does not treat a finished-run assistant block as streaming", () => { + expect(footerModel([{ type: "assistant", text: "x" }], false).streaming).toBeUndefined(); + }); +}); + +describe("toolApprovalHeight", () => { + it("bounds the argument list", () => { + const args = { a: 1, b: 2, c: 3, d: 4, e: 5 }; + expect(toolApprovalHeight({ args })).toBe(2 + 1 + 1 + (1 + 3 + 1) + 1); + expect(toolApprovalHeight({})).toBe(5); + }); +}); + +describe("streamingTail", () => { + it("shows the end of the last line, truncated from the left", () => { + expect(streamingTail("first\nsecond line", 40)).toBe("second line"); + expect(streamingTail("abcdefghij", 6)).toBe("…ghij"); + }); +}); + +describe("home screen layout", () => { + it("shows only for an empty, idle session", () => { + expect(isHome([], false)).toBe(true); + expect(isHome([], true)).toBe(false); + expect(isHome([{ type: "error", text: "/goal is not available" }], false)).toBe(false); + }); + + it("shows the big wordmark only when it fits, otherwise no logo at all", () => { + const logo = ["x".repeat(60), "x".repeat(60)]; + expect(homeLogo(80, 30, logo)).toBe(logo); + expect(homeLogo(69, 30, logo)).toBeUndefined(); + expect(homeLogo(61, 30, ["x".repeat(66)])).toBeUndefined(); + // Too short to keep the composer whole under the logo. + expect(homeLogo(80, 2 + HOME_BODY_ROWS + 1, logo)).toBeUndefined(); + expect(homeLogo(80, 2 + HOME_BODY_ROWS + 2, logo)).toBe(logo); + }); + + it("sizes the composer at 62% with a floor", () => { + expect(homeComposerWidth(100)).toBe(62); + expect(homeComposerWidth(30)).toBe(24); + expect(homeComposerWidth(20)).toBe(20); + }); +}); + +describe("shortenPath", () => { + it("abbreviates the local home and keeps the end of long paths", () => { + expect(shortenPath("/home/me/code/app", 40, "/home/me")).toBe("~/code/app"); + expect(shortenPath("/home/meadow/x", 40, "/home/me")).toBe("/home/meadow/x"); + expect(shortenPath("/srv/projects/crewcoder", 12)).toBe("…s/crewcoder"); + expect(shortenPath("/srv/projects/crewcoder", 12)).toHaveLength(12); + }); +}); + +describe("footerHeight", () => { + it("fills the terminal on the welcome screen", () => { + expect(footerHeight({ home: true, contentRows: 6, terminalHeight: 30 })).toBe(30); + expect(footerHeight({ home: true, contentRows: 40, terminalHeight: 30 })).toBe(40); + }); + + it("is just its content in a conversation", () => { + expect(footerHeight({ home: false, contentRows: 6, terminalHeight: 30 })).toBe(6); + }); +}); diff --git a/crewcoder-opentui/src/tests/footer-sizer.test.ts b/crewcoder-opentui/src/tests/footer-sizer.test.ts new file mode 100644 index 0000000..5f92785 --- /dev/null +++ b/crewcoder-opentui/src/tests/footer-sizer.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from "vitest"; +import { applyFooterHeight, footerSettled, prepareFooterForWrites } from "../footer-sizer.js"; +import { footerModel } from "../footer-layout.js"; + +const host = (footerHeight: number, height = footerHeight, terminalHeight = 30) => ({ footerHeight, height, terminalHeight }); + +describe("prepareFooterForWrites", () => { + it("shrinks the full-height welcome footer as soon as the session has a block", () => { + const h = host(30); + prepareFooterForWrites(h, { blocks: [{ type: "user", text: "hi" }], running: true }); + expect(h.footerHeight).toBe(footerModel([], true).rows); + }); + + it("leaves the welcome screen and ordinary conversation footers alone", () => { + const home = host(30); + prepareFooterForWrites(home, { blocks: [], running: false }); + expect(home.footerHeight).toBe(30); + + // A stale pending list must not resize a conversation footer before writing. + const chat = host(6); + prepareFooterForWrites(chat, { blocks: [{ type: "assistant", text: "done" }], running: false }); + expect(chat.footerHeight).toBe(6); + }); +}); + +describe("applyFooterHeight", () => { + it("sizes from the current pending blocks", () => { + const h = host(30); + applyFooterHeight(h, { blocks: [{ type: "user", text: "hi" }], running: false }, { pending: [] }); + expect(h.footerHeight).toBe(footerModel([], false).rows); + }); +}); + +describe("footerSettled", () => { + it("is true only once the renderer applied the requested height", () => { + expect(footerSettled(host(6, 30))).toBe(false); + expect(footerSettled(host(6, 6))).toBe(true); + expect(footerSettled(host(40, 30, 30))).toBe(true); + }); +}); diff --git a/crewcoder-opentui/src/tests/keybindings-args.test.ts b/crewcoder-opentui/src/tests/keybindings-args.test.ts new file mode 100644 index 0000000..9182ef1 --- /dev/null +++ b/crewcoder-opentui/src/tests/keybindings-args.test.ts @@ -0,0 +1,39 @@ +import { describe, expect, it } from "vitest"; +import { parseArgs } from "../args.js"; +import { actionLabel, DEFAULT_APP_KEYBINDINGS, matchesAction } from "../keybindings.js"; + +const key = (name: string, modifiers: Partial<{ ctrl: boolean; meta: boolean; shift: boolean }> = {}) => ({ name, ctrl: false, meta: false, shift: false, ...modifiers }); + +describe("keybindings", () => { + it("matches default chords exactly, including modifiers", () => { + expect(matchesAction(key("y", { ctrl: true }), "approve")).toBe(true); + expect(matchesAction(key("y"), "approve")).toBe(false); + expect(matchesAction(key("y", { ctrl: true, shift: true }), "approve")).toBe(false); + expect(matchesAction(key("escape"), "abort")).toBe(true); + }); + + it("honors overridden bindings", () => { + const bindings = { ...DEFAULT_APP_KEYBINDINGS, approve: ["meta+a"] }; + expect(matchesAction(key("a", { meta: true }), "approve", bindings)).toBe(true); + expect(matchesAction(key("y", { ctrl: true }), "approve", bindings)).toBe(false); + expect(actionLabel("approve", bindings)).toBe("M-A"); + }); + + it("labels default chords", () => { + expect(actionLabel("approve")).toBe("^Y"); + expect(actionLabel("abort")).toBe("escape"); + }); +}); + +describe("parseArgs", () => { + it("parses remote flags in both forms", () => { + expect(parseArgs(["--remote", "me@vps", "--remote-cwd=/work"])).toEqual({ help: false, remote: "me@vps", remoteCwd: "/work" }); + expect(parseArgs(["-h"]).help).toBe(true); + }); + + it("rejects unknown flags and missing values", () => { + expect(() => parseArgs(["--theme", "dark"])).toThrow(/Unknown argument/); + expect(() => parseArgs(["--remote"])).toThrow(/requires a value/); + expect(() => parseArgs(["--remote="])).toThrow(/requires a value/); + }); +}); diff --git a/crewcoder-opentui/src/tests/scrollback-writer.test.ts b/crewcoder-opentui/src/tests/scrollback-writer.test.ts new file mode 100644 index 0000000..7e5a0e0 --- /dev/null +++ b/crewcoder-opentui/src/tests/scrollback-writer.test.ts @@ -0,0 +1,108 @@ +import type { TuiEventBlock } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; +import { createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"; +import { afterEach, describe, expect, it } from "vitest"; +import { ScrollbackWriter } from "../scrollback-writer.js"; +import { gothamTheme } from "../theme.js"; + +let active: TestRendererSetup | undefined; + +afterEach(async () => { + await active?.dispose(); + active = undefined; +}); + +async function setup(width = 40): Promise<{ term: TestRendererSetup; writer: ScrollbackWriter; flush: () => Promise }> { + const term = await createTestRenderer({ width, height: 20, screenMode: "split-footer", externalOutputMode: "capture-stdout", footerHeight: 4 }); + active = term; + const writer = new ScrollbackWriter(term.renderer, gothamTheme); + const flush = async (): Promise => { + await term.renderOnce(); + return term.externalOutput.take().flatMap((commit) => commit.rows.map((row) => row.trimEnd())); + }; + return { term, writer, flush }; +} + +describe("ScrollbackWriter", () => { + it("commits settled blocks once, in order, separated by a blank row", async () => { + const { writer, flush } = await setup(); + const blocks: TuiEventBlock[] = [ + { type: "user", text: "fix it", background: ["repo: crewcoder"] }, + { type: "assistant", text: "done" } + ]; + + expect(writer.sync(blocks, false)).toEqual([]); + expect(await flush()).toEqual(["YOU", "fix it", "repo: crewcoder", "", "CREW CODER", "done"]); + + writer.sync(blocks, false); + expect(await flush()).toEqual([]); + }); + + it("streams finished rows of the last assistant block and holds back the changing row", async () => { + const { writer, flush } = await setup(20); + const reply: TuiEventBlock = { type: "assistant", text: "one two three four five six" }; + const blocks: TuiEventBlock[] = [reply]; + + expect(writer.sync(blocks, true)).toEqual([reply]); + const first = await flush(); + expect(first[0]).toBe("CREW CODER"); + expect(first.join(" ")).not.toContain("six"); + + reply.text += " seven eight"; + writer.sync(blocks, true); + writer.sync(blocks, false); + const rest = await flush(); + const all = [...first, ...rest]; + + expect(all.slice(1).join(" ").replace(/\s+/g, " ")).toBe("one two three four five six seven eight"); + expect(writer.pending).toEqual([]); + }); + + it("holds every block after a live one so scrollback stays in order", async () => { + const { writer, flush } = await setup(); + const tool: TuiEventBlock = { type: "tool", id: "t1", name: "bash", status: "running" }; + const after: TuiEventBlock = { type: "assistant", text: "after the tool" }; + const blocks: TuiEventBlock[] = [{ type: "user", text: "go" }, tool, after]; + + expect(writer.sync(blocks, true)).toEqual([tool, after]); + expect(await flush()).toEqual(["YOU", "go"]); + + tool.status = "done"; + tool.text = "ok"; + expect(writer.sync(blocks, true)).toEqual([after]); + writer.sync(blocks, false); + expect(await flush()).toEqual(["", "TOOL bash · done", "ok", "", "CREW CODER", "after the tool"]); + }); + + it("does not re-commit blocks after the reducer trims and re-slices the array", async () => { + const { writer, flush } = await setup(); + const blocks: TuiEventBlock[] = [{ type: "system", text: "a" }, { type: "system", text: "b" }]; + writer.sync(blocks, false); + await flush(); + + const trimmed = [...blocks.slice(-1), { type: "system", text: "c" } satisfies TuiEventBlock]; + writer.sync(trimmed, false); + + expect(await flush()).toEqual(["", "SYSTEM", "c"]); + }); + + it("pads a fresh screen once so the footer starts at the bottom, and again after /new", async () => { + const { term, flush } = await setup(); + const writer = new ScrollbackWriter(term.renderer, gothamTheme, () => 3); + writer.sync([{ type: "user", text: "one" }, { type: "assistant", text: "two" }], false); + expect(await flush()).toEqual(["", "", "", "YOU", "one", "", "CREW CODER", "two"]); + + writer.sync([], false); + writer.sync([{ type: "user", text: "fresh" }], false); + expect(await flush()).toEqual(["", "", "", "YOU", "fresh"]); + }); + + it("drops a streaming block that disappears, such as after /new", async () => { + const { writer, flush } = await setup(); + writer.sync([{ type: "assistant", text: "partial" }], true); + await flush(); + + expect(writer.sync([], false)).toEqual([]); + writer.sync([{ type: "user", text: "fresh" }], false); + expect((await flush()).filter(Boolean)).toEqual(["YOU", "fresh"]); + }); +}); diff --git a/crewcoder-opentui/src/tests/session-controller.test.ts b/crewcoder-opentui/src/tests/session-controller.test.ts new file mode 100644 index 0000000..682ec2d --- /dev/null +++ b/crewcoder-opentui/src/tests/session-controller.test.ts @@ -0,0 +1,120 @@ +import { describe, expect, it } from "vitest"; +import { SessionController } from "../session-controller.js"; +import { FakeBridge } from "./fake-bridge.js"; + +function setup(): { bridge: FakeBridge; controller: SessionController } { + const bridge = new FakeBridge(); + return { bridge, controller: new SessionController(bridge) }; +} + +describe("SessionController", () => { + it("starts a new run in review approval mode and renders streamed events", () => { + const { bridge, controller } = setup(); + let renders = 0; + controller.subscribe(() => { renders += 1; }); + + controller.submit(" fix the tests "); + bridge.emit({ type: "agent_start", sessionId: "s-1" }); + bridge.emit({ type: "thinking_delta", text: "Looking at failures" }); + bridge.emit({ type: "assistant_delta", text: "Done." }); + + expect(bridge.runs).toHaveLength(1); + expect(bridge.runs[0]).toMatchObject({ prompt: "fix the tests", approval: "review" }); + expect(controller.state.sessionId).toBe("s-1"); + expect(controller.state.blocks.map((block) => block.type)).toEqual(["user", "thinking", "assistant"]); + expect(renders).toBeGreaterThanOrEqual(4); + }); + + it("resumes the saved session once the first run has ended", () => { + const { bridge, controller } = setup(); + controller.submit("first"); + bridge.emit({ type: "agent_start", sessionId: "s-1" }); + bridge.emit({ type: "agent_end" }); + + controller.submit("second"); + + expect(bridge.runs).toHaveLength(1); + expect(bridge.resumes).toEqual([expect.objectContaining({ sessionId: "s-1", prompt: "second" })]); + }); + + it("queues prompts typed during an active run as follow-ups", () => { + const { bridge, controller } = setup(); + controller.submit("first"); + controller.submit("also check lint"); + + expect(bridge.runs).toHaveLength(1); + expect(bridge.followUps).toEqual(["also check lint"]); + expect(controller.state.blocks.at(-1)).toMatchObject({ type: "user", text: "also check lint", background: ["Queued follow-up for the running turn."] }); + }); + + it("resolves only the latest pending approval over the control channel", () => { + const { bridge, controller } = setup(); + controller.submit("delete build"); + bridge.emit({ type: "approval_required", approvalId: "a-1", toolName: "bash", reason: "rm build" }); + + expect(controller.pendingApproval()?.id).toBe("a-1"); + expect(controller.resolvePendingApproval(true)).toBe(true); + bridge.emit({ type: "approval_resolved", approvalId: "a-1", approved: true }); + + expect(bridge.approvals).toEqual([{ id: "a-1", approved: true }]); + expect(controller.pendingApproval()).toBeUndefined(); + expect(controller.resolvePendingApproval(false)).toBe(false); + }); + + it("does not approve when no run is attached", () => { + const { bridge, controller } = setup(); + controller.submit("x"); + bridge.emit({ type: "approval_required", approvalId: "a-1" }); + bridge.stop(); + + expect(controller.resolvePendingApproval(true)).toBe(false); + expect(bridge.approvals).toEqual([]); + }); + + it("aborts a running request and reports when nothing is running", () => { + const { bridge, controller } = setup(); + expect(controller.abort()).toBe(false); + + controller.submit("long task"); + expect(controller.abort()).toBe(true); + expect(bridge.running).toBe(false); + expect(controller.state.running).toBe(false); + + controller.submit("/stop"); + expect(controller.state.blocks.at(-1)).toMatchObject({ type: "system", text: "Nothing is running." }); + }); + + it("/new clears session-scoped state and starts a fresh run next", () => { + const { bridge, controller } = setup(); + controller.submit("first"); + bridge.emit({ type: "agent_start", sessionId: "s-1" }); + bridge.emit({ type: "agent_end" }); + controller.state.tokenBudget = 1000; + controller.state.fullAccess = true; + + controller.submit("/new"); + controller.submit("again"); + + expect(controller.state.sessionId).toBe("new"); + expect(controller.state.tokenBudget).toBeUndefined(); + expect(bridge.runs.at(-1)).toMatchObject({ prompt: "again", approval: "review" }); + expect(bridge.resumes).toHaveLength(0); + }); + + it("reports unported slash commands instead of sending them as prompts", () => { + const { bridge, controller } = setup(); + controller.submit("/goal ship it"); + + expect(bridge.runs).toHaveLength(0); + expect(controller.state.blocks).toEqual([ + { type: "error", text: expect.stringContaining("/goal is not available in the OpenTUI preview") } + ]); + }); + + it("ignores blank input", () => { + const { bridge, controller } = setup(); + controller.submit(" "); + expect(bridge.runs).toHaveLength(0); + expect(controller.state.blocks).toEqual([]); + }); +}); diff --git a/crewcoder-opentui/src/tests/terminal-background.test.ts b/crewcoder-opentui/src/tests/terminal-background.test.ts new file mode 100644 index 0000000..7891dff --- /dev/null +++ b/crewcoder-opentui/src/tests/terminal-background.test.ts @@ -0,0 +1,26 @@ +import { describe, expect, it } from "vitest"; +import { applyTerminalBackground } from "../terminal-background.js"; + +const sink = (): { writes: string[]; write(chunk: string): void } => { + const writes: string[] = []; + return { writes, write: (chunk: string) => { writes.push(chunk); } }; +}; + +describe("applyTerminalBackground", () => { + it("sets the terminal background with OSC 11 and restores it once with OSC 111", () => { + const out = sink(); + const reset = applyTerminalBackground(out, "#0c1014"); + reset(); + reset(); + + expect(out.writes).toEqual(["\x1b]11;#0c1014\x07", "\x1b]111\x07"]); + }); + + it("refuses anything but #rrggbb so a theme value cannot inject terminal controls", () => { + const out = sink(); + applyTerminalBackground(out, "#0c1014\x07\x1b]52;c;cHduZWQ=\x07")(); + applyTerminalBackground(out, "red")(); + + expect(out.writes).toEqual([]); + }); +}); diff --git a/crewcoder-opentui/src/tests/transcript.test.ts b/crewcoder-opentui/src/tests/transcript.test.ts new file mode 100644 index 0000000..d1ab06d --- /dev/null +++ b/crewcoder-opentui/src/tests/transcript.test.ts @@ -0,0 +1,61 @@ +import type { TuiEventBlock } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; +import { describe, expect, it } from "vitest"; +import { blockPhase, blockToRow, normalize } from "../transcript.js"; + +describe("blockToRow", () => { + it("keeps thinking separate from assistant text and background separate from typed text", () => { + const rows = ([ + { type: "user", text: "hi", background: ["repo: crewcoder", "branch: main"] }, + { type: "thinking", text: "plan" }, + { type: "assistant", text: "hello" } + ] satisfies TuiEventBlock[]).map(blockToRow); + + expect(rows.map((row) => [row.label, row.tone, row.text])).toEqual([ + ["YOU", "user", "hi"], + ["THINKING", "thinking", "plan"], + ["CREW CODER", "assistant", "hello"] + ]); + expect(rows[0]?.detail).toBe("repo: crewcoder\nbranch: main"); + }); + + it("clamps long tool output and flags failed tools as errors", () => { + const output = Array.from({ length: 20 }, (_, index) => `line ${index}`).join("\n"); + const row = blockToRow({ type: "tool", name: "bash", status: "error", text: output }); + + expect(row.tone).toBe("error"); + expect(row.text.split("\n")).toHaveLength(13); + expect(row.text).toContain("… 8 more lines"); + }); + + it("shows unported structured blocks instead of dropping them", () => { + expect(blockToRow({ type: "crew", workers: [], completed: false })).toMatchObject({ label: "CREW", tone: "muted" }); + }); +}); + +describe("blockPhase", () => { + it("streams only the last assistant or thinking block of an active run", () => { + expect(blockPhase({ type: "assistant", text: "a" }, true, true)).toBe("streaming"); + expect(blockPhase({ type: "thinking", text: "a" }, true, true)).toBe("streaming"); + expect(blockPhase({ type: "assistant", text: "a" }, false, true)).toBe("final"); + }); + + it("keeps in-place changing blocks live while the run is active", () => { + expect(blockPhase({ type: "tool", name: "bash", status: "running" }, false, true)).toBe("live"); + expect(blockPhase({ type: "tool", name: "bash", status: "done" }, false, true)).toBe("final"); + expect(blockPhase({ type: "approval", text: "x", status: "pending" }, false, true)).toBe("live"); + expect(blockPhase({ type: "approval", text: "x", status: "denied" }, false, true)).toBe("final"); + expect(blockPhase({ type: "crew", workers: [], completed: false }, false, true)).toBe("live"); + }); + + it("treats every block as final once the run is over, even one left running", () => { + expect(blockPhase({ type: "tool", name: "bash", status: "running" }, true, false)).toBe("final"); + expect(blockPhase({ type: "assistant", text: "a" }, true, false)).toBe("final"); + }); +}); + +describe("normalize", () => { + it("normalizes Windows line endings and strips terminal control sequences", () => { + expect(normalize("a\r\nb\rc")).toBe("a\nb\nc"); + expect(normalize("\x1b[31mred\x1b[0m \x1b]0;title\x07ok\x07\x08")).toBe("red ok"); + }); +}); diff --git a/crewcoder-opentui/src/theme.ts b/crewcoder-opentui/src/theme.ts new file mode 100644 index 0000000..41ba88b --- /dev/null +++ b/crewcoder-opentui/src/theme.ts @@ -0,0 +1,58 @@ +import type { Theme } from "./components/ui/types.js"; +import { defaultTheme } from "./lib/terminal-themes/default.js"; +import type { TranscriptTone } from "./transcript.js"; + +/** + * Gotham, CrewCoder's base identity (shared with the legacy TUI's default + * `dark` theme), expressed as termcn theme tokens. The background, border, and + * primary colors are fixed by the project; the rest are Gotham palette colors. + */ +export const gothamTheme: Theme = { + ...defaultTheme, + name: "gotham", + border: { color: "#195466", focusColor: "#33859e", style: "rounded" }, + colors: { + background: "#0c1014", + foreground: "#99d1ce", + primary: "#33859e", + primaryForeground: "#0c1014", + secondary: "#245361", + secondaryForeground: "#99d1ce", + accent: "#d26937", + accentForeground: "#0c1014", + success: "#2aa889", + successForeground: "#0c1014", + warning: "#edb443", + warningForeground: "#0c1014", + error: "#c23127", + errorForeground: "#99d1ce", + info: "#599cab", + infoForeground: "#0c1014", + muted: "#11151c", + mutedForeground: "#599cab", + border: "#195466", + focusRing: "#33859e", + selection: "#245361", + selectionForeground: "#99d1ce" + } +}; + +/** Gotham violet for reasoning text; termcn has no dedicated token for it. */ +export const THINKING_COLOR = "#888ca6"; + +export function toneColor(theme: Theme, tone: TranscriptTone): string { + switch (tone) { + case "user": return theme.colors.primary; + case "assistant": return theme.colors.success; + case "thinking": return THINKING_COLOR; + case "tool": return theme.colors.info; + case "approval": return theme.colors.warning; + case "error": return theme.colors.error; + case "system": + case "muted": return theme.colors.mutedForeground; + } +} + +export function bodyColor(theme: Theme, tone: TranscriptTone): string { + return tone === "thinking" ? THINKING_COLOR : theme.colors.foreground; +} diff --git a/crewcoder-opentui/src/transcript.ts b/crewcoder-opentui/src/transcript.ts new file mode 100644 index 0000000..d52a60a --- /dev/null +++ b/crewcoder-opentui/src/transcript.ts @@ -0,0 +1,110 @@ +import type { TuiEventBlock } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; + +export type TranscriptTone = "user" | "assistant" | "thinking" | "tool" | "approval" | "error" | "system" | "muted"; + +export type TranscriptRow = { + label: string; + tone: TranscriptTone; + text: string; + /** Muted context rendered under the row, such as user-message background. */ + detail?: string; +}; + +const MAX_TOOL_OUTPUT_LINES = 12; + +/** + * How a block may be written to native scrollback: + * - `final`: will not change again; commit it whole. + * - `streaming`: grows by appending text only; finished rows may be committed early. + * - `live`: still changes in place (running tool, pending approval, ...); keep it + * in the footer and commit nothing after it until it becomes final. + */ +export type BlockPhase = "final" | "streaming" | "live"; + +export function blockPhase(block: TuiEventBlock, isLast: boolean, running: boolean): BlockPhase { + // Once the run is over nothing can change a block any more, even one the + // agent never closed (a tool left "running" by a crashed process), so commit + // everything rather than holding scrollback back forever. + if (!running) return "final"; + switch (block.type) { + case "assistant": + case "thinking": + // The reducer only appends deltas to the last assistant/thinking block. + return isLast && running ? "streaming" : "final"; + case "tool": + return block.status === "running" ? "live" : "final"; + case "approval": + return block.status === "pending" ? "live" : "final"; + case "extension_ui": + return block.status === "pending" ? "live" : "final"; + case "compaction": + case "validation": + case "background_job": + return block.status === "running" ? "live" : "final"; + case "crew": + return block.completed ? "final" : "live"; + case "live_ui": + return block.status === "loading" || block.status === "ready" ? "live" : "final"; + default: + return "final"; + } +} + +/** Convert a reducer block into a display row. Pure, so it is tested without a renderer. */ +export function blockToRow(block: TuiEventBlock): TranscriptRow { + switch (block.type) { + case "user": + return { + label: "YOU", + tone: "user", + text: normalize(block.text), + // Background is provider context, not typed text; keep it visibly separate. + detail: block.background?.length ? normalize(block.background.join("\n")) : undefined + }; + case "assistant": + return { label: "CREW CODER", tone: "assistant", text: normalize(block.text) }; + case "thinking": + return { label: "THINKING", tone: "thinking", text: normalize(block.text) }; + case "tool": + return { + label: `TOOL ${block.name} · ${block.status}`, + tone: block.status === "error" ? "error" : "tool", + text: clampLines(normalize(block.text ?? ""), MAX_TOOL_OUTPUT_LINES) + }; + case "approval": + return { + label: `APPROVAL ${block.toolName ?? ""} · ${block.status}`.replace(/\s+·/, " ·"), + tone: "approval", + text: normalize(block.text), + detail: block.resolutionReason + }; + case "error": + return { label: "ERROR", tone: "error", text: normalize(block.text) }; + case "system": + return { label: "SYSTEM", tone: "system", text: normalize(block.text) }; + case "compaction": + return { label: `COMPACTION · ${block.status}`, tone: "system", text: normalize(block.message) }; + case "image": + return { label: "IMAGE", tone: "muted", text: block.attachment.path }; + default: + // Structured blocks (goals, crews, live UI, ...) are not ported yet. Show + // that something happened rather than silently dropping the event. + return { label: block.type.toUpperCase().replace(/_/g, " "), tone: "muted", text: "(not rendered in the OpenTUI preview yet)" }; + } +} + +/** Normalize line endings and strip terminal control sequences from agent text. */ +export function normalize(text: string): string { + return text + .replace(/\r\n?/g, "\n") + // eslint-disable-next-line no-control-regex + .replace(/\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[@-_]/g, "") + // eslint-disable-next-line no-control-regex + .replace(/[\x00-\x08\x0b-\x1f\x7f]/g, ""); +} + +function clampLines(text: string, maxLines: number): string { + const lines = text.split("\n"); + if (lines.length <= maxLines) return text; + return [...lines.slice(0, maxLines), `… ${lines.length - maxLines} more lines`].join("\n"); +} diff --git a/crewcoder-opentui/tsconfig.build.json b/crewcoder-opentui/tsconfig.build.json new file mode 100644 index 0000000..b82751a --- /dev/null +++ b/crewcoder-opentui/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["src/tests"] +} diff --git a/crewcoder-opentui/tsconfig.json b/crewcoder-opentui/tsconfig.json new file mode 100644 index 0000000..a25894f --- /dev/null +++ b/crewcoder-opentui/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist", + "jsx": "react-jsx", + "jsxImportSource": "@opentui/react" + }, + "include": ["src/**/*.ts", "src/**/*.tsx"] +} diff --git a/crewcoder-opentui/vitest.config.ts b/crewcoder-opentui/vitest.config.ts new file mode 100644 index 0000000..2029bbf --- /dev/null +++ b/crewcoder-opentui/vitest.config.ts @@ -0,0 +1,22 @@ +import { defineConfig } from "vitest/config"; + +// OpenTUI's native layer loads through Node's FFI, which Node.js exposes from 26.4. +const [major = 0, minor = 0] = process.versions.node.split(".").map(Number); +if (major < 26 || (major === 26 && minor < 4)) { + throw new Error( + `crewcoder-opentui tests need Node.js >=26.4.0 (current ${process.versions.node}). ` + + "Run them with a newer runtime, for example: mise exec node@26 -- npm test -w @onpoint-dev-tools/crewcoder-opentui" + ); +} + +export default defineConfig({ + esbuild: { + jsx: "automatic", + jsxImportSource: "@opentui/react" + }, + test: { + pool: "forks", + testTimeout: 10_000, + hookTimeout: 10_000 + } +}); diff --git a/crewcoder-tui-core/LICENSE b/crewcoder-tui-core/LICENSE new file mode 100644 index 0000000..dbb44a0 --- /dev/null +++ b/crewcoder-tui-core/LICENSE @@ -0,0 +1,191 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2026 OnPoint Dev Tools and CrewCoder contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/crewcoder-tui-core/README.md b/crewcoder-tui-core/README.md new file mode 100644 index 0000000..176e8a6 --- /dev/null +++ b/crewcoder-tui-core/README.md @@ -0,0 +1,51 @@ +# CrewCoder TUI core + +`@onpoint-dev-tools/crewcoder-tui-core` is the UI-independent runtime shared by +CrewCoder's terminal UIs: + +- [`@onpoint-dev-tools/crewcoder-opentui`](../crewcoder-opentui/README.md): the OpenTUI/React UI that the `crewcoder` umbrella launches. +- [`@onpoint-dev-tools/crewcoder-tui`](../crewcoder-tui/README.md): the legacy custom-renderer UI. + +It contains no rendering code and runs on Node.js 22 or newer. + +## Modules + +Import by subpath (there is no root export): + +| Subpath | Purpose | +|---|---| +| `bridge/crewcoder-process` | `CrewCoderProcessBridge`: spawns `crewcoder run --json-events` / `session resume`, writes approval, follow-up, UI-response and compaction control messages, and runs the one-shot CLI helpers (sessions, providers, extension renderers). | +| `bridge/event-parser` | Zod-validated parser for the agent's JSON event stream. | +| `bridge/remote-connection` | SSH target validation and POSIX quoting for `--remote` mode. | +| `bridge/live-ui-protocol` | Live UI message and permission types. | +| `state/tui-store` | `TuiState`, transcript block types, and `createInitialState()`. | +| `state/event-reducer` | `applyCrewCoderEvent(state, event)`: the single event-to-state reducer. | +| `state/usage`, `state/effort-levels`, `state/image-attachment`, `state/git-status` | Usage summaries, effort levels per model, image sniffing/persistence, and Git status labels. | +| `theme/logo` | CrewCoder logo text (big block wordmark, compact, mini) used by both UIs' home screens. Plain strings; each UI colors and draws them itself. | + +```ts +import { CrewCoderProcessBridge } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/crewcoder-process"; +import { applyCrewCoderEvent } from "@onpoint-dev-tools/crewcoder-tui-core/state/event-reducer"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; +``` + +## Agent resolution + +The bridge runs, in order: the SSH command when `CREWCODER_REMOTE` is set, then +`CREWCODER_BIN`, then a sibling `crewcoder-agent/dist/cli.js` (monorepo checkout or the +same npm scope directory), and finally `crewcoder` on `PATH`. + +## Contract + +The reducer and bridge are the TUI side of +[`TUI_BACKEND_CONTRACT.md`](../crewcoder-agent/docs/contributor/TUI_BACKEND_CONTRACT.md). +Rendering guardrails that both UIs must honor (thinking blocks, user-message +`background`, `message_end` replay handling, live approvals) are documented in +[`crewcoder-tui/AGENTS.md`](../crewcoder-tui/AGENTS.md#event-rendering-guardrails). +Changes here affect both UIs: run the core, legacy TUI, and OpenTUI test suites. + +```bash +npm test -w @onpoint-dev-tools/crewcoder-tui-core +npm test -w @onpoint-dev-tools/crewcoder-tui +mise exec node@26 -- npm test -w @onpoint-dev-tools/crewcoder-opentui +``` diff --git a/crewcoder-tui-core/package.json b/crewcoder-tui-core/package.json new file mode 100644 index 0000000..ef0ee7d --- /dev/null +++ b/crewcoder-tui-core/package.json @@ -0,0 +1,51 @@ +{ + "name": "@onpoint-dev-tools/crewcoder-tui-core", + "version": "0.1.0", + "private": false, + "description": "UI-independent CrewCoder terminal UI runtime: agent process bridge, JSON event parser, and transcript state reducer shared by CrewCoder TUIs.", + "license": "Apache-2.0", + "repository": { + "type": "git", + "url": "git+https://github.com/OnPoint-Dev-Tools/crewcoder.git", + "directory": "crewcoder-tui-core" + }, + "bugs": "https://github.com/OnPoint-Dev-Tools/crewcoder/issues", + "homepage": "https://github.com/OnPoint-Dev-Tools/crewcoder#readme", + "type": "module", + "files": [ + "dist", + "LICENSE", + "README.md" + ], + "engines": { + "node": ">=22.0.0" + }, + "exports": { + "./bridge/*": { + "types": "./dist/bridge/*.d.ts", + "default": "./dist/bridge/*.js" + }, + "./state/*": { + "types": "./dist/state/*.d.ts", + "default": "./dist/state/*.js" + }, + "./theme/*": { + "types": "./dist/theme/*.d.ts", + "default": "./dist/theme/*.js" + }, + "./package.json": "./package.json" + }, + "publishConfig": { + "access": "public", + "provenance": true + }, + "scripts": { + "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"", + "build": "tsc -p tsconfig.build.json", + "typecheck": "tsc -p tsconfig.json --noEmit", + "test": "vitest run" + }, + "dependencies": { + "zod": "^3.23.8" + } +} diff --git a/crewcoder-tui/src/bridge/crewcoder-process.ts b/crewcoder-tui-core/src/bridge/crewcoder-process.ts similarity index 100% rename from crewcoder-tui/src/bridge/crewcoder-process.ts rename to crewcoder-tui-core/src/bridge/crewcoder-process.ts diff --git a/crewcoder-tui/src/bridge/event-parser.ts b/crewcoder-tui-core/src/bridge/event-parser.ts similarity index 100% rename from crewcoder-tui/src/bridge/event-parser.ts rename to crewcoder-tui-core/src/bridge/event-parser.ts diff --git a/crewcoder-tui/src/bridge/live-ui-protocol.ts b/crewcoder-tui-core/src/bridge/live-ui-protocol.ts similarity index 100% rename from crewcoder-tui/src/bridge/live-ui-protocol.ts rename to crewcoder-tui-core/src/bridge/live-ui-protocol.ts diff --git a/crewcoder-tui/src/bridge/remote-connection.ts b/crewcoder-tui-core/src/bridge/remote-connection.ts similarity index 100% rename from crewcoder-tui/src/bridge/remote-connection.ts rename to crewcoder-tui-core/src/bridge/remote-connection.ts diff --git a/crewcoder-tui/src/state/effort-levels.ts b/crewcoder-tui-core/src/state/effort-levels.ts similarity index 100% rename from crewcoder-tui/src/state/effort-levels.ts rename to crewcoder-tui-core/src/state/effort-levels.ts diff --git a/crewcoder-tui/src/state/event-reducer.ts b/crewcoder-tui-core/src/state/event-reducer.ts similarity index 100% rename from crewcoder-tui/src/state/event-reducer.ts rename to crewcoder-tui-core/src/state/event-reducer.ts diff --git a/crewcoder-tui/src/state/git-status.ts b/crewcoder-tui-core/src/state/git-status.ts similarity index 100% rename from crewcoder-tui/src/state/git-status.ts rename to crewcoder-tui-core/src/state/git-status.ts diff --git a/crewcoder-tui/src/state/image-attachment.ts b/crewcoder-tui-core/src/state/image-attachment.ts similarity index 100% rename from crewcoder-tui/src/state/image-attachment.ts rename to crewcoder-tui-core/src/state/image-attachment.ts diff --git a/crewcoder-tui/src/state/tui-store.ts b/crewcoder-tui-core/src/state/tui-store.ts similarity index 100% rename from crewcoder-tui/src/state/tui-store.ts rename to crewcoder-tui-core/src/state/tui-store.ts diff --git a/crewcoder-tui/src/state/usage.ts b/crewcoder-tui-core/src/state/usage.ts similarity index 100% rename from crewcoder-tui/src/state/usage.ts rename to crewcoder-tui-core/src/state/usage.ts diff --git a/crewcoder-tui/src/tests/event-reducer.test.ts b/crewcoder-tui-core/src/tests/event-reducer.test.ts similarity index 100% rename from crewcoder-tui/src/tests/event-reducer.test.ts rename to crewcoder-tui-core/src/tests/event-reducer.test.ts diff --git a/crewcoder-tui/src/tests/image-attachment.test.ts b/crewcoder-tui-core/src/tests/image-attachment.test.ts similarity index 100% rename from crewcoder-tui/src/tests/image-attachment.test.ts rename to crewcoder-tui-core/src/tests/image-attachment.test.ts diff --git a/crewcoder-tui/src/tests/live-ui-protocol.test.ts b/crewcoder-tui-core/src/tests/live-ui-protocol.test.ts similarity index 100% rename from crewcoder-tui/src/tests/live-ui-protocol.test.ts rename to crewcoder-tui-core/src/tests/live-ui-protocol.test.ts diff --git a/crewcoder-tui/src/tests/remote-connection.test.ts b/crewcoder-tui-core/src/tests/remote-connection.test.ts similarity index 100% rename from crewcoder-tui/src/tests/remote-connection.test.ts rename to crewcoder-tui-core/src/tests/remote-connection.test.ts diff --git a/crewcoder-tui/src/tests/tui-store.test.ts b/crewcoder-tui-core/src/tests/tui-store.test.ts similarity index 100% rename from crewcoder-tui/src/tests/tui-store.test.ts rename to crewcoder-tui-core/src/tests/tui-store.test.ts diff --git a/crewcoder-tui/src/tests/usage.test.ts b/crewcoder-tui-core/src/tests/usage.test.ts similarity index 100% rename from crewcoder-tui/src/tests/usage.test.ts rename to crewcoder-tui-core/src/tests/usage.test.ts diff --git a/crewcoder-tui/src/theme/logo.ts b/crewcoder-tui-core/src/theme/logo.ts similarity index 100% rename from crewcoder-tui/src/theme/logo.ts rename to crewcoder-tui-core/src/theme/logo.ts diff --git a/crewcoder-tui-core/tsconfig.build.json b/crewcoder-tui-core/tsconfig.build.json new file mode 100644 index 0000000..7eb52de --- /dev/null +++ b/crewcoder-tui-core/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["src/tests/**"] +} diff --git a/crewcoder-tui-core/tsconfig.json b/crewcoder-tui-core/tsconfig.json new file mode 100644 index 0000000..677d4f4 --- /dev/null +++ b/crewcoder-tui-core/tsconfig.json @@ -0,0 +1,8 @@ +{ + "extends": "../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "dist" + }, + "include": ["src/**/*.ts"] +} diff --git a/crewcoder-tui-core/vitest.config.ts b/crewcoder-tui-core/vitest.config.ts new file mode 100644 index 0000000..f4df8cf --- /dev/null +++ b/crewcoder-tui-core/vitest.config.ts @@ -0,0 +1,9 @@ +import { defineConfig } from 'vitest/config'; + +export default defineConfig({ + test: { + pool: 'forks', + testTimeout: 10_000, + hookTimeout: 10_000, + }, +}); diff --git a/crewcoder-tui/AGENTS.md b/crewcoder-tui/AGENTS.md index d22e5bf..391088a 100644 --- a/crewcoder-tui/AGENTS.md +++ b/crewcoder-tui/AGENTS.md @@ -4,7 +4,18 @@ This package is `@onpoint-dev-tools/crewcoder-tui`. -It is the custom terminal UI for CrewCoder. +It is the **legacy** custom-renderer terminal UI for CrewCoder. The `crewcoder` umbrella +now launches `@onpoint-dev-tools/crewcoder-opentui`; this package stays published for +users who prefer it (`npm i -g @onpoint-dev-tools/crewcoder-tui`, then `crewcoder-tui`). +Keep it working; do not deprecate or delete it without the owner's decision. + +The agent process bridge, event parser, remote-connection quoting, Live UI protocol +types, reducer, `state/*` modules, and the logo text (`theme/logo`) live in `@onpoint-dev-tools/crewcoder-tui-core` +and are shared with the OpenTUI UI. Import them by subpath +(`@onpoint-dev-tools/crewcoder-tui-core/bridge/crewcoder-process`, +`.../state/event-reducer`, ...). Paths below such as `src/bridge/remote-connection.ts`, +`state/tui-store.ts`, and the event-reducer/image/usage tests now refer to that package. +Behavior changes there affect both UIs; run both suites. DISCLAIMER: crewcoder and crewcode are 2 different apps, CrewCoder harness has knowledge and plugin logic for crewcode, but everything else is for 'CrewCoder or crewcoder' dont get it confused, if you in doubt double check with me @@ -32,14 +43,11 @@ crewcoder-tui/ │ └── LIVE_UI_SANDBOX.md ├── src/ │ ├── cli.ts -│ ├── bridge/ -│ │ ├── crewcoder-process.ts -│ │ ├── event-parser.ts +│ ├── bridge/ # agent bridge, event parser, live-ui-protocol: crewcoder-tui-core │ │ ├── live-ui-controller.ts │ │ ├── live-ui-frame.ts │ │ ├── live-ui-gate.ts │ │ ├── live-ui-host.ts -│ │ ├── live-ui-protocol.ts │ │ ├── live-ui-registry.ts │ │ ├── live-ui-runtime.ts │ │ └── live-ui-trust-gate.ts @@ -60,11 +68,6 @@ crewcoder-tui/ │ │ ├── markdown-renderer.ts │ │ ├── modal-view.ts │ │ └── path-suggestions.ts -│ ├── state/ -│ │ ├── effort-levels.ts -│ │ ├── event-reducer.ts -│ │ ├── tui-store.ts -│ │ └── usage.ts │ ├── tests/ │ │ ├── app-home.test.ts │ │ ├── app-input.test.ts @@ -90,8 +93,7 @@ crewcoder-tui/ │ │ ├── spinner.test.ts │ │ ├── status-bar.test.ts │ │ └── theme.test.ts -│ ├── theme/ -│ │ ├── logo.ts +│ ├── theme/ # logo.ts lives in crewcoder-tui-core │ │ └── theme.ts │ └── tui/ │ ├── ansi.ts @@ -121,7 +123,7 @@ For user-facing rendering, prefer `ctx.theme` tokens over hardcoded hex colors s ## CLI launch -When both workspace packages are installed, bare `crewcoder` launches the `crewcoder-tui` binary. Keep the TUI's backend invocations argument-bearing (`crewcoder run`, `crewcoder session ...`) so they continue to target the agent CLI instead of reopening the TUI. +The scoped agent package's bare `crewcoder` launches the `crewcoder-tui` binary from `PATH`. The `crewcoder` umbrella's bare invocation launches `crewcoder-opentui` instead (see the root `AGENTS.md`). Keep the TUI's backend invocations argument-bearing (`crewcoder run`, `crewcoder session ...`) so they continue to target the agent CLI instead of reopening the TUI. ## Remote SSH agents diff --git a/crewcoder-tui/README.md b/crewcoder-tui/README.md index 833f7b9..2a92c16 100644 --- a/crewcoder-tui/README.md +++ b/crewcoder-tui/README.md @@ -1,6 +1,17 @@ -# CrewCoder TUI +# CrewCoder TUI (legacy) -CrewCoder TUI is a custom terminal UI package for CrewCoder. +CrewCoder TUI is the original custom terminal UI package for CrewCoder. The `crewcoder` +umbrella package now opens the [OpenTUI-based UI](../crewcoder-opentui/README.md); this +package remains published and maintained for users who prefer it, and it runs on +Node.js 22 or newer: + +```bash +npm install --global @onpoint-dev-tools/crewcoder-tui +crewcoder-tui +``` + +Its agent bridge, event reducer, and state live in the shared +[`@onpoint-dev-tools/crewcoder-tui-core`](../crewcoder-tui-core/README.md) package. Custom TUI architecture: diff --git a/crewcoder-tui/docs/CLI_LAUNCH.md b/crewcoder-tui/docs/CLI_LAUNCH.md index 86ea959..6703e02 100644 --- a/crewcoder-tui/docs/CLI_LAUNCH.md +++ b/crewcoder-tui/docs/CLI_LAUNCH.md @@ -1,6 +1,14 @@ # CLI launch -With both workspace packages installed or linked, launching CrewCoder without arguments opens the terminal UI: +There are two bare-launch routes: + +- The `crewcoder` **umbrella** package (`npm i -g crewcoder`) opens the OpenTUI UI, + `@onpoint-dev-tools/crewcoder-opentui`. It is an optional dependency that needs + Node.js >=26.4; when it is unavailable the umbrella prints guidance instead. See the + [installation guide](../../docs/INSTALLATION.md). +- The scoped **agent** package opens this legacy UI, as described below. + +With the scoped agent and this package installed or linked, launching CrewCoder without arguments opens the legacy terminal UI: ```bash crewcoder diff --git a/crewcoder-tui/package.json b/crewcoder-tui/package.json index 509e6be..1a09d9c 100644 --- a/crewcoder-tui/package.json +++ b/crewcoder-tui/package.json @@ -2,7 +2,7 @@ "name": "@onpoint-dev-tools/crewcoder-tui", "version": "0.6.4", "private": false, - "description": "CrewCoder custom terminal UI connected to crewcoder-agent with wired backend process bridge.", + "description": "Legacy CrewCoder terminal UI (custom renderer). The crewcoder umbrella now ships crewcoder-opentui; install this package directly to keep the legacy UI.", "license": "Apache-2.0", "repository": { "type": "git", @@ -26,13 +26,21 @@ }, "scripts": { "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"", + "predev": "npm run build -w @onpoint-dev-tools/crewcoder-tui-core", "dev": "tsx src/cli.ts", + "prebuild": "npm run build -w @onpoint-dev-tools/crewcoder-tui-core", "build": "tsc -p tsconfig.json", + "pretypecheck": "npm run build -w @onpoint-dev-tools/crewcoder-tui-core", "typecheck": "tsc -p tsconfig.json --noEmit", + "pretest": "npm run build -w @onpoint-dev-tools/crewcoder-tui-core", "test": "vitest run", "start": "node dist/cli.js" }, "dependencies": { + "@onpoint-dev-tools/crewcoder-tui-core": "0.1.0", "zod": "^3.23.8" + }, + "engines": { + "node": ">=22.0.0" } } diff --git a/crewcoder-tui/src/bridge/live-ui-controller.ts b/crewcoder-tui/src/bridge/live-ui-controller.ts index 384307c..1d65538 100644 --- a/crewcoder-tui/src/bridge/live-ui-controller.ts +++ b/crewcoder-tui/src/bridge/live-ui-controller.ts @@ -28,7 +28,7 @@ import type { CrewCoderLiveUiProps, CrewCoderLiveUiSurface, LiveUiFrame -} from "./live-ui-protocol.js"; +} from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; export type LiveUiMountRequest = { /** Registry key (typically a transcript block id or surface-scoped id). */ diff --git a/crewcoder-tui/src/bridge/live-ui-frame.ts b/crewcoder-tui/src/bridge/live-ui-frame.ts index bfc52d5..4343dc8 100644 --- a/crewcoder-tui/src/bridge/live-ui-frame.ts +++ b/crewcoder-tui/src/bridge/live-ui-frame.ts @@ -17,7 +17,7 @@ import { stripAnsi } from "../tui/ansi.js"; import { box, padRight, truncate } from "../tui/layout.js"; -import type { LiveUiFrame } from "./live-ui-protocol.js"; +import type { LiveUiFrame } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; export type LiveUiFrameTheme = { border: string; diff --git a/crewcoder-tui/src/bridge/live-ui-gate.ts b/crewcoder-tui/src/bridge/live-ui-gate.ts index e7f5ff4..d0e461b 100644 --- a/crewcoder-tui/src/bridge/live-ui-gate.ts +++ b/crewcoder-tui/src/bridge/live-ui-gate.ts @@ -22,7 +22,7 @@ import type { CrewCoderLiveUiPermissions, CrewCoderLiveUiProps, CrewCoderLiveUiSurface -} from "./live-ui-protocol.js"; +} from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; export const SUPPORTED_LIVE_UI_SURFACES: readonly CrewCoderLiveUiSurface[] = ["modal", "transcript", "status"]; diff --git a/crewcoder-tui/src/bridge/live-ui-host.ts b/crewcoder-tui/src/bridge/live-ui-host.ts index 9134687..aad004a 100644 --- a/crewcoder-tui/src/bridge/live-ui-host.ts +++ b/crewcoder-tui/src/bridge/live-ui-host.ts @@ -30,7 +30,7 @@ import { type CrewCoderLiveUiSurface, type CrewCoderLiveUiWorkerData, type LiveUiFrame -} from "./live-ui-protocol.js"; +} from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; export type LiveUiSpawnOptions = { /** Extension-relative-resolved absolute path to the built live UI entry module. */ diff --git a/crewcoder-tui/src/bridge/live-ui-registry.ts b/crewcoder-tui/src/bridge/live-ui-registry.ts index 02ad383..eb79d73 100644 --- a/crewcoder-tui/src/bridge/live-ui-registry.ts +++ b/crewcoder-tui/src/bridge/live-ui-registry.ts @@ -16,7 +16,7 @@ * `dispose()` can be tracked (which keeps this unit-testable with a fake host). */ -import type { CrewCoderLiveUiInstance, CrewCoderLiveUiSurface } from "./live-ui-protocol.js"; +import type { CrewCoderLiveUiInstance, CrewCoderLiveUiSurface } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; export type LiveUiDisposeReason = | "scroll_away" diff --git a/crewcoder-tui/src/bridge/live-ui-runtime.ts b/crewcoder-tui/src/bridge/live-ui-runtime.ts index f7d48ab..cd185ca 100644 --- a/crewcoder-tui/src/bridge/live-ui-runtime.ts +++ b/crewcoder-tui/src/bridge/live-ui-runtime.ts @@ -22,7 +22,7 @@ import { type CrewCoderLiveUiInstance, type CrewCoderLiveUiProps, type LiveUiFrame -} from "./live-ui-protocol.js"; +} from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; export type LiveUiComponentSize = { width: number; diff --git a/crewcoder-tui/src/bridge/live-ui-session-store.ts b/crewcoder-tui/src/bridge/live-ui-session-store.ts index 2feddc3..fb2424f 100644 --- a/crewcoder-tui/src/bridge/live-ui-session-store.ts +++ b/crewcoder-tui/src/bridge/live-ui-session-store.ts @@ -1,6 +1,6 @@ import fs from "node:fs"; import path from "node:path"; -import type { CrewCoderLiveUiJsonValue } from "./live-ui-protocol.js"; +import type { CrewCoderLiveUiJsonValue } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; export class LiveUiSessionStore { private readonly baseDir: string; diff --git a/crewcoder-tui/src/components/App.ts b/crewcoder-tui/src/components/App.ts index 52fd753..c9a4bcc 100644 --- a/crewcoder-tui/src/components/App.ts +++ b/crewcoder-tui/src/components/App.ts @@ -14,7 +14,7 @@ import { PickerOverlay, type PickerOption } from "./PickerOverlay.js"; import { ApprovalOverlay } from "./ApprovalOverlay.js"; import { ExtensionUiOverlay } from "./ExtensionUiOverlay.js"; import { CompactionPreviewOverlay, type CompactionPreviewParams } from "./CompactionPreviewOverlay.js"; -import { isTuiMode, normalizeTuiMode, pushSystemLog, TUI_MODES, type TuiDecisionExplanation, type TuiEventBlock, type TuiGoal, type TuiMode, type TuiReviewSummary, type TuiState } from "../state/tui-store.js"; +import { isTuiMode, normalizeTuiMode, pushSystemLog, TUI_MODES, type TuiDecisionExplanation, type TuiEventBlock, type TuiGoal, type TuiMode, type TuiReviewSummary, type TuiState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; const MODE_DESCRIPTIONS: Record = { general: "General coding agent mode", @@ -22,21 +22,21 @@ const MODE_DESCRIPTIONS: Record = { plugin: "CrewCode app plugin architect mode", extension: "CrewCoder extension architect mode" }; -import { branchCrewCoderSession, CrewCoderProcessBridge, execCrewCoderCommand, isCrewCoderRemote, listCrewCoderExtensionRenderers, listCrewCoderLiveUiContributions, listCrewCoderProviders, listCrewCoderSessions, type CrewCoderApprovalMode, type ProviderRecord, type SessionRecord } from "../bridge/crewcoder-process.js"; +import { branchCrewCoderSession, CrewCoderProcessBridge, execCrewCoderCommand, isCrewCoderRemote, listCrewCoderExtensionRenderers, listCrewCoderLiveUiContributions, listCrewCoderProviders, listCrewCoderSessions, type CrewCoderApprovalMode, type ProviderRecord, type SessionRecord } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/crewcoder-process"; import { LiveUiTrustGate } from "../bridge/live-ui-trust-gate.js"; import { LiveUiController, type LiveUiControllerCallbacks } from "../bridge/live-ui-controller.js"; import { LiveUiInstanceRegistry } from "../bridge/live-ui-registry.js"; import { LiveUiRepaintScheduler, type LiveUiFrameTheme } from "../bridge/live-ui-frame.js"; import { LiveUiSessionStore } from "../bridge/live-ui-session-store.js"; import { matchesTuiLiveUiContribution, prepareLiveUiSpawn, type LiveUiSpawnPlan, type TuiLiveUiContribution, type TuiLiveUiEvent, type TuiLiveUiGateContext } from "../bridge/live-ui-gate.js"; -import type { CrewCoderLiveUiInputEvent, CrewCoderLiveUiKind } from "../bridge/live-ui-protocol.js"; +import type { CrewCoderLiveUiInputEvent, CrewCoderLiveUiKind } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; import { readClipboard } from "../tui/clipboard.js"; -import { applyCrewCoderEvent } from "../state/event-reducer.js"; +import { applyCrewCoderEvent } from "@onpoint-dev-tools/crewcoder-tui-core/state/event-reducer"; import type { OverlayOptions } from "../tui/overlay.js"; import { bg, bold, fg, reset, stripAnsi, visibleLength } from "../tui/ansi.js"; -import { DEFAULT_EFFORT, effortLevelsForModel, normalizeEffort } from "../state/effort-levels.js"; +import { DEFAULT_EFFORT, effortLevelsForModel, normalizeEffort } from "@onpoint-dev-tools/crewcoder-tui-core/state/effort-levels"; import { listPathSuggestions } from "./path-suggestions.js"; -import { bigCrewCodeLogoLines, compactCrewCodeLogoLines } from "../theme/logo.js"; +import { bigCrewCodeLogoLines, compactCrewCodeLogoLines } from "@onpoint-dev-tools/crewcoder-tui-core/theme/logo"; import { pulseClock, renderBannerPulse } from "./logo-banner.js"; import { box, emptyLine, padRight } from "../tui/layout.js"; diff --git a/crewcoder-tui/src/components/ApprovalOverlay.ts b/crewcoder-tui/src/components/ApprovalOverlay.ts index dcf02fd..10f382e 100644 --- a/crewcoder-tui/src/components/ApprovalOverlay.ts +++ b/crewcoder-tui/src/components/ApprovalOverlay.ts @@ -1,5 +1,5 @@ import type { Component, KeyEvent, RenderContext } from "../tui/component.js"; -import type { TuiEventBlock } from "../state/tui-store.js"; +import type { TuiEventBlock } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { bg, bold, fg, reset } from "../tui/ansi.js"; import { emptyLine, padRight, truncate, wrapText } from "../tui/layout.js"; diff --git a/crewcoder-tui/src/components/Composer.ts b/crewcoder-tui/src/components/Composer.ts index 59592cb..aaa115a 100644 --- a/crewcoder-tui/src/components/Composer.ts +++ b/crewcoder-tui/src/components/Composer.ts @@ -1,10 +1,10 @@ import type { Component, KeyEvent, RenderContext } from "../tui/component.js"; -import type { TuiState } from "../state/tui-store.js"; +import type { TuiState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { bg, bold, fg, reset, visibleLength } from "../tui/ansi.js"; import { padRight, truncate } from "../tui/layout.js"; -import { formatContextStatus } from "../state/usage.js"; +import { formatContextStatus } from "@onpoint-dev-tools/crewcoder-tui-core/state/usage"; import { readClipboard, readClipboardImage, writeClipboard } from "../tui/clipboard.js"; -import { describeAttachment, persistImageBuffer, persistImageFile, sniffImage, type ImageAttachment } from "../state/image-attachment.js"; +import { describeAttachment, persistImageBuffer, persistImageFile, sniffImage, type ImageAttachment } from "@onpoint-dev-tools/crewcoder-tui-core/state/image-attachment"; import { toolHasExpandableOutput } from "./MainViewport.js"; export type SubmitHandler = (value: string) => void; diff --git a/crewcoder-tui/src/components/EffortOverlay.ts b/crewcoder-tui/src/components/EffortOverlay.ts index 5165bc6..6c5ef20 100644 --- a/crewcoder-tui/src/components/EffortOverlay.ts +++ b/crewcoder-tui/src/components/EffortOverlay.ts @@ -1,8 +1,8 @@ import type { Component, KeyEvent, RenderContext } from "../tui/component.js"; import { fg, reset } from "../tui/ansi.js"; import { emptyLine, padRight } from "../tui/layout.js"; -import type { EffortLevel } from "../state/effort-levels.js"; -import { effortLevelsForModel } from "../state/effort-levels.js"; +import type { EffortLevel } from "@onpoint-dev-tools/crewcoder-tui-core/state/effort-levels"; +import { effortLevelsForModel } from "@onpoint-dev-tools/crewcoder-tui-core/state/effort-levels"; export type EffortSelectHandler = (effort: EffortLevel) => void; diff --git a/crewcoder-tui/src/components/ExtensionUiOverlay.ts b/crewcoder-tui/src/components/ExtensionUiOverlay.ts index 21e9130..7a0f39f 100644 --- a/crewcoder-tui/src/components/ExtensionUiOverlay.ts +++ b/crewcoder-tui/src/components/ExtensionUiOverlay.ts @@ -1,5 +1,5 @@ import type { Component, KeyEvent, RenderContext } from "../tui/component.js"; -import type { TuiEventBlock } from "../state/tui-store.js"; +import type { TuiEventBlock } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { bg, bold, fg, reset, visibleLength } from "../tui/ansi.js"; import { emptyLine, padRight, truncate, wrapText } from "../tui/layout.js"; import { renderExtensionUiErrorBlock } from "./ExtensionUiErrorBlock.js"; diff --git a/crewcoder-tui/src/components/Header.ts b/crewcoder-tui/src/components/Header.ts index 32ac1f0..f7a3ebf 100644 --- a/crewcoder-tui/src/components/Header.ts +++ b/crewcoder-tui/src/components/Header.ts @@ -1,8 +1,8 @@ import type { Component, RenderContext } from "../tui/component.js"; -import type { TuiState } from "../state/tui-store.js"; +import type { TuiState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { bold, fg, reset, visibleLength } from "../tui/ansi.js"; import { padRight, truncate } from "../tui/layout.js"; -import { compactCrewCodeLogoLines, miniCrewCodeLogoLines } from "../theme/logo.js"; +import { compactCrewCodeLogoLines, miniCrewCodeLogoLines } from "@onpoint-dev-tools/crewcoder-tui-core/theme/logo"; export class Header implements Component { constructor(_state?: TuiState) {} diff --git a/crewcoder-tui/src/components/MainViewport.ts b/crewcoder-tui/src/components/MainViewport.ts index f88e1a7..2ce2b03 100644 --- a/crewcoder-tui/src/components/MainViewport.ts +++ b/crewcoder-tui/src/components/MainViewport.ts @@ -1,14 +1,14 @@ import { stripVTControlCharacters } from "node:util"; import type { Component, KeyEvent, RenderContext, RenderedImagePlacement } from "../tui/component.js"; -import type { TuiDeclarativeComponent, TuiEventBlock } from "../state/tui-store.js"; -import type { TuiState } from "../state/tui-store.js"; +import type { TuiDeclarativeComponent, TuiEventBlock } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; +import type { TuiState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { bg, bold, fg, italic, reset, stripAnsi, visibleLength } from "../tui/ansi.js"; import { writeClipboard } from "../tui/clipboard.js"; import { emptyLine, padRight, splitLines, truncate, wrapText } from "../tui/layout.js"; import { spinnerFrame, renderSpinner } from "./Spinner.js"; import { renderMarkdown } from "./markdown-renderer.js"; import { renderExtensionUiErrorBlock } from "./ExtensionUiErrorBlock.js"; -import { describeAttachment } from "../state/image-attachment.js"; +import { describeAttachment } from "@onpoint-dev-tools/crewcoder-tui-core/state/image-attachment"; import { detectImageProtocol, fitPlacement } from "../tui/image-protocol.js"; const TEXT_PADDING = 2; diff --git a/crewcoder-tui/src/components/RightSidebar.ts b/crewcoder-tui/src/components/RightSidebar.ts index 8c3ccd0..92cf6d1 100644 --- a/crewcoder-tui/src/components/RightSidebar.ts +++ b/crewcoder-tui/src/components/RightSidebar.ts @@ -1,5 +1,5 @@ import type { Component, RenderContext } from "../tui/component.js"; -import type { TuiCrewWorker, TuiState } from "../state/tui-store.js"; +import type { TuiCrewWorker, TuiState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { bg, bold, fg, reset } from "../tui/ansi.js"; import { horizontalRule, padRight, truncate, wrapText } from "../tui/layout.js"; import { spinnerFrame } from "./Spinner.js"; diff --git a/crewcoder-tui/src/components/SessionsOverlay.ts b/crewcoder-tui/src/components/SessionsOverlay.ts index 4eb37f2..f5ff366 100644 --- a/crewcoder-tui/src/components/SessionsOverlay.ts +++ b/crewcoder-tui/src/components/SessionsOverlay.ts @@ -1,5 +1,5 @@ import type { Component, KeyEvent, RenderContext } from "../tui/component.js"; -import { listCrewCoderSessions, type SessionRecord } from "../bridge/crewcoder-process.js"; +import { listCrewCoderSessions, type SessionRecord } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/crewcoder-process"; import type { ModalRow } from "./modal-view.js"; import { modalChromeHeight, modalRowAt, renderModalView } from "./modal-view.js"; diff --git a/crewcoder-tui/src/components/StatusBar.ts b/crewcoder-tui/src/components/StatusBar.ts index ac8d3d3..8d37705 100644 --- a/crewcoder-tui/src/components/StatusBar.ts +++ b/crewcoder-tui/src/components/StatusBar.ts @@ -1,6 +1,6 @@ import type { Component, RenderContext } from "../tui/component.js"; -import type { TuiState } from "../state/tui-store.js"; -import type { CrewCoderLiveUiPermissions } from "../bridge/live-ui-protocol.js"; +import type { TuiState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; +import type { CrewCoderLiveUiPermissions } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; import { bold, fg, reset } from "../tui/ansi.js"; import { padRight, truncate } from "../tui/layout.js"; diff --git a/crewcoder-tui/src/components/TaskWidget.ts b/crewcoder-tui/src/components/TaskWidget.ts index b3c47ce..f9693c9 100644 --- a/crewcoder-tui/src/components/TaskWidget.ts +++ b/crewcoder-tui/src/components/TaskWidget.ts @@ -2,7 +2,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import type { Component, RenderContext } from "../tui/component.js"; -import type { TuiState } from "../state/tui-store.js"; +import type { TuiState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { bold, fg, reset, strikethrough } from "../tui/ansi.js"; import { padRight, truncate, wrapText } from "../tui/layout.js"; diff --git a/crewcoder-tui/src/tests/app-home.test.ts b/crewcoder-tui/src/tests/app-home.test.ts index 82c48ed..9ab4761 100644 --- a/crewcoder-tui/src/tests/app-home.test.ts +++ b/crewcoder-tui/src/tests/app-home.test.ts @@ -5,10 +5,10 @@ import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { App } from "../components/App.js"; import { RightSidebar } from "../components/RightSidebar.js"; -import { readGitLabel } from "../state/git-status.js"; -import { createInitialState } from "../state/tui-store.js"; +import { readGitLabel } from "@onpoint-dev-tools/crewcoder-tui-core/state/git-status"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { crewCoderTheme } from "../theme/theme.js"; -import { bigCrewCodeLogoLines } from "../theme/logo.js"; +import { bigCrewCodeLogoLines } from "@onpoint-dev-tools/crewcoder-tui-core/theme/logo"; import { bg, fg, reset, stripAnsi } from "../tui/ansi.js"; const SIZE = { width: 100, height: 32 }; diff --git a/crewcoder-tui/src/tests/app-input.test.ts b/crewcoder-tui/src/tests/app-input.test.ts index df96e06..f0bd58f 100644 --- a/crewcoder-tui/src/tests/app-input.test.ts +++ b/crewcoder-tui/src/tests/app-input.test.ts @@ -3,7 +3,7 @@ import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { App } from "../components/App.js"; -import { createInitialState } from "../state/tui-store.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { parseInputEvents } from "../tui/input.js"; import { stripAnsi } from "../tui/ansi.js"; import { crewCoderTheme } from "../theme/theme.js"; diff --git a/crewcoder-tui/src/tests/app-live-ui.test.ts b/crewcoder-tui/src/tests/app-live-ui.test.ts index a82a575..966e8a6 100644 --- a/crewcoder-tui/src/tests/app-live-ui.test.ts +++ b/crewcoder-tui/src/tests/app-live-ui.test.ts @@ -1,11 +1,11 @@ import { describe, expect, it } from "vitest"; import { App } from "../components/App.js"; -import { createInitialState } from "../state/tui-store.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { LiveUiHost, type LiveUiHostCallbacks, type LiveUiSpawnOptions, type LiveUiWorkerLike } from "../bridge/live-ui-host.js"; import { crewCoderTheme } from "../theme/theme.js"; import { stripAnsi } from "../tui/ansi.js"; -import type { SessionRecord } from "../bridge/crewcoder-process.js"; -import type { CrewCoderLiveUiHost, LiveUiFrame } from "../bridge/live-ui-protocol.js"; +import type { SessionRecord } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/crewcoder-process"; +import type { CrewCoderLiveUiHost, LiveUiFrame } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; function host(): CrewCoderLiveUiHost { return { diff --git a/crewcoder-tui/src/tests/app-why.test.ts b/crewcoder-tui/src/tests/app-why.test.ts index 16894c3..45c05b2 100644 --- a/crewcoder-tui/src/tests/app-why.test.ts +++ b/crewcoder-tui/src/tests/app-why.test.ts @@ -4,7 +4,7 @@ import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { App } from "../components/App.js"; import { MainViewport } from "../components/MainViewport.js"; -import { createInitialState } from "../state/tui-store.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { crewCoderTheme } from "../theme/theme.js"; import { parseInputEvents } from "../tui/input.js"; import { stripAnsi } from "../tui/ansi.js"; diff --git a/crewcoder-tui/src/tests/checkpoint-settings.test.ts b/crewcoder-tui/src/tests/checkpoint-settings.test.ts index effa92c..e77a82b 100644 --- a/crewcoder-tui/src/tests/checkpoint-settings.test.ts +++ b/crewcoder-tui/src/tests/checkpoint-settings.test.ts @@ -4,8 +4,8 @@ import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { App } from "../components/App.js"; import { commandOptions } from "../components/CommandPalette.js"; -import { applyCrewCoderEvent } from "../state/event-reducer.js"; -import { createInitialState } from "../state/tui-store.js"; +import { applyCrewCoderEvent } from "@onpoint-dev-tools/crewcoder-tui-core/state/event-reducer"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { parseInputEvents } from "../tui/input.js"; const originalCrewCoderBin = process.env.CREWCODER_BIN; diff --git a/crewcoder-tui/src/tests/composer-history.test.ts b/crewcoder-tui/src/tests/composer-history.test.ts index 3abcf9c..49637c6 100644 --- a/crewcoder-tui/src/tests/composer-history.test.ts +++ b/crewcoder-tui/src/tests/composer-history.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { Composer } from "../components/Composer.js"; -import { createInitialState } from "../state/tui-store.js"; -import type { TuiState } from "../state/tui-store.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; +import type { TuiState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import type { KeyEvent } from "../tui/component.js"; function key(name: string, overrides: Partial = {}): KeyEvent { diff --git a/crewcoder-tui/src/tests/composer.test.ts b/crewcoder-tui/src/tests/composer.test.ts index f05649b..cee82fe 100644 --- a/crewcoder-tui/src/tests/composer.test.ts +++ b/crewcoder-tui/src/tests/composer.test.ts @@ -3,7 +3,7 @@ import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; import { Composer } from "../components/Composer.js"; -import { createInitialState } from "../state/tui-store.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { crewCoderTheme } from "../theme/theme.js"; import { bg, fg, reset, stripAnsi } from "../tui/ansi.js"; diff --git a/crewcoder-tui/src/tests/diff-viewer.test.ts b/crewcoder-tui/src/tests/diff-viewer.test.ts index 9a7e420..74370f2 100644 --- a/crewcoder-tui/src/tests/diff-viewer.test.ts +++ b/crewcoder-tui/src/tests/diff-viewer.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { MainViewport } from "../components/MainViewport.js"; -import { createInitialState } from "../state/tui-store.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { bg, stripAnsi } from "../tui/ansi.js"; import { crewCoderTheme } from "../theme/theme.js"; diff --git a/crewcoder-tui/src/tests/extension-ui-overlay.test.ts b/crewcoder-tui/src/tests/extension-ui-overlay.test.ts index 4b44397..4fbfe0e 100644 --- a/crewcoder-tui/src/tests/extension-ui-overlay.test.ts +++ b/crewcoder-tui/src/tests/extension-ui-overlay.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { ExtensionUiOverlay } from "../components/ExtensionUiOverlay.js"; -import type { TuiEventBlock } from "../state/tui-store.js"; +import type { TuiEventBlock } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { crewCoderTheme } from "../theme/theme.js"; import { stripAnsi } from "../tui/ansi.js"; import type { KeyEvent } from "../tui/component.js"; diff --git a/crewcoder-tui/src/tests/goal-command.test.ts b/crewcoder-tui/src/tests/goal-command.test.ts index 9182452..f4f7fba 100644 --- a/crewcoder-tui/src/tests/goal-command.test.ts +++ b/crewcoder-tui/src/tests/goal-command.test.ts @@ -4,7 +4,7 @@ import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { App, parseGoalStartInput, tokenizeGoalCommand } from "../components/App.js"; import { GoalOverlay } from "../components/GoalOverlay.js"; -import { createInitialState } from "../state/tui-store.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; const originalBin = process.env.CREWCODER_BIN; diff --git a/crewcoder-tui/src/tests/header.test.ts b/crewcoder-tui/src/tests/header.test.ts index 896dc2b..f6c34e9 100644 --- a/crewcoder-tui/src/tests/header.test.ts +++ b/crewcoder-tui/src/tests/header.test.ts @@ -1,9 +1,9 @@ import { describe, expect, it } from "vitest"; import { Header } from "../components/Header.js"; -import { compactCrewCodeLogoLines, miniCrewCodeLogoLines } from "../theme/logo.js"; +import { compactCrewCodeLogoLines, miniCrewCodeLogoLines } from "@onpoint-dev-tools/crewcoder-tui-core/theme/logo"; import { crewCoderTheme } from "../theme/theme.js"; import { stripAnsi } from "../tui/ansi.js"; -import { createInitialState } from "../state/tui-store.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; describe("Header", () => { it("renders standalone header branding without session status", () => { diff --git a/crewcoder-tui/src/tests/image-wiring.test.ts b/crewcoder-tui/src/tests/image-wiring.test.ts index 8d135bb..817162f 100644 --- a/crewcoder-tui/src/tests/image-wiring.test.ts +++ b/crewcoder-tui/src/tests/image-wiring.test.ts @@ -2,8 +2,8 @@ import { describe, expect, it } from "vitest"; import { App } from "../components/App.js"; import { Composer } from "../components/Composer.js"; import { MainViewport } from "../components/MainViewport.js"; -import { createInitialState } from "../state/tui-store.js"; -import type { ImageAttachment } from "../state/image-attachment.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; +import type { ImageAttachment } from "@onpoint-dev-tools/crewcoder-tui-core/state/image-attachment"; import { crewCoderTheme } from "../theme/theme.js"; import { stripAnsi } from "../tui/ansi.js"; import type { RenderedImagePlacement } from "../tui/component.js"; diff --git a/crewcoder-tui/src/tests/live-ui-controller.test.ts b/crewcoder-tui/src/tests/live-ui-controller.test.ts index a4bd444..aede098 100644 --- a/crewcoder-tui/src/tests/live-ui-controller.test.ts +++ b/crewcoder-tui/src/tests/live-ui-controller.test.ts @@ -6,7 +6,7 @@ import { LiveUiRepaintScheduler } from "../bridge/live-ui-frame.js"; import { LiveUiHost } from "../bridge/live-ui-host.js"; import { stripAnsi } from "../tui/ansi.js"; import type { LiveUiWorkerLike, LiveUiWorkerSpec } from "../bridge/live-ui-host.js"; -import type { CrewCoderLiveUiHost, CrewCoderLiveUiInstance, CrewCoderLiveUiProps, LiveUiFrame } from "../bridge/live-ui-protocol.js"; +import type { CrewCoderLiveUiHost, CrewCoderLiveUiInstance, CrewCoderLiveUiProps, LiveUiFrame } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; const theme = { border: "#18372c", focusBorder: "#285a48", title: "#cccccc", text: "#ffffff" }; diff --git a/crewcoder-tui/src/tests/live-ui-frame.test.ts b/crewcoder-tui/src/tests/live-ui-frame.test.ts index 6b7f8fe..399e104 100644 --- a/crewcoder-tui/src/tests/live-ui-frame.test.ts +++ b/crewcoder-tui/src/tests/live-ui-frame.test.ts @@ -8,7 +8,7 @@ import { type LiveUiFrameStyle } from "../bridge/live-ui-frame.js"; import { stripAnsi, visibleLength } from "../tui/ansi.js"; -import type { LiveUiFrame } from "../bridge/live-ui-protocol.js"; +import type { LiveUiFrame } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; const theme = { border: "#18372c", focusBorder: "#285a48", title: "#cccccc", text: "#ffffff" }; diff --git a/crewcoder-tui/src/tests/live-ui-host.test.ts b/crewcoder-tui/src/tests/live-ui-host.test.ts index b4f219a..9499464 100644 --- a/crewcoder-tui/src/tests/live-ui-host.test.ts +++ b/crewcoder-tui/src/tests/live-ui-host.test.ts @@ -10,7 +10,7 @@ import { type LiveUiWorkerLike, type LiveUiWorkerSpec } from "../bridge/live-ui-host.js"; -import type { CrewCoderLiveUiHost, CrewCoderLiveUiInstance, CrewCoderLiveUiProps, LiveUiFrame } from "../bridge/live-ui-protocol.js"; +import type { CrewCoderLiveUiHost, CrewCoderLiveUiInstance, CrewCoderLiveUiProps, LiveUiFrame } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; class FakeWorker implements LiveUiWorkerLike { posted: unknown[] = []; diff --git a/crewcoder-tui/src/tests/live-ui-registry.test.ts b/crewcoder-tui/src/tests/live-ui-registry.test.ts index a8eb271..15fc849 100644 --- a/crewcoder-tui/src/tests/live-ui-registry.test.ts +++ b/crewcoder-tui/src/tests/live-ui-registry.test.ts @@ -4,7 +4,7 @@ import { type LiveUiDisposeReason, type LiveUiTrackable } from "../bridge/live-ui-registry.js"; -import type { CrewCoderLiveUiSurface } from "../bridge/live-ui-protocol.js"; +import type { CrewCoderLiveUiSurface } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; function makeTrackable(overrides: Partial = {}): LiveUiTrackable & { disposed: number } { const surface: CrewCoderLiveUiSurface = overrides.surface ?? "modal"; diff --git a/crewcoder-tui/src/tests/live-ui-runtime.test.ts b/crewcoder-tui/src/tests/live-ui-runtime.test.ts index 7f8a805..a34665a 100644 --- a/crewcoder-tui/src/tests/live-ui-runtime.test.ts +++ b/crewcoder-tui/src/tests/live-ui-runtime.test.ts @@ -4,7 +4,7 @@ import { reduceLiveUiChild, type LiveUiComponent } from "../bridge/live-ui-runtime.js"; -import type { CrewCoderLiveUiHost, CrewCoderLiveUiProps, LiveUiFrame } from "../bridge/live-ui-protocol.js"; +import type { CrewCoderLiveUiHost, CrewCoderLiveUiProps, LiveUiFrame } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; const props: CrewCoderLiveUiProps = { extensionId: "review-pack", diff --git a/crewcoder-tui/src/tests/live-ui-trust-gate.test.ts b/crewcoder-tui/src/tests/live-ui-trust-gate.test.ts index 9b36748..7688dd3 100644 --- a/crewcoder-tui/src/tests/live-ui-trust-gate.test.ts +++ b/crewcoder-tui/src/tests/live-ui-trust-gate.test.ts @@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest"; import { LiveUiTrustGate } from "../bridge/live-ui-trust-gate.js"; import { LiveUiHost } from "../bridge/live-ui-host.js"; import type { LiveUiSpawnOptions, LiveUiWorkerLike, LiveUiWorkerSpec } from "../bridge/live-ui-host.js"; -import type { CrewCoderLiveUiHost, CrewCoderLiveUiProps } from "../bridge/live-ui-protocol.js"; +import type { CrewCoderLiveUiHost, CrewCoderLiveUiProps } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/live-ui-protocol"; function props(): CrewCoderLiveUiProps { return { extensionId: "review-pack", contributionId: "review-panel", surface: "modal", event: { type: "x" } }; diff --git a/crewcoder-tui/src/tests/main-viewport.test.ts b/crewcoder-tui/src/tests/main-viewport.test.ts index 7c56585..ed2a1f4 100644 --- a/crewcoder-tui/src/tests/main-viewport.test.ts +++ b/crewcoder-tui/src/tests/main-viewport.test.ts @@ -2,9 +2,9 @@ import { describe, expect, it } from "vitest"; import { Header } from "../components/Header.js"; import { firstLiveBlockIndex, MainViewport } from "../components/MainViewport.js"; import { SPINNER_FRAMES } from "../components/Spinner.js"; -import { createInitialState } from "../state/tui-store.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { bg, bold, fg, italic, stripAnsi } from "../tui/ansi.js"; -import { compactCrewCodeLogoLines, miniCrewCodeLogoLines } from "../theme/logo.js"; +import { compactCrewCodeLogoLines, miniCrewCodeLogoLines } from "@onpoint-dev-tools/crewcoder-tui-core/theme/logo"; import { crewCoderTheme, lightCrewCoderTheme } from "../theme/theme.js"; describe("Header", () => { diff --git a/crewcoder-tui/src/tests/picker-overlay.test.ts b/crewcoder-tui/src/tests/picker-overlay.test.ts index 863d190..a3d942f 100644 --- a/crewcoder-tui/src/tests/picker-overlay.test.ts +++ b/crewcoder-tui/src/tests/picker-overlay.test.ts @@ -6,7 +6,7 @@ import { padRight, truncate } from "../tui/layout.js"; const listCrewCoderSessions = vi.fn(); -vi.mock("../bridge/crewcoder-process.js", () => ({ +vi.mock("@onpoint-dev-tools/crewcoder-tui-core/bridge/crewcoder-process", () => ({ listCrewCoderSessions })); diff --git a/crewcoder-tui/src/tests/provider-defaults.test.ts b/crewcoder-tui/src/tests/provider-defaults.test.ts index 6f937be..8dcae37 100644 --- a/crewcoder-tui/src/tests/provider-defaults.test.ts +++ b/crewcoder-tui/src/tests/provider-defaults.test.ts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { builtinProviderDefaults, resolveProviderRecord } from "../components/App.js"; -import { createInitialState } from "../state/tui-store.js"; -import { effortLevelsForModel } from "../state/effort-levels.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; +import { effortLevelsForModel } from "@onpoint-dev-tools/crewcoder-tui-core/state/effort-levels"; afterEach(() => vi.unstubAllEnvs()); diff --git a/crewcoder-tui/src/tests/remote-status-bar.test.ts b/crewcoder-tui/src/tests/remote-status-bar.test.ts index f6d1f24..02bd4d0 100644 --- a/crewcoder-tui/src/tests/remote-status-bar.test.ts +++ b/crewcoder-tui/src/tests/remote-status-bar.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { RightSidebar } from "../components/RightSidebar.js"; -import { createInitialState } from "../state/tui-store.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { stripAnsi } from "../tui/ansi.js"; import { crewCoderTheme } from "../theme/theme.js"; diff --git a/crewcoder-tui/src/tests/right-sidebar.test.ts b/crewcoder-tui/src/tests/right-sidebar.test.ts index c6c0774..18c4a1a 100644 --- a/crewcoder-tui/src/tests/right-sidebar.test.ts +++ b/crewcoder-tui/src/tests/right-sidebar.test.ts @@ -3,8 +3,8 @@ import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { RightSidebar } from "../components/RightSidebar.js"; -import { applyCrewCoderEvent } from "../state/event-reducer.js"; -import { createInitialState } from "../state/tui-store.js"; +import { applyCrewCoderEvent } from "@onpoint-dev-tools/crewcoder-tui-core/state/event-reducer"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { stripAnsi } from "../tui/ansi.js"; import { crewCoderTheme } from "../theme/theme.js"; diff --git a/crewcoder-tui/src/tests/sessions-overlay.test.ts b/crewcoder-tui/src/tests/sessions-overlay.test.ts index 9de2d60..7479788 100644 --- a/crewcoder-tui/src/tests/sessions-overlay.test.ts +++ b/crewcoder-tui/src/tests/sessions-overlay.test.ts @@ -5,7 +5,7 @@ import { crewCoderTheme } from "../theme/theme.js"; const listCrewCoderSessions = vi.fn(); -vi.mock("../bridge/crewcoder-process.js", () => ({ +vi.mock("@onpoint-dev-tools/crewcoder-tui-core/bridge/crewcoder-process", () => ({ listCrewCoderSessions })); diff --git a/crewcoder-tui/src/tests/set-budget.test.ts b/crewcoder-tui/src/tests/set-budget.test.ts index 9552214..9f77ec9 100644 --- a/crewcoder-tui/src/tests/set-budget.test.ts +++ b/crewcoder-tui/src/tests/set-budget.test.ts @@ -1,7 +1,7 @@ import { describe, expect, it } from "vitest"; import { App, formatBudgetTokens, parseBudgetInput } from "../components/App.js"; import { commandOptions } from "../components/CommandPalette.js"; -import { createInitialState } from "../state/tui-store.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { parseInputEvents } from "../tui/input.js"; type RunOptions = { budget?: number }; diff --git a/crewcoder-tui/src/tests/status-bar.test.ts b/crewcoder-tui/src/tests/status-bar.test.ts index 1b3ddc9..bbf3257 100644 --- a/crewcoder-tui/src/tests/status-bar.test.ts +++ b/crewcoder-tui/src/tests/status-bar.test.ts @@ -4,8 +4,8 @@ import os from "node:os"; import path from "node:path"; import { describe, expect, it } from "vitest"; import { StatusBar } from "../components/StatusBar.js"; -import { readGitLabel } from "../state/git-status.js"; -import { createInitialState } from "../state/tui-store.js"; +import { readGitLabel } from "@onpoint-dev-tools/crewcoder-tui-core/state/git-status"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { stripAnsi } from "../tui/ansi.js"; import { crewCoderTheme } from "../theme/theme.js"; diff --git a/crewcoder-tui/src/tests/tool-image-results.test.ts b/crewcoder-tui/src/tests/tool-image-results.test.ts index 5cc61bf..c0c5e9c 100644 --- a/crewcoder-tui/src/tests/tool-image-results.test.ts +++ b/crewcoder-tui/src/tests/tool-image-results.test.ts @@ -2,9 +2,9 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { attachmentFromToolImage, toolImageAttachments } from "../state/image-attachment.js"; -import { applyCrewCoderEvent } from "../state/event-reducer.js"; -import { createInitialState, type TuiState } from "../state/tui-store.js"; +import { attachmentFromToolImage, toolImageAttachments } from "@onpoint-dev-tools/crewcoder-tui-core/state/image-attachment"; +import { applyCrewCoderEvent } from "@onpoint-dev-tools/crewcoder-tui-core/state/event-reducer"; +import { createInitialState, type TuiState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { MainViewport } from "../components/MainViewport.js"; import { crewCoderTheme } from "../theme/theme.js"; import { stripAnsi } from "../tui/ansi.js"; diff --git a/crewcoder-tui/src/tests/transcript-containment.test.ts b/crewcoder-tui/src/tests/transcript-containment.test.ts index f4f3f45..f9cef2a 100644 --- a/crewcoder-tui/src/tests/transcript-containment.test.ts +++ b/crewcoder-tui/src/tests/transcript-containment.test.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from "vitest"; import { MainViewport } from "../components/MainViewport.js"; -import { createInitialState } from "../state/tui-store.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { stripAnsi } from "../tui/ansi.js"; import { padRight, splitLines } from "../tui/layout.js"; import { crewCoderTheme } from "../theme/theme.js"; diff --git a/crewcoder-tui/src/tests/worker-identity-command.test.ts b/crewcoder-tui/src/tests/worker-identity-command.test.ts index 072189d..ce5db8b 100644 --- a/crewcoder-tui/src/tests/worker-identity-command.test.ts +++ b/crewcoder-tui/src/tests/worker-identity-command.test.ts @@ -1,9 +1,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import * as bridge from "../bridge/crewcoder-process.js"; +import * as bridge from "@onpoint-dev-tools/crewcoder-tui-core/bridge/crewcoder-process"; import { App } from "../components/App.js"; import { Composer } from "../components/Composer.js"; import { builtinPaletteItems } from "../components/CommandPalette.js"; -import { createInitialState } from "../state/tui-store.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { parseInputEvents } from "../tui/input.js"; import { stripAnsi } from "../tui/ansi.js"; import { crewCoderTheme } from "../theme/theme.js"; diff --git a/crewcoder-tui/src/tui/component.ts b/crewcoder-tui/src/tui/component.ts index 613b146..5f6553f 100644 --- a/crewcoder-tui/src/tui/component.ts +++ b/crewcoder-tui/src/tui/component.ts @@ -1,5 +1,5 @@ import type { CrewCoderTheme } from "../theme/theme.js"; -import type { ImageAttachment } from "../state/image-attachment.js"; +import type { ImageAttachment } from "@onpoint-dev-tools/crewcoder-tui-core/state/image-attachment"; import type { ImagePlacement, ImageProtocol } from "./image-protocol.js"; export type Size = { width: number; height: number }; diff --git a/crewcoder-tui/src/tui/tui.ts b/crewcoder-tui/src/tui/tui.ts index dc0fbec..5fafbc9 100644 --- a/crewcoder-tui/src/tui/tui.ts +++ b/crewcoder-tui/src/tui/tui.ts @@ -1,11 +1,11 @@ import { App } from "../components/App.js"; -import { readGitLabel } from "../state/git-status.js"; -import { createInitialState } from "../state/tui-store.js"; +import { readGitLabel } from "@onpoint-dev-tools/crewcoder-tui-core/state/git-status"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { loadCrewCoderTheme } from "../theme/theme.js"; import { InputRouter } from "./input.js"; import { OverlayManager } from "./overlay.js"; import { Renderer } from "./renderer.js"; -import { readCrewCoderRemoteConnection } from "../bridge/remote-connection.js"; +import { readCrewCoderRemoteConnection } from "@onpoint-dev-tools/crewcoder-tui-core/bridge/remote-connection"; export class CrewCoderTui { private readonly state: ReturnType; diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md index 4bfe21e..9a05845 100644 --- a/docs/INSTALLATION.md +++ b/docs/INSTALLATION.md @@ -1,9 +1,17 @@ # Installing CrewCoder -The unscoped `crewcoder` npm package is the supported umbrella launcher. It declares both runtime packages as dependencies: +The unscoped `crewcoder` npm package is the supported umbrella launcher. It declares: -- `@onpoint-dev-tools/crewcoder-agent` -- `@onpoint-dev-tools/crewcoder-tui` +- `@onpoint-dev-tools/crewcoder-agent` as a required dependency (Node.js 22+). +- `@onpoint-dev-tools/crewcoder-opentui`, the OpenTUI terminal UI (preview), as an + **optional** dependency. It needs Node.js 26.4+ and an OpenTUI native build for the + platform (Linux x64/arm64 glibc or musl, macOS x64/arm64, Windows x64/arm64). npm + skips it when it cannot be installed, so headless servers and sandboxes still get a + working agent. + +The original terminal UI is published separately as the legacy +`@onpoint-dev-tools/crewcoder-tui` package (Node.js 22+) and is no longer part of the +umbrella. ## Try without a persistent install @@ -11,7 +19,7 @@ The unscoped `crewcoder` npm package is the supported umbrella launcher. It decl npx crewcoder ``` -npm downloads the umbrella package and both runtime dependencies into its cache, then opens the TUI. This does not create a persistent global installation. +npm downloads the umbrella package and its dependencies into its cache, then opens the TUI. This does not create a persistent global installation. Arguments are forwarded to the agent CLI: @@ -42,7 +50,25 @@ npm install --global crewcoder@latest crew ``` -Node.js 22 or newer is required. +Node.js 22 or newer is required; the terminal UI additionally needs Node.js 26.4 or newer. + +## When bare `crewcoder` does not open the TUI + +A bare `crewcoder` exits with status 1 and a short explanation instead of starting the +UI when: + +- stdin or stdout is not an interactive terminal (CI, pipes, `ssh host crewcoder`); +- `@onpoint-dev-tools/crewcoder-opentui` is not installed (npm skipped the optional + dependency); or +- the running Node.js is older than the UI's `engines.node` floor (`>=26.4.0`). + +Agent commands with arguments are unaffected. To keep a terminal UI on Node.js 22, +install the legacy UI: + +```sh +npm install --global @onpoint-dev-tools/crewcoder-tui +crewcoder-tui +``` ## Update a global installation @@ -58,10 +84,10 @@ For CI, scripts, or another non-interactive terminal, skip the prompt explicitly crewcoder update --yes ``` -The update installs the public umbrella package with `npm install --global crewcoder@latest`; that umbrella pins the corresponding CrewCoder agent and TUI packages. If no newer stable release exists, the command prints `current version is up to date` and does not run npm install. A prompt without a TTY fails closed and tells the caller to use `--yes`. +The update installs the public umbrella package with `npm install --global crewcoder@latest`; that umbrella pins the corresponding CrewCoder agent and OpenTUI packages. If no newer stable release exists, the command prints `current version is up to date` and does not run npm install. A prompt without a TTY fails closed and tells the caller to use `--yes`. Running `npm install --global crewcoder@latest` directly also updates an existing global install, but it does not provide CrewCoder's version preview and confirmation. ## Scoped packages -The scoped packages remain independently installable for embedding, packaging, or development workflows. Most CLI users should install the `crewcoder` umbrella instead of installing the agent and TUI separately. +The scoped packages remain independently installable for embedding, packaging, or development workflows. Most CLI users should install the `crewcoder` umbrella instead of installing the agent and a TUI separately. diff --git a/docs/RELEASING.md b/docs/RELEASING.md index f4110c9..ae8f06a 100644 --- a/docs/RELEASING.md +++ b/docs/RELEASING.md @@ -6,7 +6,7 @@ Create a coordinated release from a clean branch with one command: npm run release -- 0.7.0 ``` -The Codex provider uses the user's installed Codex CLI. The command updates the umbrella, agent, browser client, and SDK package versions as one coordinated release group. It preserves the TUI package version and the umbrella package's existing exact TUI dependency. It also updates the release group's exact internal dependencies, runtime version constants, generated client and SDK version API baselines, and `package-lock.json`; runs the SDK release checks; creates a `chore(release): v0.7.0` commit and annotated `v0.7.0` tag; then atomically pushes the current branch and tag to its configured remote. +The Codex provider uses the user's installed Codex CLI. The command updates the umbrella, agent, browser client, and SDK package versions as one coordinated release group. It preserves the independent `crewcoder-tui-core`, legacy `crewcoder-tui`, and `crewcoder-opentui` versions and the umbrella's existing exact `crewcoder-opentui` optional dependency; bump those packages by hand when they change. The protected publish workflow publishes in dependency order: agent, TUI core, legacy TUI, OpenTUI, browser client, SDK, then the umbrella. It also updates the release group's exact internal dependencies, runtime version constants, generated client and SDK version API baselines, and `package-lock.json`; runs the SDK release checks; creates a `chore(release): v0.7.0` commit and annotated `v0.7.0` tag; then atomically pushes the current branch and tag to its configured remote. Only `crewcoder-client/api/version.d.ts` and `crewcoder-sdk/api/version.d.ts` may change during the automatic API baseline refresh. Any other public declaration change stops the release for explicit review. diff --git a/lib/launcher.js b/lib/launcher.js index 4d7fb5f..1f6e84b 100644 --- a/lib/launcher.js +++ b/lib/launcher.js @@ -1,43 +1,83 @@ import { spawn } from "node:child_process"; +import fs from "node:fs"; import path from "node:path"; import { createRequire } from "node:module"; const require = createRequire(import.meta.url); const AGENT_PACKAGE = "@onpoint-dev-tools/crewcoder-agent"; -const TUI_PACKAGE_JSON = "@onpoint-dev-tools/crewcoder-tui/package.json"; +const TUI_PACKAGE = "@onpoint-dev-tools/crewcoder-opentui"; +const LEGACY_TUI_PACKAGE = "@onpoint-dev-tools/crewcoder-tui"; +const HEADLESS_HINT = "Agent commands still work without it, for example `crewcoder run \"\"` (see `crewcoder --help`)."; +const LEGACY_HINT = `The legacy terminal UI runs on Node.js 22+: \`npm i -g ${LEGACY_TUI_PACKAGE}\`, then \`crewcoder-tui\`.`; + +/** + * @typedef {{ + * resolveModule?: (specifier: string) => string, + * readJson?: (filePath: string) => unknown, + * nodeVersion?: string, + * interactive?: boolean + * }} ResolveOptions + */ /** * Resolve the installed CLI that should handle this invocation. - * Bare `crewcoder` opens the TUI; argument-bearing calls use the agent CLI. + * Bare `crewcoder` opens the OpenTUI terminal UI; argument-bearing calls use the agent CLI. + * The TUI is an optional dependency, so a bare call fails with guidance instead of a stack + * trace when it is missing, the Node.js runtime is too old, or there is no terminal. * * @param {readonly string[]} args - * @param {(specifier: string) => string} [resolveModule] + * @param {ResolveOptions} [options] * @returns {string} */ -export function resolveCrewCoderCli(args, resolveModule = require.resolve) { - if (args.length === 0) { - const packageJsonPath = resolveModule(TUI_PACKAGE_JSON); - return path.join(path.dirname(packageJsonPath), "dist", "cli.js"); +export function resolveCrewCoderCli(args, options = {}) { + const { + resolveModule = require.resolve, + readJson = (filePath) => JSON.parse(fs.readFileSync(filePath, "utf8")), + nodeVersion = process.versions.node, + interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY) + } = options; + + if (args.length > 0) { + const agentEntryPath = resolveModule(AGENT_PACKAGE); + return path.join(path.dirname(agentEntryPath), "cli.js"); + } + + if (!interactive) { + throw new Error(`The terminal UI needs an interactive terminal. ${HEADLESS_HINT}`); + } + + let packageJsonPath; + try { + packageJsonPath = resolveModule(`${TUI_PACKAGE}/package.json`); + } catch { + throw new Error(`The terminal UI (${TUI_PACKAGE}) is not installed. It is optional and npm skips it on unsupported Node.js versions or platforms without an OpenTUI native build. ${LEGACY_HINT} ${HEADLESS_HINT}`); } - const agentEntryPath = resolveModule(AGENT_PACKAGE); - return path.join(path.dirname(agentEntryPath), "cli.js"); + const manifest = /** @type {{ engines?: { node?: unknown } }} */ (readJson(packageJsonPath)); + const required = typeof manifest?.engines?.node === "string" ? minimumVersion(manifest.engines.node) : undefined; + if (required && compareVersions(nodeVersion, required) < 0) { + throw new Error(`The terminal UI needs Node.js >=${required} (current ${nodeVersion}). Upgrade Node.js to use it. ${LEGACY_HINT} ${HEADLESS_HINT}`); + } + return path.join(path.dirname(packageJsonPath), "dist", "cli.js"); } /** * Run the selected CrewCoder package with inherited terminal I/O. * * @param {readonly string[]} args - * @param {{ spawnProcess?: typeof spawn, nodePath?: string, resolveModule?: (specifier: string) => string }} [options] + * @param {ResolveOptions & { spawnProcess?: typeof spawn, nodePath?: string }} [options] * @returns {Promise} */ export function runCrewCoder(args, options = {}) { const spawnProcess = options.spawnProcess ?? spawn; const nodePath = options.nodePath ?? process.execPath; - const cliPath = resolveCrewCoderCli(args, options.resolveModule); + const cliPath = resolveCrewCoderCli(args, options); + // OpenTUI loads its native layer through Node's experimental FFI; keep that + // runtime notice from printing above the TUI. Agent invocations are unchanged. + const nodeArgs = args.length === 0 ? ["--disable-warning=ExperimentalWarning"] : []; return new Promise((resolve, reject) => { - const child = spawnProcess(nodePath, [cliPath, ...args], { + const child = spawnProcess(nodePath, [...nodeArgs, cliPath, ...args], { stdio: "inherit", env: process.env }); @@ -47,3 +87,29 @@ export function runCrewCoder(args, options = {}) { }); }); } + +/** + * Extract the lower bound from a simple `>=x.y.z` engines range. Other range + * shapes return undefined so the launcher never blocks on a range it cannot read. + * + * @param {string} range + * @returns {string | undefined} + */ +export function minimumVersion(range) { + return /^\s*>=\s*v?(\d+\.\d+\.\d+)\s*$/.exec(range)?.[1]; +} + +/** + * @param {string} left + * @param {string} right + * @returns {number} + */ +function compareVersions(left, right) { + const leftParts = left.replace(/^v/, "").split(/[.-]/).slice(0, 3).map(Number); + const rightParts = right.split(".").map(Number); + for (let index = 0; index < 3; index += 1) { + const difference = (leftParts[index] || 0) - (rightParts[index] || 0); + if (difference !== 0) return difference; + } + return 0; +} diff --git a/package-lock.json b/package-lock.json index 18a8b65..cccb4f9 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,7 +13,6 @@ ], "dependencies": { "@onpoint-dev-tools/crewcoder-agent": "0.7.8", - "@onpoint-dev-tools/crewcoder-tui": "0.6.4", "typescript": "^5.7.2" }, "bin": { @@ -28,6 +27,9 @@ }, "engines": { "node": ">=22.0.0" + }, + "optionalDependencies": { + "@onpoint-dev-tools/crewcoder-opentui": "0.1.0" } }, "crewcoder-agent": { @@ -89,6 +91,27 @@ "version": "0.7.8", "license": "Apache-2.0" }, + "crewcoder-opentui": { + "name": "@onpoint-dev-tools/crewcoder-opentui", + "version": "0.1.0", + "license": "Apache-2.0", + "dependencies": { + "@onpoint-dev-tools/crewcoder-tui-core": "0.1.0", + "@opentui/core": "0.9.2", + "@opentui/react": "0.9.2", + "cli-spinners": "3.4.0", + "react": "^19.3.1" + }, + "bin": { + "crewcoder-opentui": "dist/cli.js" + }, + "devDependencies": { + "@types/react": "^19.3.0" + }, + "engines": { + "node": ">=26.4.0" + } + }, "crewcoder-sdk": { "name": "@onpoint-dev-tools/crewcoder-sdk", "version": "0.7.8", @@ -107,10 +130,25 @@ "version": "0.6.4", "license": "Apache-2.0", "dependencies": { + "@onpoint-dev-tools/crewcoder-tui-core": "0.1.0", "zod": "^3.23.8" }, "bin": { "crewcoder-tui": "dist/cli.js" + }, + "engines": { + "node": ">=22.0.0" + } + }, + "crewcoder-tui-core": { + "name": "@onpoint-dev-tools/crewcoder-tui-core", + "version": "0.1.0", + "license": "Apache-2.0", + "dependencies": { + "zod": "^3.23.8" + }, + "engines": { + "node": ">=22.0.0" } }, "node_modules/@agentclientprotocol/sdk": { @@ -769,6 +807,10 @@ "resolved": "crewcoder-client", "link": true }, + "node_modules/@onpoint-dev-tools/crewcoder-opentui": { + "resolved": "crewcoder-opentui", + "link": true + }, "node_modules/@onpoint-dev-tools/crewcoder-sdk": { "resolved": "crewcoder-sdk", "link": true @@ -777,6 +819,157 @@ "resolved": "crewcoder-tui", "link": true }, + "node_modules/@onpoint-dev-tools/crewcoder-tui-core": { + "resolved": "crewcoder-tui-core", + "link": true + }, + "node_modules/@opentui/core": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@opentui/core/-/core-0.9.2.tgz", + "integrity": "sha512-Wp0szaFvKET8TlcCO9C7AHgUnPY8qCTsj1im88jOAdX9InlYrerooWF9ez1QBrR/i6+6xhBf/iF/pch3d1xbeg==", + "license": "MIT", + "dependencies": { + "bun-ffi-structs": "0.3.1", + "diff": "9.0.0", + "string-width": "7.2.0" + }, + "engines": { + "bun": ">=1.3.14", + "node": ">=26.4.0" + }, + "optionalDependencies": { + "@opentui/core-darwin-arm64": "0.9.2", + "@opentui/core-darwin-x64": "0.9.2", + "@opentui/core-linux-arm64": "0.9.2", + "@opentui/core-linux-arm64-musl": "0.9.2", + "@opentui/core-linux-x64": "0.9.2", + "@opentui/core-linux-x64-musl": "0.9.2", + "@opentui/core-win32-arm64": "0.9.2", + "@opentui/core-win32-x64": "0.9.2" + }, + "peerDependencies": { + "web-tree-sitter": "0.25.10" + } + }, + "node_modules/@opentui/core-darwin-arm64": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@opentui/core-darwin-arm64/-/core-darwin-arm64-0.9.2.tgz", + "integrity": "sha512-6ASALGMPpmpsoGKYUpJYF+HJs1lZiw9zYsUhInCRYuVvBxYkBqV7MSz+1HFsTTd/ewqFuNnV/JMlEieMXZqiEA==", + "cpu": [ + "arm64" + ], + "license": "MIT AND LGPL-2.1-or-later", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@opentui/core-darwin-x64": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@opentui/core-darwin-x64/-/core-darwin-x64-0.9.2.tgz", + "integrity": "sha512-KWSEd1W0Gmx+EiixTc8YWbF3/htVFRPREeWV9BsT3Sag0SAwuZNJYhIixR+UGptggShUc4EiNofaAwEdDUG2IA==", + "cpu": [ + "x64" + ], + "license": "MIT AND LGPL-2.1-or-later", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@opentui/core-linux-arm64": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@opentui/core-linux-arm64/-/core-linux-arm64-0.9.2.tgz", + "integrity": "sha512-SKhb+H6F+iAz/Vb0avxxZYor1CIzVYhuMo21qN67xZ9XdqnvPaM5aHRU05rWOjU1U3pRlMslnf4DZZvyqfxjkQ==", + "cpu": [ + "arm64" + ], + "license": "MIT AND LGPL-2.1-or-later", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@opentui/core-linux-arm64-musl": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@opentui/core-linux-arm64-musl/-/core-linux-arm64-musl-0.9.2.tgz", + "integrity": "sha512-RZ8k4ShFV4N9nKCIeNos2NVi1a9dtWpO5HHk75ey8/a9JTiJUtGJhDgko73Hsw/CSqo0rj20yR4n532UuexTzg==", + "cpu": [ + "arm64" + ], + "license": "MIT AND LGPL-2.1-or-later", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@opentui/core-linux-x64": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@opentui/core-linux-x64/-/core-linux-x64-0.9.2.tgz", + "integrity": "sha512-5tEyEyYioX8owwsSJPTgvDdgMqjqOjOg6g8Bu5gSV9D9XKd5uRzhRC/zCQLubaVmK7oREmaXWJqT4tfIdVqeuw==", + "cpu": [ + "x64" + ], + "license": "MIT AND LGPL-2.1-or-later", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@opentui/core-linux-x64-musl": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@opentui/core-linux-x64-musl/-/core-linux-x64-musl-0.9.2.tgz", + "integrity": "sha512-23T5lMds4fckZxOiLs3INU6Sg5MmSes31li9Oh43bZixD03q0q7dlaD38RetK0RqUhrhlqyDdkcNpcRf9p0U2w==", + "cpu": [ + "x64" + ], + "license": "MIT AND LGPL-2.1-or-later", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@opentui/core-win32-arm64": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@opentui/core-win32-arm64/-/core-win32-arm64-0.9.2.tgz", + "integrity": "sha512-chqxvz7+SXdVLMva7vvfmOogLNn4t9LfeyvUrkc0QLiL4pJyKaR7KxnkI59ykd7A9PlMwzx+Jeb03l6J6kZhVA==", + "cpu": [ + "arm64" + ], + "license": "MIT AND LGPL-2.1-or-later", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@opentui/core-win32-x64": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@opentui/core-win32-x64/-/core-win32-x64-0.9.2.tgz", + "integrity": "sha512-1DlQEOwM8vOoipAJa/IA4VvtAzpQtbdSjZ9iLA0918HP24iZOAhSfjzH+KkEmRTtPECVL8mk7eFBENS6DtoEwQ==", + "cpu": [ + "x64" + ], + "license": "MIT AND LGPL-2.1-or-later", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@opentui/react": { + "version": "0.9.2", + "resolved": "https://registry.npmjs.org/@opentui/react/-/react-0.9.2.tgz", + "integrity": "sha512-BYhtxLFMBSkw1/LLRtjQbB7cuu31GRYtkAccvY2A51/zuHPaOJwEi6oUf/2MvjVuH+aivQcV4sCoEvKezzdozQ==", + "license": "MIT", + "dependencies": { + "@opentui/core": "0.9.2", + "react-reconciler": "^0.33.0" + }, + "peerDependencies": { + "react": ">=19.2.0", + "react-devtools-core": "^7.0.1", + "ws": "^8.18.0" + } + }, "node_modules/@rollup/rollup-android-arm-eabi": { "version": "4.61.1", "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.61.1.tgz", @@ -1172,6 +1365,16 @@ "undici-types": "~6.21.0" } }, + "node_modules/@types/react": { + "version": "19.3.0", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.3.0.tgz", + "integrity": "sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, "node_modules/@vitest/expect": { "version": "2.1.9", "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz", @@ -1334,6 +1537,18 @@ } } }, + "node_modules/ansi-regex": { + "version": "6.6.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.6.0.tgz", + "integrity": "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -1383,6 +1598,15 @@ "url": "https://opencollective.com/express" } }, + "node_modules/bun-ffi-structs": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/bun-ffi-structs/-/bun-ffi-structs-0.3.1.tgz", + "integrity": "sha512-3gM7PpVWLyrwxWjcilSiGuhWanhZivvo6l0u573NziPH6f/gwk6McbaYgn7oJWov6pKGRTDbrg94W5DcJsKTtQ==", + "license": "MIT", + "peerDependencies": { + "typescript": "^5" + } + }, "node_modules/bytes": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", @@ -1461,6 +1685,18 @@ "node": ">= 16" } }, + "node_modules/cli-spinners": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-3.4.0.tgz", + "integrity": "sha512-bXfOC4QcT1tKXGorxL3wbJm6XJPDqEnij2gQ2m7ESQuE+/z9YFIWnl/5RpTiKWbMq3EVKR4fRLJGn6DVfu0mpw==", + "license": "MIT", + "engines": { + "node": ">=18.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/commander": { "version": "12.1.0", "resolved": "https://registry.npmjs.org/commander/-/commander-12.1.0.tgz", @@ -1547,6 +1783,13 @@ "node": ">= 8" } }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -1584,6 +1827,15 @@ "node": ">= 0.8" } }, + "node_modules/diff": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-9.0.0.tgz", + "integrity": "sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.3.1" + } + }, "node_modules/dunder-proto": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", @@ -1606,6 +1858,12 @@ "license": "MIT", "peer": true }, + "node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "license": "MIT" + }, "node_modules/encodeurl": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", @@ -1934,6 +2192,18 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/get-east-asian-width": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/get-intrinsic": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", @@ -2473,6 +2743,63 @@ "node": ">= 0.10" } }, + "node_modules/react": { + "version": "19.3.1", + "resolved": "https://registry.npmjs.org/react/-/react-19.3.1.tgz", + "integrity": "sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-devtools-core": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/react-devtools-core/-/react-devtools-core-7.0.1.tgz", + "integrity": "sha512-C3yNvRHaizlpiASzy7b9vbnBGLrhvdhl1CbdU6EnZgxPNbai60szdLtl+VL76UNOt5bOoVTOz5rNWZxgGt+Gsw==", + "license": "MIT", + "peer": true, + "dependencies": { + "shell-quote": "^1.6.1", + "ws": "^7" + } + }, + "node_modules/react-devtools-core/node_modules/ws": { + "version": "7.5.14", + "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.14.tgz", + "integrity": "sha512-u9Oi2nQ8SZnTUAf6spLLKF5TyqoG3Nbbrd4ai6Sjo4P24bycDewhQqtNMIg4bFpnpH/TD4qk4IuAVhT0HIIqug==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=8.3.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": "^5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, + "node_modules/react-reconciler": { + "version": "0.33.0", + "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.33.0.tgz", + "integrity": "sha512-KetWRytFv1epdpJc3J4G75I4WrplZE5jOL7Yq0p34+OVOKF4Se7WrdIdVC45XsSSmUTlht2FM/fM1FZb1mfQeA==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.27.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "peerDependencies": { + "react": "^19.2.0" + } + }, "node_modules/require-from-string": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-2.0.2.tgz", @@ -2552,6 +2879,12 @@ "license": "MIT", "peer": true }, + "node_modules/scheduler": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", + "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", + "license": "MIT" + }, "node_modules/send": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/send/-/send-1.2.1.tgz", @@ -2629,6 +2962,19 @@ "node": ">=8" } }, + "node_modules/shell-quote": { + "version": "1.12.0", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.12.0.tgz", + "integrity": "sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/side-channel": { "version": "1.1.1", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.1.tgz", @@ -2757,6 +3103,38 @@ "dev": true, "license": "MIT" }, + "node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, "node_modules/tinybench": { "version": "2.9.0", "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz", @@ -3498,6 +3876,21 @@ } } }, + "node_modules/web-tree-sitter": { + "version": "0.25.10", + "resolved": "https://registry.npmjs.org/web-tree-sitter/-/web-tree-sitter-0.25.10.tgz", + "integrity": "sha512-Y09sF44/13XvgVKgO2cNDw5rGk6s26MgoZPXLESvMXeefBf7i6/73eFurre0IsTW6E14Y0ArIzhUMmjoc7xyzA==", + "license": "MIT", + "peer": true, + "peerDependencies": { + "@types/emscripten": "^1.40.0" + }, + "peerDependenciesMeta": { + "@types/emscripten": { + "optional": true + } + } + }, "node_modules/which": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", @@ -3538,6 +3931,28 @@ "license": "ISC", "peer": true }, + "node_modules/ws": { + "version": "8.23.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.23.0.tgz", + "integrity": "sha512-wCkmX8QMOrKjgO8HW2WyDbTSGeqkocxgDzS9iR79rEAexty6/2qzilx3Ag8Tqf9ykop3irLKle0MtVn5qjVnoQ==", + "license": "MIT", + "peer": true, + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/zod": { "version": "3.25.76", "resolved": "https://registry.npmjs.org/zod/-/zod-3.25.76.tgz", diff --git a/package.json b/package.json index 420b11d..dd26248 100644 --- a/package.json +++ b/package.json @@ -50,11 +50,12 @@ "dev:tui": "npm run dev -w @onpoint-dev-tools/crewcoder-tui", "start:agent": "npm run start -w @onpoint-dev-tools/crewcoder-agent", "start:tui": "npm run start -w @onpoint-dev-tools/crewcoder-tui", - "release:check:sdk": "node scripts/check-sdk-release.cjs && npm run release:check && npm run release:check -w @onpoint-dev-tools/crewcoder-agent && npm run release:check -w @onpoint-dev-tools/crewcoder-client && npm run release:check -w @onpoint-dev-tools/crewcoder-sdk" + "release:check:sdk": "node scripts/check-sdk-release.cjs && npm run release:check && npm run release:check -w @onpoint-dev-tools/crewcoder-agent && npm run release:check -w @onpoint-dev-tools/crewcoder-client && npm run release:check -w @onpoint-dev-tools/crewcoder-sdk", + "dev:opentui": "npm run dev -w @onpoint-dev-tools/crewcoder-opentui", + "start:opentui": "npm run start -w @onpoint-dev-tools/crewcoder-opentui" }, "dependencies": { "@onpoint-dev-tools/crewcoder-agent": "0.7.8", - "@onpoint-dev-tools/crewcoder-tui": "0.6.4", "typescript": "^5.7.2" }, "devDependencies": { @@ -65,5 +66,8 @@ }, "engines": { "node": ">=22.0.0" + }, + "optionalDependencies": { + "@onpoint-dev-tools/crewcoder-opentui": "0.1.0" } } diff --git a/scripts/check-crewcoder-package.cjs b/scripts/check-crewcoder-package.cjs index 340a432..8b88fb2 100644 --- a/scripts/check-crewcoder-package.cjs +++ b/scripts/check-crewcoder-package.cjs @@ -7,10 +7,13 @@ const root = path.resolve(__dirname, ".."); const manifest = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")); const requiredDependencies = [ "@onpoint-dev-tools/crewcoder-agent", - "@onpoint-dev-tools/crewcoder-tui", // The published agent currently imports the TypeScript compiler at runtime. "typescript" ]; +// The OpenTUI terminal UI needs Node.js >=26.4 and native binaries, so it stays +// optional: headless installs on VPSs and sandboxes must succeed without it. +const optionalTui = "@onpoint-dev-tools/crewcoder-opentui"; +const legacyTui = "@onpoint-dev-tools/crewcoder-tui"; for (const dependency of requiredDependencies) { if (typeof manifest.dependencies?.[dependency] !== "string") { @@ -18,6 +21,14 @@ for (const dependency of requiredDependencies) { process.exit(1); } } +if (typeof manifest.optionalDependencies?.[optionalTui] !== "string" || manifest.dependencies?.[optionalTui] !== undefined) { + console.error(`${optionalTui} must be an optionalDependency of the umbrella, not a required dependency.`); + process.exit(1); +} +if (manifest.dependencies?.[legacyTui] !== undefined || manifest.optionalDependencies?.[legacyTui] !== undefined) { + console.error(`${legacyTui} is published separately as the legacy UI and must not be an umbrella dependency.`); + process.exit(1); +} if (manifest.bin?.crewcoder !== "./bin/crewcoder.js" || manifest.bin?.crew !== "./bin/crewcoder.js" || manifest.bin?.cc !== undefined) { console.error("The crewcoder and crew bins must point to ./bin/crewcoder.js, and cc must remain available to the system compiler."); process.exit(1); diff --git a/scripts/check-sdk-release.cjs b/scripts/check-sdk-release.cjs index c2c7a08..a3e4e15 100644 --- a/scripts/check-sdk-release.cjs +++ b/scripts/check-sdk-release.cjs @@ -7,10 +7,14 @@ const agentPath = path.join(root, "crewcoder-agent", "package.json"); const sdkPath = path.join(root, "crewcoder-sdk", "package.json"); const clientPath = path.join(root, "crewcoder-client", "package.json"); const tuiPath = path.join(root, "crewcoder-tui", "package.json"); +const tuiCorePath = path.join(root, "crewcoder-tui-core", "package.json"); +const openTuiPath = path.join(root, "crewcoder-opentui", "package.json"); const agent = JSON.parse(fs.readFileSync(agentPath, "utf8")); const sdk = JSON.parse(fs.readFileSync(sdkPath, "utf8")); const client = JSON.parse(fs.readFileSync(clientPath, "utf8")); const tui = JSON.parse(fs.readFileSync(tuiPath, "utf8")); +const tuiCore = JSON.parse(fs.readFileSync(tuiCorePath, "utf8")); +const openTui = JSON.parse(fs.readFileSync(openTuiPath, "utf8")); const publishing = process.argv.includes("--publish"); const failures = []; const expectedRepositoryHost = "github.com/OnPoint-Dev-Tools/crewcoder"; @@ -24,14 +28,19 @@ function packageRepositoryUrl(manifest) { if (agent.version !== sdk.version || client.version !== sdk.version) failures.push(`Version mismatch: agent=${agent.version}, client=${client.version}, sdk=${sdk.version}`); if (sdk.dependencies?.[agent.name] !== agent.version) failures.push(`SDK dependency ${agent.name} must exactly match ${agent.version}.`); if (sdk.dependencies?.[client.name] !== client.version) failures.push(`SDK dependency ${client.name} must exactly match ${client.version}.`); -if (agent.license !== "Apache-2.0" || sdk.license !== "Apache-2.0" || client.license !== "Apache-2.0" || tui.license !== "Apache-2.0") failures.push("Agent, client, SDK, and TUI must declare Apache-2.0."); +if ([agent, sdk, client, tui, tuiCore, openTui].some((manifest) => manifest.license !== "Apache-2.0")) failures.push("Agent, client, SDK, TUI core, and both TUIs must declare Apache-2.0."); +for (const [label, manifest] of [["tui", tui], ["opentui", openTui]]) { + if (manifest.dependencies?.[tuiCore.name] !== tuiCore.version) failures.push(`${label} dependency ${tuiCore.name} must exactly match ${tuiCore.version}.`); +} +if (tuiCore.engines?.node !== ">=22.0.0" || tui.engines?.node !== ">=22.0.0") failures.push("TUI core and the legacy TUI must require Node.js >=22.0.0."); +if (openTui.engines?.node !== ">=26.4.0") failures.push("crewcoder-opentui must declare the Node.js >=26.4.0 floor that the umbrella launcher enforces."); if (agent.engines?.node !== ">=22.0.0" || sdk.engines?.node !== ">=22.0.0") failures.push("Agent and SDK must require Node.js >=22.0.0."); -for (const packageDirectory of ["crewcoder-agent", "crewcoder-client", "crewcoder-sdk", "crewcoder-tui"]) { +for (const packageDirectory of ["crewcoder-agent", "crewcoder-client", "crewcoder-sdk", "crewcoder-tui", "crewcoder-tui-core", "crewcoder-opentui"]) { for (const file of ["LICENSE", "README.md"]) { if (!fs.existsSync(path.join(root, packageDirectory, file))) failures.push(`${packageDirectory}/${file} is missing.`); } } -for (const [label, manifest] of [["agent", agent], ["client", client], ["sdk", sdk], ["tui", tui]]) { +for (const [label, manifest] of [["agent", agent], ["client", client], ["sdk", sdk], ["tui", tui], ["tui-core", tuiCore], ["opentui", openTui]]) { const repositoryUrl = packageRepositoryUrl(manifest); if (!repositoryUrl) failures.push(`${label} package.json repository.url is missing.`); else if (!repositoryUrl.includes(expectedRepositoryHost)) failures.push(`${label} repository.url must point at ${expectedRepositoryHost}.`); @@ -54,8 +63,9 @@ const clientFleetVersion = clientFleetSource.match(/CREWCODER_FLEET_PROTOCOL_VER if (!agentFleetVersion || agentFleetVersion !== clientFleetVersion) failures.push(`Fleet protocol version mismatch: agent=${agentFleetVersion ?? "missing"}, client=${clientFleetVersion ?? "missing"}.`); if (publishing) { - if (agent.private === true || sdk.private === true || client.private === true || tui.private === true) failures.push("Publishing is blocked while any package has private: true."); - if (!agent.repository || !sdk.repository || !client.repository || !tui.repository) failures.push("Publishing requires repository metadata in every package."); + const published = [agent, sdk, client, tui, tuiCore, openTui]; + if (published.some((manifest) => manifest.private === true)) failures.push("Publishing is blocked while any package has private: true."); + if (published.some((manifest) => !manifest.repository)) failures.push("Publishing requires repository metadata in every package."); } if (failures.length) { diff --git a/test/codex-progress-boundaries.test.ts b/test/codex-progress-boundaries.test.ts index 519d760..37882b0 100644 --- a/test/codex-progress-boundaries.test.ts +++ b/test/codex-progress-boundaries.test.ts @@ -2,8 +2,8 @@ import { expect, it } from "vitest"; import { CodexProgress } from "../crewcoder-agent/src/providers/codex-progress.js"; import { createJsonEventSink } from "../crewcoder-agent/src/core/json-event-stream.js"; import { translateEvent } from "../crewcoder-agent/src/acp/event-translator.js"; -import { applyCrewCoderEvent } from "../crewcoder-tui/src/state/event-reducer.js"; -import { createInitialState } from "../crewcoder-tui/src/state/tui-store.js"; +import { applyCrewCoderEvent } from "@onpoint-dev-tools/crewcoder-tui-core/state/event-reducer"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { MainViewport } from "../crewcoder-tui/src/components/MainViewport.js"; import { crewCoderTheme } from "../crewcoder-tui/src/theme/theme.js"; import { stripAnsi } from "../crewcoder-tui/src/tui/ansi.js"; diff --git a/test/codex-public-progress.test.ts b/test/codex-public-progress.test.ts index e029100..af70d0d 100644 --- a/test/codex-public-progress.test.ts +++ b/test/codex-public-progress.test.ts @@ -2,8 +2,8 @@ import { expect, it } from "vitest"; import { CodexProgress } from "../crewcoder-agent/src/providers/codex-progress.js"; import { createJsonEventSink } from "../crewcoder-agent/src/core/json-event-stream.js"; import { translateEvent } from "../crewcoder-agent/src/acp/event-translator.js"; -import { applyCrewCoderEvent } from "../crewcoder-tui/src/state/event-reducer.js"; -import { createInitialState } from "../crewcoder-tui/src/state/tui-store.js"; +import { applyCrewCoderEvent } from "@onpoint-dev-tools/crewcoder-tui-core/state/event-reducer"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; it("keeps full summary bodies and public commentary in terminal thinking, with final replies separate", async () => { const progress = new CodexProgress(); diff --git a/test/launcher.test.js b/test/launcher.test.js index ed3324e..ad015c1 100644 --- a/test/launcher.test.js +++ b/test/launcher.test.js @@ -1,25 +1,61 @@ import { EventEmitter } from "node:events"; import path from "node:path"; import { describe, expect, it, vi } from "vitest"; -import { resolveCrewCoderCli, runCrewCoder } from "../lib/launcher.js"; +import { minimumVersion, resolveCrewCoderCli, runCrewCoder } from "../lib/launcher.js"; const agentEntryPath = path.resolve("fixtures/crewcoder-agent/dist/index.js"); -const tuiPackageJsonPath = path.resolve("fixtures/crewcoder-tui/package.json"); -const resolveModule = (specifier) => specifier.endsWith("/package.json") ? tuiPackageJsonPath : agentEntryPath; +const tuiPackageJsonPath = path.resolve("fixtures/crewcoder-opentui/package.json"); +const resolveModule = (specifier) => { + if (specifier === "@onpoint-dev-tools/crewcoder-opentui/package.json") return tuiPackageJsonPath; + if (specifier === "@onpoint-dev-tools/crewcoder-agent") return agentEntryPath; + throw new Error(`Cannot find module '${specifier}'`); +}; +const readJson = () => ({ engines: { node: ">=26.4.0" } }); +const tty = { resolveModule, readJson, nodeVersion: "26.13.1", interactive: true }; describe("CrewCoder umbrella launcher", () => { - it("selects the TUI for a bare invocation", () => { - expect(resolveCrewCoderCli([], resolveModule)).toBe(path.resolve("fixtures/crewcoder-tui/dist/cli.js")); + it("selects the OpenTUI terminal UI for a bare interactive invocation", () => { + expect(resolveCrewCoderCli([], tty)).toBe(path.resolve("fixtures/crewcoder-opentui/dist/cli.js")); }); - it("selects the agent for argument-bearing commands", () => { - expect(resolveCrewCoderCli(["providers"], resolveModule)).toBe(path.resolve("fixtures/crewcoder-agent/dist/cli.js")); + it("selects the agent for argument-bearing commands without probing the TUI", () => { + const options = { ...tty, interactive: false, nodeVersion: "22.0.0", resolveModule: (specifier) => { + if (specifier.includes("opentui")) throw new Error("TUI must not be resolved"); + return resolveModule(specifier); + } }; + expect(resolveCrewCoderCli(["providers"], options)).toBe(path.resolve("fixtures/crewcoder-agent/dist/cli.js")); + }); + + it("explains the missing optional TUI and points at the legacy UI and agent commands", () => { + const options = { ...tty, resolveModule: (specifier) => { + if (specifier.includes("opentui")) throw new Error("Cannot find module"); + return resolveModule(specifier); + } }; + expect(() => resolveCrewCoderCli([], options)).toThrow(/crewcoder-opentui\) is not installed/); + expect(() => resolveCrewCoderCli([], options)).toThrow(/@onpoint-dev-tools\/crewcoder-tui/); + expect(() => resolveCrewCoderCli([], options)).toThrow(/crewcoder run/); + }); + + it("refuses to launch the TUI on a Node.js older than its engines floor", () => { + expect(() => resolveCrewCoderCli([], { ...tty, nodeVersion: "22.13.1" })).toThrow(/needs Node\.js >=26\.4\.0 \(current 22\.13\.1\)/); + expect(() => resolveCrewCoderCli([], { ...tty, nodeVersion: "26.3.9" })).toThrow(/needs Node\.js >=26\.4\.0/); + expect(resolveCrewCoderCli([], { ...tty, nodeVersion: "26.4.0" })).toContain("crewcoder-opentui"); + expect(resolveCrewCoderCli([], { ...tty, nodeVersion: "27.0.0-pre" })).toContain("crewcoder-opentui"); + }); + + it("does not open the TUI without an interactive terminal", () => { + expect(() => resolveCrewCoderCli([], { ...tty, interactive: false })).toThrow(/needs an interactive terminal/); + }); + + it("launches when the engines range is not a simple lower bound", () => { + expect(resolveCrewCoderCli([], { ...tty, nodeVersion: "20.0.0", readJson: () => ({ engines: { node: "^26 || ^27" } }) })).toContain("crewcoder-opentui"); + expect(resolveCrewCoderCli([], { ...tty, nodeVersion: "20.0.0", readJson: () => ({}) })).toContain("crewcoder-opentui"); }); it("forwards arguments and the child exit code", async () => { const child = new EventEmitter(); const spawnProcess = vi.fn(() => child); - const result = runCrewCoder(["run", "check this"], { spawnProcess, nodePath: "/node", resolveModule }); + const result = runCrewCoder(["run", "check this"], { ...tty, spawnProcess, nodePath: "/node" }); child.emit("close", 7, null); @@ -31,9 +67,24 @@ describe("CrewCoder umbrella launcher", () => { ); }); + it("silences only the FFI experimental notice when spawning the TUI", async () => { + const child = new EventEmitter(); + const spawnProcess = vi.fn(() => child); + const result = runCrewCoder([], { ...tty, spawnProcess, nodePath: "/node" }); + + child.emit("close", 0, null); + + await expect(result).resolves.toBe(0); + expect(spawnProcess).toHaveBeenCalledWith( + "/node", + ["--disable-warning=ExperimentalWarning", path.resolve("fixtures/crewcoder-opentui/dist/cli.js")], + { stdio: "inherit", env: process.env } + ); + }); + it("reports launcher failures", async () => { const child = new EventEmitter(); - const result = runCrewCoder(["--version"], { spawnProcess: () => child, resolveModule }); + const result = runCrewCoder(["--version"], { ...tty, spawnProcess: () => child }); const failure = new Error("spawn failed"); child.emit("error", failure); @@ -41,3 +92,12 @@ describe("CrewCoder umbrella launcher", () => { await expect(result).rejects.toBe(failure); }); }); + +describe("minimumVersion", () => { + it("reads simple lower-bound engines ranges only", () => { + expect(minimumVersion(">=26.4.0")).toBe("26.4.0"); + expect(minimumVersion(" >= v22.0.0 ")).toBe("22.0.0"); + expect(minimumVersion("^26.4.0")).toBeUndefined(); + expect(minimumVersion(">=26")).toBeUndefined(); + }); +}); diff --git a/test/release.test.js b/test/release.test.js index cc63710..1aad0a9 100644 --- a/test/release.test.js +++ b/test/release.test.js @@ -13,10 +13,12 @@ afterEach(() => { }); describe("release automation", () => { - it("commits version API baselines without including the independent TUI manifest", () => { + it("commits version API baselines without including the independent TUI manifests", () => { expect(releaseFiles).toContain("crewcoder-client/api/version.d.ts"); expect(releaseFiles).toContain("crewcoder-sdk/api/version.d.ts"); expect(releaseFiles).not.toContain("crewcoder-tui/package.json"); + expect(releaseFiles).not.toContain("crewcoder-tui-core/package.json"); + expect(releaseFiles).not.toContain("crewcoder-opentui/package.json"); }); it("accepts stable semantic versions and compares them numerically", () => { @@ -26,16 +28,18 @@ describe("release automation", () => { expect(() => stableVersionParts("0.2.3-beta.1")).toThrow(/stable semantic version/); }); - it("updates the coordinated release group while preserving the TUI version", () => { + it("updates the coordinated release group while preserving the TUI versions", () => { const repositoryRoot = fs.mkdtempSync(path.join(os.tmpdir(), "crewcoder-release-test-")); temporaryDirectories.push(repositoryRoot); const manifests = { - "package.json": { name: "crewcoder", version: "0.1.0", dependencies: { "@onpoint-dev-tools/crewcoder-agent": "0.1.0", "@onpoint-dev-tools/crewcoder-tui": "0.0.9" } }, + "package.json": { name: "crewcoder", version: "0.1.0", dependencies: { "@onpoint-dev-tools/crewcoder-agent": "0.1.0" }, optionalDependencies: { "@onpoint-dev-tools/crewcoder-opentui": "0.0.7" } }, "crewcoder-agent/package.json": { name: "@onpoint-dev-tools/crewcoder-agent", version: "0.1.0", dependencies: {} }, "crewcoder-client/package.json": { name: "@onpoint-dev-tools/crewcoder-client", version: "0.1.0" }, "crewcoder-sdk/package.json": { name: "@onpoint-dev-tools/crewcoder-sdk", version: "0.1.0", dependencies: { "@onpoint-dev-tools/crewcoder-agent": "0.1.0", "@onpoint-dev-tools/crewcoder-client": "0.1.0" } }, - "crewcoder-tui/package.json": { name: "@onpoint-dev-tools/crewcoder-tui", version: "0.0.9" } + "crewcoder-tui/package.json": { name: "@onpoint-dev-tools/crewcoder-tui", version: "0.0.9" }, + "crewcoder-opentui/package.json": { name: "@onpoint-dev-tools/crewcoder-opentui", version: "0.0.7" } }; + const independent = ["crewcoder-tui/package.json", "crewcoder-opentui/package.json"]; for (const [relativePath, manifest] of Object.entries(manifests)) { const filePath = path.join(repositoryRoot, relativePath); fs.mkdirSync(path.dirname(filePath), { recursive: true }); @@ -54,15 +58,14 @@ describe("release automation", () => { updateReleaseMetadata(repositoryRoot, "0.2.3"); - for (const relativePath of Object.keys(manifests).filter((relativePath) => relativePath !== "crewcoder-tui/package.json")) { + for (const relativePath of Object.keys(manifests).filter((relativePath) => !independent.includes(relativePath))) { expect(JSON.parse(fs.readFileSync(path.join(repositoryRoot, relativePath), "utf8")).version).toBe("0.2.3"); } expect(JSON.parse(fs.readFileSync(path.join(repositoryRoot, "crewcoder-tui/package.json"), "utf8")).version).toBe("0.0.9"); + expect(JSON.parse(fs.readFileSync(path.join(repositoryRoot, "crewcoder-opentui/package.json"), "utf8")).version).toBe("0.0.7"); const rootManifest = JSON.parse(fs.readFileSync(path.join(repositoryRoot, "package.json"), "utf8")); - expect(rootManifest.dependencies).toMatchObject({ - "@onpoint-dev-tools/crewcoder-agent": "0.2.3", - "@onpoint-dev-tools/crewcoder-tui": "0.0.9" - }); + expect(rootManifest.dependencies).toEqual({ "@onpoint-dev-tools/crewcoder-agent": "0.2.3" }); + expect(rootManifest.optionalDependencies).toEqual({ "@onpoint-dev-tools/crewcoder-opentui": "0.0.7" }); const sdkManifest = JSON.parse(fs.readFileSync(path.join(repositoryRoot, "crewcoder-sdk/package.json"), "utf8")); expect(sdkManifest.dependencies).toMatchObject({ "@onpoint-dev-tools/crewcoder-agent": "0.2.3", diff --git a/test/tool-mode-tui.test.ts b/test/tool-mode-tui.test.ts index b42dc77..4fa4f43 100644 --- a/test/tool-mode-tui.test.ts +++ b/test/tool-mode-tui.test.ts @@ -1,10 +1,10 @@ import fs from "node:fs"; import path from "node:path"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; -import * as bridge from "../crewcoder-tui/src/bridge/crewcoder-process.js"; +import * as bridge from "@onpoint-dev-tools/crewcoder-tui-core/bridge/crewcoder-process"; import { App } from "../crewcoder-tui/src/components/App.js"; import { builtinPaletteItems } from "../crewcoder-tui/src/components/CommandPalette.js"; -import { createInitialState } from "../crewcoder-tui/src/state/tui-store.js"; +import { createInitialState } from "@onpoint-dev-tools/crewcoder-tui-core/state/tui-store"; import { parseInputEvents } from "../crewcoder-tui/src/tui/input.js"; import { stripAnsi } from "../crewcoder-tui/src/tui/ansi.js"; import { crewCoderTheme } from "../crewcoder-tui/src/theme/theme.js"; diff --git a/tsconfig.json b/tsconfig.json index adddc81..cf9523c 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -10,6 +10,7 @@ "@onpoint-dev-tools/crewcoder-sdk/*": ["./crewcoder-sdk/src/*"], "@onpoint-dev-tools/crewcoder-client": ["./crewcoder-client/src/index.ts"], "@onpoint-dev-tools/crewcoder-client/*": ["./crewcoder-client/src/*"], + "@onpoint-dev-tools/crewcoder-tui-core/*": ["./crewcoder-tui-core/src/*"], "@onpoint-dev-tools/crewcoder-tui": ["./crewcoder-tui/src/cli.ts"], "@onpoint-dev-tools/crewcoder-tui/*": ["./crewcoder-tui/src/*"] } From f52780f683c357156d2ee5ced51ed519a9d94b99 Mon Sep 17 00:00:00 2001 From: OnPoint-Dev-Tools Date: Mon, 16 Nov 2026 22:29:48 -0500 Subject: [PATCH 02/25] feat: OpenTUI slash commands, pickers, multi-line composer, and alerts OpenTUI (crewcoder-opentui): - Slash command palette built on the termcn OpenTUI command palette, with grouped fuzzy search, scrolling, current-value markers, and exact footer sizing (fixes clipped palette and wrong-item selection with groups). - Every legacy picker: sessions, rewind, provider/model/effort, modes and workers, prompts, tool mode, profile, remove-dir, commands, skills, handoff. Picker commands also take a value directly (/effort high). - Remaining legacy commands: branch, compact (+ preview summary editor and auto on/off), export, goal, reload, clear, thinking, identity, full-access, checkpoints, memory, remember, set-budget, add-dir, extensions, plugins, review-summary, why, task, teams, team, approve, deny, approve-plan, follow-up, help. /crew skipped; /sidebar and /file-changes deferred. - Status, on/off, and text-output results show in a vendored termcn alert above the composer until the next key. - Multi-line composer on