Merge branch 'main' into org-config-selector
This commit is contained in:
commit
e3f0ec5d4d
43 changed files with 1320 additions and 846 deletions
|
|
@ -29,7 +29,7 @@ rules:
|
|||
|
||||
- readline-sync: Provides synchronous CLI user interactions
|
||||
|
||||
- Jest: Used for testing framework
|
||||
- Vitest: Used for testing framework
|
||||
|
||||
|
||||
All code should follow established patterns for a Node.js CLI tool
|
||||
|
|
|
|||
25
.github/workflows/continue-detailed-review.yaml
vendored
Normal file
25
.github/workflows/continue-detailed-review.yaml
vendored
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
name: Continue Detailed Review
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, ready_for_review]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
detailed-code-review:
|
||||
name: Continue Detailed Review
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Run Detailed PR Review
|
||||
uses: continuedev/continue/actions/detailed-review@5361d5e33b880add1d3d050eeadd01971434fb75
|
||||
with:
|
||||
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
|
||||
continue-org: continuedev
|
||||
continue-config: continuedev/review-bot
|
||||
25
.github/workflows/continue-general-review.yaml
vendored
Normal file
25
.github/workflows/continue-general-review.yaml
vendored
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
name: Continue General Review
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, ready_for_review]
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
general-code-review:
|
||||
name: Continue General Review
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Run Continue PR Review Action
|
||||
uses: continuedev/continue/actions/general-review@5361d5e33b880add1d3d050eeadd01971434fb75
|
||||
with:
|
||||
continue-api-key: ${{ secrets.CONTINUE_API_KEY }}
|
||||
continue-org: "continuedev"
|
||||
continue-config: "continuedev/review-bot"
|
||||
250
.github/workflows/continue-review.yaml
vendored
250
.github/workflows/continue-review.yaml
vendored
|
|
@ -1,250 +0,0 @@
|
|||
name: Continue CLI Code Review
|
||||
|
||||
on:
|
||||
workflow_call:
|
||||
inputs:
|
||||
assistant:
|
||||
description: "Assistant configuration to use"
|
||||
required: false
|
||||
default: "nate/default-assistant"
|
||||
type: string
|
||||
prompt:
|
||||
description: "Custom prompt to use instead of the default PR review"
|
||||
required: false
|
||||
type: string
|
||||
secrets:
|
||||
CONTINUE_API_KEY:
|
||||
required: true
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
assistant:
|
||||
description: "Assistant configuration to use"
|
||||
required: false
|
||||
default: "nate/default-assistant"
|
||||
type: string
|
||||
prompt:
|
||||
description: "Custom prompt to use instead of the default PR review"
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
code-review:
|
||||
name: AI Code Review
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # Fetch full history for better context
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20
|
||||
|
||||
- name: Install Continue CLI
|
||||
run: npm install -g @continuedev/cli
|
||||
|
||||
- name: Build PR diff prompt
|
||||
if: github.event_name == 'pull_request' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request')
|
||||
run: |
|
||||
# Get PR number - different methods depending on trigger
|
||||
if [ "${{ github.event_name }}" = "pull_request" ]; then
|
||||
PR_NUMBER="${{ github.event.number }}"
|
||||
else
|
||||
# For workflow_call triggered by PR, we need to get it from context
|
||||
PR_NUMBER=$(jq -r '.pull_request.number' "$GITHUB_EVENT_PATH" 2>/dev/null || echo "")
|
||||
fi
|
||||
|
||||
if [ -n "$PR_NUMBER" ] && [ "$PR_NUMBER" != "null" ]; then
|
||||
# Get PR diff using GitHub CLI
|
||||
gh pr diff $PR_NUMBER > pr_diff.txt
|
||||
|
||||
# Create comprehensive prompt
|
||||
cat > review_prompt.txt << 'EOF'
|
||||
You are conducting a code review for a pull request. Below is the git diff showing all the changes:
|
||||
|
||||
EOF
|
||||
|
||||
echo "--- PR DIFF START ---" >> review_prompt.txt
|
||||
cat pr_diff.txt >> review_prompt.txt
|
||||
echo "--- PR DIFF END ---" >> review_prompt.txt
|
||||
|
||||
cat >> review_prompt.txt << 'EOF'
|
||||
|
||||
Please analyze these changes and provide a comprehensive code review. Consider:
|
||||
|
||||
1. **Code Quality**: Are there any bugs, performance issues, or code smells?
|
||||
2. **Best Practices**: Does the code follow established patterns and conventions?
|
||||
3. **Security**: Are there any potential security vulnerabilities?
|
||||
4. **Testing**: Are appropriate tests included or updated?
|
||||
5. **Documentation**: Is documentation adequate for the changes?
|
||||
6. **Architecture**: Do the changes fit well with the existing codebase structure?
|
||||
|
||||
You can use the available tools to explore the codebase and understand context better.
|
||||
|
||||
Format your response as a markdown code review with the following structure:
|
||||
|
||||
## Code Review Summary
|
||||
|
||||
### Issues Found
|
||||
- [List any problems with severity levels]
|
||||
|
||||
### Suggestions
|
||||
- [List improvement recommendations]
|
||||
|
||||
### Overall Assessment
|
||||
[Provide overall recommendation: APPROVE, REQUEST_CHANGES, or COMMENT]
|
||||
|
||||
Only call the 'exit' tool if you find critical security vulnerabilities or bugs that would break production.
|
||||
EOF
|
||||
else
|
||||
echo "Could not determine PR number, using generic prompt"
|
||||
cat > review_prompt.txt << 'EOF'
|
||||
Please review the recent changes to this codebase and provide feedback on code quality, potential issues, and suggestions for improvement.
|
||||
|
||||
Format your response as a markdown code review.
|
||||
EOF
|
||||
fi
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
|
||||
- name: Build custom prompt
|
||||
if: inputs.prompt != ''
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
run: |
|
||||
# Get PR number for custom prompts too
|
||||
if [ "${{ github.event_name }}" = "pull_request" ]; then
|
||||
PR_NUMBER="${{ github.event.number }}"
|
||||
else
|
||||
# For workflow_call triggered by PR, we need to get it from context
|
||||
PR_NUMBER=$(jq -r '.pull_request.number' "$GITHUB_EVENT_PATH" 2>/dev/null || echo "")
|
||||
fi
|
||||
|
||||
if [ -n "$PR_NUMBER" ] && [ "$PR_NUMBER" != "null" ]; then
|
||||
# Get PR diff using GitHub CLI
|
||||
gh pr diff $PR_NUMBER > pr_diff.txt
|
||||
|
||||
# Create custom prompt with diff included
|
||||
echo "${{ inputs.prompt }}" > review_prompt.txt
|
||||
echo "" >> review_prompt.txt
|
||||
echo "Below is the git diff showing all the changes:" >> review_prompt.txt
|
||||
echo "" >> review_prompt.txt
|
||||
echo "--- PR DIFF START ---" >> review_prompt.txt
|
||||
cat pr_diff.txt >> review_prompt.txt
|
||||
echo "--- PR DIFF END ---" >> review_prompt.txt
|
||||
else
|
||||
echo "${{ inputs.prompt }}" > review_prompt.txt
|
||||
fi
|
||||
|
||||
- name: Build default prompt for non-PR triggers
|
||||
if: inputs.prompt == '' && github.event_name != 'pull_request' && (github.event_name != 'workflow_run' || github.event.workflow_run.event != 'pull_request')
|
||||
run: |
|
||||
cat > review_prompt.txt << 'EOF'
|
||||
Please review the recent changes to this codebase and provide feedback on code quality, potential issues, and suggestions for improvement. You do not need to acknowledge what was done well.
|
||||
|
||||
Format your response as a markdown code review with each comment having only a short description about the problem and suggested solution, each being separated by "\n\n---\n\n".
|
||||
|
||||
EOF
|
||||
|
||||
- name: Run Continue CLI Review
|
||||
run: |
|
||||
echo "Running Continue CLI with prompt:"
|
||||
echo "=================================="
|
||||
cat review_prompt.txt
|
||||
echo "=================================="
|
||||
echo ""
|
||||
|
||||
# Run the CLI with the generated prompt and pipe output to code_review.md
|
||||
cat review_prompt.txt | cn --auto --config "${{ inputs.assistant }}" -p > code_review.md
|
||||
env:
|
||||
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
|
||||
|
||||
- name: Upload Review Results
|
||||
uses: actions/upload-artifact@v4
|
||||
if: always()
|
||||
with:
|
||||
name: code-review-results
|
||||
path: |
|
||||
code_review.md
|
||||
review_prompt.txt
|
||||
pr_diff.txt
|
||||
retention-days: 30
|
||||
|
||||
- name: Comment PR with Review
|
||||
if: always() && (github.event_name == 'pull_request' || (github.event_name == 'workflow_run' && github.event.workflow_run.event == 'pull_request'))
|
||||
uses: actions/github-script@v7
|
||||
with:
|
||||
script: |
|
||||
const fs = require('fs');
|
||||
|
||||
try {
|
||||
let reviewContent = '';
|
||||
|
||||
if (fs.existsSync('code_review.md') && fs.statSync('code_review.md').size > 0) {
|
||||
reviewContent = fs.readFileSync('code_review.md', 'utf8');
|
||||
} else {
|
||||
reviewContent = '⚠️ AI review completed but no review output was generated. Check the action logs for details.';
|
||||
}
|
||||
|
||||
// Get PR number
|
||||
let prNumber;
|
||||
if (context.payload.pull_request) {
|
||||
prNumber = context.payload.pull_request.number;
|
||||
} else if (context.payload.workflow_run && context.payload.workflow_run.pull_requests && context.payload.workflow_run.pull_requests.length > 0) {
|
||||
prNumber = context.payload.workflow_run.pull_requests[0].number;
|
||||
}
|
||||
|
||||
if (!prNumber) {
|
||||
console.log('Could not determine PR number for commenting');
|
||||
return;
|
||||
}
|
||||
|
||||
// Unique identifier for our bot comments
|
||||
const botSignature = '<!-- continue-cli-review -->';
|
||||
const newComment = `${botSignature}\n${reviewContent}`;
|
||||
|
||||
// Get all comments on the PR
|
||||
const { data: comments } = await github.rest.issues.listComments({ per_page: 100,
|
||||
issue_number: prNumber,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
});
|
||||
|
||||
// Find existing Continue CLI review comment
|
||||
const existingComment = comments.find(comment =>
|
||||
comment.body.includes(botSignature)
|
||||
);
|
||||
|
||||
if (existingComment) {
|
||||
// Update existing comment
|
||||
await github.rest.issues.updateComment({
|
||||
comment_id: existingComment.id,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: newComment
|
||||
});
|
||||
console.log(`Successfully updated existing comment #${existingComment.id} on PR #${prNumber}`);
|
||||
} else {
|
||||
// Create new comment
|
||||
await github.rest.issues.createComment({
|
||||
issue_number: prNumber,
|
||||
owner: context.repo.owner,
|
||||
repo: context.repo.repo,
|
||||
body: newComment
|
||||
});
|
||||
console.log(`Successfully created new comment on PR #${prNumber}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.log('Failed to post/update comment:', error.message);
|
||||
console.log('Error details:', error);
|
||||
}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
12
.github/workflows/pr_checks.yml
vendored
12
.github/workflows/pr_checks.yml
vendored
|
|
@ -86,18 +86,6 @@ jobs:
|
|||
shell: bash
|
||||
run: npm test -- --exclude='**/*.e2e.*' --exclude='**/e2e/**'
|
||||
|
||||
review:
|
||||
uses: ./.github/workflows/continue-review.yaml
|
||||
secrets:
|
||||
CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }}
|
||||
with:
|
||||
prompt: |
|
||||
Please review the below changes for any mistakes. You can look around the codebase to investigate if needed. Look for:
|
||||
- React changes causing too many re-renders
|
||||
- Functions that are too long
|
||||
- Other potentially subtle bugs
|
||||
Keep your response concise and give a bullet pointed list of the findings, including suggested fixes for any problems you find.
|
||||
|
||||
# GitHub does not have a way of requiring that all checks pass (you must manually select each job)
|
||||
# This action at least lets us manage the list of required tests via source control
|
||||
# so that creators of new jobs can add them to this list
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ test
|
|||
.continue
|
||||
.releaserc.json
|
||||
AGENTS.md
|
||||
jest.config.mjs
|
||||
vitest.config.ts
|
||||
tsconfig.json
|
||||
tsconfig.build.json
|
||||
TESTING_STRATEGY.md
|
||||
|
|
|
|||
10
.vscode/launch.json
vendored
10
.vscode/launch.json
vendored
|
|
@ -24,16 +24,14 @@
|
|||
],
|
||||
"preLaunchTask": "watch-logs"
|
||||
},
|
||||
|
||||
{
|
||||
{
|
||||
"name": "Debug Tests",
|
||||
"type": "node",
|
||||
"request": "launch",
|
||||
"program": "${workspaceFolder}/node_modules/.bin/jest",
|
||||
"args": ["--runInBand", "--no-cache"],
|
||||
"program": "${workspaceFolder}/node_modules/.bin/vitest",
|
||||
"args": ["--run", "--no-cache"],
|
||||
"env": {
|
||||
"NODE_ENV": "test",
|
||||
"NODE_OPTIONS": "--experimental-vm-modules"
|
||||
"NODE_ENV": "test"
|
||||
},
|
||||
"console": "integratedTerminal",
|
||||
"internalConsoleOptions": "neverOpen",
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ This file provides guidance to AI coding agents when working with code in this r
|
|||
## Development Commands
|
||||
|
||||
- **Build**: `npm run build` - Compiles TypeScript to JavaScript in dist/
|
||||
- **Test**: `npm test` - Runs Jest tests with ESM support
|
||||
- **Test**: `npm test` - Runs Vitest tests with ESM support
|
||||
- **Type Check**: `npm run lint` - Runs TypeScript compiler without emitting files for type checking
|
||||
- **Format**: `npm run format` - Runs Prettier with --write flag to check + fix formatting
|
||||
- **Start**: `npm start` - Runs the built CLI from dist/index.js
|
||||
|
|
@ -54,8 +54,8 @@ This is a CLI tool for Continue Dev that provides an interactive AI-assisted dev
|
|||
|
||||
### Testing Setup
|
||||
|
||||
- Uses Jest with TypeScript and ESM support
|
||||
- Configuration in `jest.config.mjs`
|
||||
- Uses Vitest with TypeScript and ESM support
|
||||
- Configuration in `vitest.config.ts`
|
||||
- Tests should be written with `.test.ts` extension
|
||||
- No existing test files found - tests should be added when writing new functionality
|
||||
- Run tests using `npm run test path/or/pattern`
|
||||
|
|
|
|||
21
README.md
21
README.md
|
|
@ -29,6 +29,12 @@ The CLI automatically saves your chat history for each terminal session. You can
|
|||
```bash
|
||||
# Resume the last session in this terminal
|
||||
cn --resume
|
||||
|
||||
# List recent sessions and choose one to resume
|
||||
cn ls
|
||||
|
||||
# List sessions in JSON format (for scripting)
|
||||
cn ls --json
|
||||
```
|
||||
|
||||
## Command Line Options
|
||||
|
|
@ -37,3 +43,18 @@ cn --resume
|
|||
- `--config <path>`: Specify agent configuration path
|
||||
- `--resume`: Resume the last session for this terminal
|
||||
- `<prompt>`: Optional prompt to start with
|
||||
|
||||
## Commands
|
||||
|
||||
- `cn`: Start an interactive chat session
|
||||
- `cn ls`: List recent sessions with TUI selector to choose one to resume
|
||||
- `cn login`: Authenticate with Continue
|
||||
- `cn logout`: Sign out of current session
|
||||
- `cn remote`: Launch a remote instance
|
||||
- `cn serve`: Start HTTP server mode
|
||||
|
||||
### Session Listing (`cn ls`)
|
||||
|
||||
Shows recent sessions, limited by screen height to ensure it fits on your terminal.
|
||||
|
||||
- `--json`: Output in JSON format for scripting (always shows 10 sessions)
|
||||
|
|
|
|||
|
|
@ -178,7 +178,6 @@ export default [
|
|||
"coverage/**",
|
||||
"*.d.ts",
|
||||
"src/__mocks__/**",
|
||||
"jest.setup.ts",
|
||||
"vitest.config.ts",
|
||||
"*.config.js",
|
||||
"*.config.ts",
|
||||
|
|
|
|||
|
|
@ -1,78 +0,0 @@
|
|||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
export default {
|
||||
transform: {
|
||||
"\\.[jt]sx?$": ["ts-jest", { useESM: true }],
|
||||
},
|
||||
|
||||
moduleNameMapper: {
|
||||
"^(\\.{1,2}/.+)\\.js$": "$1",
|
||||
"^highlight\\.js/lib/languages/(.+)$":
|
||||
"<rootDir>/src/ui/__mocks__/highlightLanguage.js",
|
||||
"^lowlight$": "<rootDir>/src/ui/__mocks__/lowlight.js",
|
||||
"^ink-testing-library$":
|
||||
"<rootDir>/node_modules/ink-testing-library/build/index.js",
|
||||
"^./SyntaxHighlighter\\.js$":
|
||||
"<rootDir>/src/ui/__mocks__/SyntaxHighlighter.ts",
|
||||
"^./FreeTrialStatus\\.js$":
|
||||
"<rootDir>/src/ui/__mocks__/FreeTrialStatus.tsx",
|
||||
},
|
||||
extensionsToTreatAsEsm: [".ts", ".tsx"],
|
||||
preset: "ts-jest/presets/default-esm",
|
||||
testTimeout: 10000,
|
||||
testEnvironment: "node",
|
||||
testPathIgnorePatterns: ["<rootDir>/dist/"],
|
||||
modulePathIgnorePatterns: ["<rootDir>/dist/"],
|
||||
transformIgnorePatterns: ["node_modules/(?!(highlight.js|lowlight)/)"],
|
||||
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
|
||||
globals: {
|
||||
__dirname: path.dirname(fileURLToPath(import.meta.url)),
|
||||
__filename: path.resolve(fileURLToPath(import.meta.url)),
|
||||
},
|
||||
resolver: "<rootDir>/jest.resolver.cjs",
|
||||
// Force E2E tests to run sequentially to avoid console override conflicts
|
||||
projects: [
|
||||
{
|
||||
displayName: "e2e",
|
||||
testMatch: ["<rootDir>/src/e2e/**/*.test.ts"],
|
||||
maxWorkers: 1,
|
||||
transform: {
|
||||
"\\.[jt]sx?$": ["ts-jest", { useESM: true }],
|
||||
},
|
||||
moduleNameMapper: {
|
||||
"^(\\.{1,2}/.+)\\.js$": "$1",
|
||||
},
|
||||
extensionsToTreatAsEsm: [".ts", ".tsx"],
|
||||
preset: "ts-jest/presets/default-esm",
|
||||
testEnvironment: "node",
|
||||
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
|
||||
resolver: "<rootDir>/jest.resolver.cjs",
|
||||
},
|
||||
{
|
||||
displayName: "unit",
|
||||
testMatch: ["<rootDir>/src/**/*.test.{ts,tsx}"],
|
||||
testPathIgnorePatterns: ["<rootDir>/src/e2e/"],
|
||||
transform: {
|
||||
"\\.[jt]sx?$": ["ts-jest", { useESM: true }],
|
||||
},
|
||||
moduleNameMapper: {
|
||||
"^(\\.{1,2}/.+)\\.js$": "$1",
|
||||
"^highlight\\.js/lib/languages/(.+)$":
|
||||
"<rootDir>/src/ui/__mocks__/highlightLanguage.js",
|
||||
"^lowlight$": "<rootDir>/src/ui/__mocks__/lowlight.js",
|
||||
"^ink-testing-library$":
|
||||
"<rootDir>/node_modules/ink-testing-library/build/index.js",
|
||||
"^./SyntaxHighlighter\\.js$":
|
||||
"<rootDir>/src/ui/__mocks__/SyntaxHighlighter.ts",
|
||||
"^./FreeTrialStatus\\.js$":
|
||||
"<rootDir>/src/ui/__mocks__/FreeTrialStatus.tsx",
|
||||
},
|
||||
extensionsToTreatAsEsm: [".ts", ".tsx"],
|
||||
preset: "ts-jest/presets/default-esm",
|
||||
testEnvironment: "node",
|
||||
setupFilesAfterEnv: ["<rootDir>/jest.setup.ts"],
|
||||
resolver: "<rootDir>/jest.resolver.cjs",
|
||||
},
|
||||
],
|
||||
};
|
||||
|
|
@ -1,53 +0,0 @@
|
|||
// Custom resolver for Jest to handle .js extensions in ESM project
|
||||
const path = require("path");
|
||||
const fs = require("fs");
|
||||
|
||||
module.exports = (request, options) => {
|
||||
// Call the default resolver
|
||||
const defaultResolver = options.defaultResolver;
|
||||
|
||||
// First try the default resolver
|
||||
try {
|
||||
return defaultResolver(request, options);
|
||||
} catch (e) {
|
||||
// Only continue if module not found
|
||||
if (!e.message || !e.message.includes("Cannot find module")) {
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle relative imports
|
||||
if (request.startsWith(".")) {
|
||||
const basePath = options.basedir;
|
||||
const fullPath = path.resolve(basePath, request);
|
||||
|
||||
// Try various extensions
|
||||
const extensions = ["", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs"];
|
||||
|
||||
for (const ext of extensions) {
|
||||
const testPath = fullPath + ext;
|
||||
try {
|
||||
if (fs.existsSync(testPath)) {
|
||||
return defaultResolver(testPath, options);
|
||||
}
|
||||
} catch (e) {
|
||||
// Continue to next extension
|
||||
}
|
||||
}
|
||||
|
||||
// Also try adding /index with various extensions
|
||||
for (const ext of extensions) {
|
||||
const testPath = path.join(fullPath, "index" + ext);
|
||||
try {
|
||||
if (fs.existsSync(testPath)) {
|
||||
return defaultResolver(testPath, options);
|
||||
}
|
||||
} catch (e) {
|
||||
// Continue to next extension
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If still not found, throw original error
|
||||
throw new Error(`Cannot find module '${request}'`);
|
||||
};
|
||||
|
|
@ -1,31 +0,0 @@
|
|||
module.exports = (path, options) => {
|
||||
// Call the default resolver
|
||||
const resolver = options.defaultResolver;
|
||||
|
||||
try {
|
||||
// Try to resolve the path as-is first
|
||||
return resolver(path, options);
|
||||
} catch (error) {
|
||||
// If the path ends with .js and resolution fails, try without the extension
|
||||
if (path.endsWith(".js")) {
|
||||
const pathWithoutJs = path.slice(0, -3);
|
||||
try {
|
||||
return resolver(pathWithoutJs, options);
|
||||
} catch {
|
||||
// If that also fails, try with .ts extension
|
||||
try {
|
||||
return resolver(pathWithoutJs + ".ts", options);
|
||||
} catch {
|
||||
// If that also fails, try with .tsx extension
|
||||
try {
|
||||
return resolver(pathWithoutJs + ".tsx", options);
|
||||
} catch {
|
||||
// If all attempts fail, throw the original error
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
|
@ -1,41 +0,0 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import { resetConsoleOverrides } from "./src/util/consoleOverride.js";
|
||||
|
||||
// Disable telemetry for tests
|
||||
process.env.CONTINUE_CLI_ENABLE_TELEMETRY = "0";
|
||||
|
||||
// Mock the 'open' package to prevent browser opening during tests
|
||||
jest.mock("open", () => jest.fn().mockResolvedValue(undefined));
|
||||
|
||||
// Mock common modules that cause issues
|
||||
jest.mock("./src/logging.js");
|
||||
jest.mock("./src/hooks/useService.js");
|
||||
jest.mock("./src/auth/workos.js");
|
||||
jest.mock("./src/commands/commands.js");
|
||||
jest.mock("./src/services/index.js");
|
||||
jest.mock("./src/services/ServiceContainerContext.js");
|
||||
jest.mock("./src/config.js");
|
||||
jest.mock("./src/configLoader.js");
|
||||
jest.mock("./src/args.js");
|
||||
jest.mock("./src/services/ServiceContainer.js");
|
||||
jest.mock("./src/permissions/permissionsYamlLoader.js");
|
||||
jest.mock("./src/permissions/precedenceResolver.js");
|
||||
|
||||
// Set up global afterEach hook to clear all timers and reset console
|
||||
afterEach(() => {
|
||||
// Clear jest timers only if they're available
|
||||
if (typeof jest !== "undefined" && jest.clearAllTimers) {
|
||||
try {
|
||||
jest.clearAllTimers();
|
||||
} catch (e) {
|
||||
// Ignore errors when clearing timers
|
||||
}
|
||||
}
|
||||
|
||||
// Reset console overrides to ensure clean state for each test
|
||||
try {
|
||||
resetConsoleOverrides();
|
||||
} catch (e) {
|
||||
// Ignore errors when resetting console
|
||||
}
|
||||
});
|
||||
19
package-lock.json
generated
19
package-lock.json
generated
|
|
@ -29,6 +29,7 @@
|
|||
"@workos-inc/node": "^7.45.0",
|
||||
"chalk": "^5.4.1",
|
||||
"commander": "^14.0.0",
|
||||
"date-fns": "^4.1.0",
|
||||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.5.0",
|
||||
"express": "^5.1.0",
|
||||
|
|
@ -63,6 +64,7 @@
|
|||
"@semantic-release/github": "^11.0.3",
|
||||
"@semantic-release/npm": "^12.0.2",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@types/date-fns": "^2.5.3",
|
||||
"@types/diff": "^7.0.2",
|
||||
"@types/express": "^5.0.3",
|
||||
"@types/glob": "^8.1.0",
|
||||
|
|
@ -5627,6 +5629,13 @@
|
|||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/date-fns": {
|
||||
"version": "2.5.3",
|
||||
"resolved": "https://registry.npmjs.org/@types/date-fns/-/date-fns-2.5.3.tgz",
|
||||
"integrity": "sha512-4KVPD3g5RjSgZtdOjvI/TDFkLNUHhdoWxmierdQbDeEg17Rov0hbBYtIzNaQA67ORpteOhvR9YEMTb6xeDCang==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/deep-eql": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
|
||||
|
|
@ -8124,6 +8133,16 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/date-fns": {
|
||||
"version": "4.1.0",
|
||||
"resolved": "https://registry.npmjs.org/date-fns/-/date-fns-4.1.0.tgz",
|
||||
"integrity": "sha512-Ukq0owbQXxa/U3EGtsdVBkR1w7KOQ5gIBqdH2hkvknzZPYvBxb/aa6E8L7tmjFtkwZBu3UXBbjIgPo/Ez4xaNg==",
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/kossnocorp"
|
||||
}
|
||||
},
|
||||
"node_modules/debug": {
|
||||
"version": "4.4.1",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz",
|
||||
|
|
|
|||
|
|
@ -58,6 +58,7 @@
|
|||
"@workos-inc/node": "^7.45.0",
|
||||
"chalk": "^5.4.1",
|
||||
"commander": "^14.0.0",
|
||||
"date-fns": "^4.1.0",
|
||||
"diff": "^7.0.0",
|
||||
"dotenv": "^16.5.0",
|
||||
"express": "^5.1.0",
|
||||
|
|
@ -89,6 +90,7 @@
|
|||
"@semantic-release/github": "^11.0.3",
|
||||
"@semantic-release/npm": "^12.0.2",
|
||||
"@testing-library/react": "^16.3.0",
|
||||
"@types/date-fns": "^2.5.3",
|
||||
"@types/diff": "^7.0.2",
|
||||
"@types/express": "^5.0.3",
|
||||
"@types/glob": "^8.1.0",
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ This document provides an overview of the different testing strategies used in t
|
|||
- Testing business logic components
|
||||
- Testing error handling and edge cases
|
||||
|
||||
**Framework**: Jest with TypeScript support
|
||||
**Framework**: Vitest with TypeScript support
|
||||
|
||||
**Examples**:
|
||||
|
||||
|
|
@ -54,7 +54,7 @@ This document provides an overview of the different testing strategies used in t
|
|||
- Testing component state changes
|
||||
- Testing message display and formatting
|
||||
|
||||
**Framework**: Jest + Ink Testing Library + React Testing utilities
|
||||
**Framework**: Vitest + Ink Testing Library + React Testing utilities
|
||||
|
||||
**Examples**:
|
||||
|
||||
|
|
@ -112,7 +112,7 @@ This document provides an overview of the different testing strategies used in t
|
|||
|
||||
## Configuration
|
||||
|
||||
**Jest Configuration**: [`jest.config.mjs`](../jest.config.mjs)
|
||||
**Vitest Configuration**: [`vitest.config.ts`](../vitest.config.ts)
|
||||
|
||||
- TypeScript support with ES modules
|
||||
- React/Ink component testing setup
|
||||
|
|
@ -125,14 +125,14 @@ This document provides an overview of the different testing strategies used in t
|
|||
# Run all tests with linting
|
||||
npm test
|
||||
|
||||
# Run tests in watch mode (Jest only)
|
||||
npx jest --watch
|
||||
# Run tests in watch mode
|
||||
npx vitest --watch
|
||||
|
||||
# Run specific test file
|
||||
npx jest src/util/formatError.test.ts
|
||||
npx vitest src/util/formatError.test.ts
|
||||
|
||||
# Run tests with coverage
|
||||
npx jest --coverage
|
||||
npx vitest --coverage
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
|
|
|||
71
src/asciiArt.test.ts
Normal file
71
src/asciiArt.test.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import { describe, expect, it, beforeEach, afterEach } from "vitest";
|
||||
|
||||
import { getDisplayableAsciiArt, CONTINUE_ASCII_ART } from "./asciiArt.js";
|
||||
|
||||
describe("asciiArt", () => {
|
||||
let originalColumns: number | undefined;
|
||||
|
||||
beforeEach(() => {
|
||||
originalColumns = process.stdout.columns;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
if (originalColumns === undefined) {
|
||||
delete (process.stdout as any).columns;
|
||||
} else {
|
||||
process.stdout.columns = originalColumns;
|
||||
}
|
||||
});
|
||||
|
||||
describe("getDisplayableAsciiArt", () => {
|
||||
it("should return full ASCII art when terminal is wide enough", () => {
|
||||
// Set process.stdout.columns to simulate wide terminal
|
||||
process.stdout.columns = 80;
|
||||
|
||||
const result = getDisplayableAsciiArt();
|
||||
|
||||
expect(result).toBe(CONTINUE_ASCII_ART);
|
||||
});
|
||||
|
||||
it("should return simple text version when terminal is too narrow", () => {
|
||||
// Set process.stdout.columns to simulate narrow terminal
|
||||
process.stdout.columns = 60;
|
||||
|
||||
const result = getDisplayableAsciiArt();
|
||||
|
||||
expect(result).toContain("CONTINUE");
|
||||
expect(result).toContain("v0.0.0-dev");
|
||||
expect(result).not.toBe(CONTINUE_ASCII_ART);
|
||||
// Should be much shorter than the full ASCII art
|
||||
expect(result.length).toBeLessThan(CONTINUE_ASCII_ART.length / 2);
|
||||
});
|
||||
|
||||
it("should return simple text version when terminal is below threshold", () => {
|
||||
// Test the edge case at exactly 74 columns (below our threshold of 75)
|
||||
process.stdout.columns = 74;
|
||||
|
||||
const result = getDisplayableAsciiArt();
|
||||
|
||||
expect(result).toContain("CONTINUE");
|
||||
expect(result).not.toBe(CONTINUE_ASCII_ART);
|
||||
});
|
||||
|
||||
it("should return full ASCII art when terminal is exactly at threshold", () => {
|
||||
// Test the edge case at exactly 75 columns (our threshold)
|
||||
process.stdout.columns = 75;
|
||||
|
||||
const result = getDisplayableAsciiArt();
|
||||
|
||||
expect(result).toBe(CONTINUE_ASCII_ART);
|
||||
});
|
||||
|
||||
it("should default to full ASCII art when columns is undefined", () => {
|
||||
// Set process.stdout.columns to undefined (should default to 80)
|
||||
delete (process.stdout as any).columns;
|
||||
|
||||
const result = getDisplayableAsciiArt();
|
||||
|
||||
expect(result).toBe(CONTINUE_ASCII_ART);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -14,6 +14,24 @@ ${mind.multiline(` ██████╗ ██████╗ ███╗
|
|||
╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚══════╝`)}
|
||||
${d("v" + getVersion())}`;
|
||||
|
||||
// Minimum terminal width required to display ASCII art properly
|
||||
const MIN_WIDTH_FOR_ASCII_ART = 75;
|
||||
|
||||
/**
|
||||
* Returns the ASCII art only if the terminal is wide enough to display it properly.
|
||||
* If terminal is too narrow, returns just the version string.
|
||||
*/
|
||||
export function getDisplayableAsciiArt(): string {
|
||||
const terminalWidth = process.stdout.columns || 80;
|
||||
|
||||
if (terminalWidth >= MIN_WIDTH_FOR_ASCII_ART) {
|
||||
return CONTINUE_ASCII_ART;
|
||||
}
|
||||
|
||||
// If terminal is too narrow, just show a simple version
|
||||
return `\n${chalk.bold.blue("CONTINUE")} ${d("v" + getVersion())}\n`;
|
||||
}
|
||||
|
||||
export const CONTINUE_LOGO_ASCII_ART = `
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
|
||||
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @@
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import chalk from "chalk";
|
|||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import * as readlineSync from "readline-sync";
|
||||
|
||||
import { CONTINUE_ASCII_ART } from "../asciiArt.js";
|
||||
import { getDisplayableAsciiArt } from "../asciiArt.js";
|
||||
import {
|
||||
compactChatHistory,
|
||||
findCompactionIndex,
|
||||
|
|
@ -456,7 +456,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
|
|||
}
|
||||
|
||||
// Show ASCII art and version for TUI mode
|
||||
console.log(CONTINUE_ASCII_ART);
|
||||
console.log(getDisplayableAsciiArt());
|
||||
|
||||
// Start TUI with skipOnboarding since we already handled it
|
||||
await startTUIChat({
|
||||
|
|
|
|||
|
|
@ -1,5 +1,13 @@
|
|||
import { type AssistantConfig } from "@continuedev/sdk";
|
||||
|
||||
// Export command functions
|
||||
export { chat } from "./chat.js";
|
||||
export { login } from "./login.js";
|
||||
export { logout } from "./logout.js";
|
||||
export { remote } from "./remote.js";
|
||||
export { serve } from "./serve.js";
|
||||
export { listSessionsCommand } from "./ls.js";
|
||||
|
||||
export interface SlashCommand {
|
||||
name: string;
|
||||
description: string;
|
||||
|
|
|
|||
129
src/commands/ls.test.ts
Normal file
129
src/commands/ls.test.ts
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import * as sessionModule from "../session.js";
|
||||
|
||||
import { listSessionsCommand } from "./ls.js";
|
||||
|
||||
// Mock the session module
|
||||
vi.mock("../session.js", () => ({
|
||||
listSessions: vi.fn(),
|
||||
loadSessionById: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock the TUI components
|
||||
vi.mock("../ui/SessionSelector.js", () => ({
|
||||
SessionSelector: () => null,
|
||||
}));
|
||||
|
||||
// Mock ink
|
||||
vi.mock("ink", () => ({
|
||||
render: vi.fn(() => ({ unmount: vi.fn() })),
|
||||
}));
|
||||
|
||||
// Mock react
|
||||
vi.mock("react", () => ({
|
||||
createElement: vi.fn(),
|
||||
}));
|
||||
|
||||
// Mock the chat command
|
||||
vi.mock("./chat.js", () => ({
|
||||
chat: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("listSessionsCommand", () => {
|
||||
const mockListSessions = vi.mocked(sessionModule.listSessions);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("should output JSON format when format is json", async () => {
|
||||
const mockSessions = [
|
||||
{
|
||||
id: "session-1",
|
||||
path: "/path/to/session1.json",
|
||||
timestamp: new Date("2023-01-01T10:00:00Z"),
|
||||
messageCount: 5,
|
||||
firstUserMessage: "Hello world",
|
||||
},
|
||||
{
|
||||
id: "session-2",
|
||||
path: "/path/to/session2.json",
|
||||
timestamp: new Date("2023-01-01T09:00:00Z"),
|
||||
messageCount: 3,
|
||||
firstUserMessage: "Test message",
|
||||
},
|
||||
];
|
||||
|
||||
mockListSessions.mockReturnValue(mockSessions);
|
||||
|
||||
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
|
||||
await listSessionsCommand({ format: "json" });
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
JSON.stringify({
|
||||
sessions: [
|
||||
{
|
||||
id: "session-1",
|
||||
timestamp: "2023-01-01T10:00:00.000Z",
|
||||
messageCount: 5,
|
||||
firstUserMessage: "Hello world",
|
||||
},
|
||||
{
|
||||
id: "session-2",
|
||||
timestamp: "2023-01-01T09:00:00.000Z",
|
||||
messageCount: 3,
|
||||
firstUserMessage: "Test message",
|
||||
},
|
||||
],
|
||||
}, null, 2)
|
||||
);
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("should use limit of 10 for JSON and 20 for TUI", async () => {
|
||||
mockListSessions.mockReturnValue([]);
|
||||
|
||||
// JSON mode should fetch 10
|
||||
await listSessionsCommand({ format: "json" });
|
||||
expect(mockListSessions).toHaveBeenCalledWith(10);
|
||||
|
||||
// TUI mode should fetch 20 (so UI can choose how many to display)
|
||||
await listSessionsCommand({});
|
||||
expect(mockListSessions).toHaveBeenCalledWith(20);
|
||||
});
|
||||
|
||||
it("should handle empty sessions gracefully in JSON mode", async () => {
|
||||
mockListSessions.mockReturnValue([]);
|
||||
|
||||
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
|
||||
await listSessionsCommand({ format: "json" });
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
JSON.stringify({ sessions: [] }, null, 2)
|
||||
);
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
|
||||
it("should handle empty sessions gracefully in TUI mode", async () => {
|
||||
mockListSessions.mockReturnValue([]);
|
||||
|
||||
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
|
||||
|
||||
await listSessionsCommand({});
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
"No previous sessions found. Start a new conversation with: cn"
|
||||
);
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
108
src/commands/ls.ts
Normal file
108
src/commands/ls.ts
Normal file
|
|
@ -0,0 +1,108 @@
|
|||
import { render } from "ink";
|
||||
import React from "react";
|
||||
|
||||
import { loadSessionById, listSessions } from "../session.js";
|
||||
import { SessionSelector } from "../ui/SessionSelector.js";
|
||||
import { logger } from "../util/logger.js";
|
||||
|
||||
import { chat } from "./chat.js";
|
||||
|
||||
interface ListSessionsOptions {
|
||||
format?: "json";
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a specific session ID for the current process
|
||||
* This allows us to load a selected session as if it were the current session
|
||||
*/
|
||||
function setSessionId(sessionId: string): void {
|
||||
// Use the same environment variable that getSessionId() checks
|
||||
process.env.CONTINUE_CLI_TEST_SESSION_ID = sessionId.replace(
|
||||
"continue-cli-",
|
||||
"",
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* List recent chat sessions and allow selection
|
||||
*/
|
||||
export async function listSessionsCommand(
|
||||
options: ListSessionsOptions = {},
|
||||
): Promise<void> {
|
||||
// Fetch more sessions than we might display so the UI can choose based on screen height
|
||||
// But still limit for JSON output to keep it reasonable
|
||||
const sessions = listSessions(options.format === "json" ? 10 : 20);
|
||||
|
||||
// Handle JSON format output
|
||||
if (options.format === "json") {
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
sessions: sessions.map((session) => ({
|
||||
id: session.id,
|
||||
timestamp: session.timestamp.toISOString(),
|
||||
messageCount: session.messageCount,
|
||||
firstUserMessage: session.firstUserMessage,
|
||||
})),
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle empty sessions case
|
||||
if (sessions.length === 0) {
|
||||
console.log(
|
||||
"No previous sessions found. Start a new conversation with: cn",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Start TUI selector
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const handleSelect = async (sessionId: string) => {
|
||||
try {
|
||||
app.unmount();
|
||||
|
||||
// Verify the session exists before trying to load it
|
||||
const sessionHistory = loadSessionById(sessionId);
|
||||
if (!sessionHistory) {
|
||||
console.error(`Session ${sessionId} could not be loaded.`);
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
logger.info(`Loading session: ${sessionId}`);
|
||||
|
||||
// Set the session ID so that when chat() runs, it will load this session
|
||||
setSessionId(sessionId);
|
||||
|
||||
// Start chat with resume flag to load the selected session
|
||||
await chat(undefined, {
|
||||
resume: true,
|
||||
headless: false,
|
||||
});
|
||||
|
||||
resolve();
|
||||
} catch (error) {
|
||||
logger.error("Error loading session:", error);
|
||||
reject(error);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExit = () => {
|
||||
app.unmount();
|
||||
resolve();
|
||||
};
|
||||
|
||||
const app = render(
|
||||
React.createElement(SessionSelector, {
|
||||
sessions,
|
||||
onSelect: handleSelect,
|
||||
onExit: handleExit,
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
|
@ -44,7 +44,7 @@ describe("E2E: Resume Flag", () => {
|
|||
expect(firstResult.stdout).toContain("Hello! Nice to meet you.");
|
||||
|
||||
// Verify that a session file was created
|
||||
const sessionDir = path.join(context.testDir, ".continue-cli", "sessions");
|
||||
const sessionDir = path.join(context.testDir, ".continue", "cli-sessions");
|
||||
const sessionFiles = await fs.readdir(sessionDir);
|
||||
expect(sessionFiles).toHaveLength(1);
|
||||
|
||||
|
|
@ -131,7 +131,7 @@ describe("E2E: Resume Flag", () => {
|
|||
expect(firstResult.stdout).toContain("First response");
|
||||
|
||||
// Verify the first session was saved correctly
|
||||
const sessionDir = path.join(context.testDir, ".continue-cli", "sessions");
|
||||
const sessionDir = path.join(context.testDir, ".continue", "cli-sessions");
|
||||
let sessionFiles = await fs.readdir(sessionDir);
|
||||
expect(sessionFiles).toHaveLength(1);
|
||||
|
||||
|
|
|
|||
12
src/index.ts
12
src/index.ts
|
|
@ -5,6 +5,7 @@ import { Command } from "commander";
|
|||
import { chat } from "./commands/chat.js";
|
||||
import { login } from "./commands/login.js";
|
||||
import { logout } from "./commands/logout.js";
|
||||
import { listSessionsCommand } from "./commands/ls.js";
|
||||
import { remoteTest } from "./commands/remote-test.js";
|
||||
import { remote } from "./commands/remote.js";
|
||||
import { serve } from "./commands/serve.js";
|
||||
|
|
@ -148,6 +149,17 @@ program
|
|||
await logout();
|
||||
});
|
||||
|
||||
// List sessions subcommand
|
||||
program
|
||||
.command("ls")
|
||||
.description("List recent chat sessions and select one to resume")
|
||||
.option("--json", "Output in JSON format")
|
||||
.action(async (options) => {
|
||||
await listSessionsCommand({
|
||||
format: options.json ? "json" : undefined,
|
||||
});
|
||||
});
|
||||
|
||||
// Remote subcommand
|
||||
program
|
||||
.command("remote [prompt]")
|
||||
|
|
|
|||
121
src/session.ts
121
src/session.ts
|
|
@ -156,7 +156,7 @@ function getSessionId(): string {
|
|||
function getSessionDir(): string {
|
||||
// For tests, use the test directory if we're in test mode
|
||||
if (process.env.CONTINUE_CLI_TEST && process.env.HOME) {
|
||||
const sessionDir = path.join(process.env.HOME, ".continue-cli", "sessions");
|
||||
const sessionDir = path.join(process.env.HOME, ".continue", "cli-sessions");
|
||||
|
||||
// Create directory if it doesn't exist
|
||||
if (!fs.existsSync(sessionDir)) {
|
||||
|
|
@ -167,7 +167,7 @@ function getSessionDir(): string {
|
|||
}
|
||||
|
||||
const homeDir = os.homedir();
|
||||
const sessionDir = path.join(homeDir, ".continue-cli", "sessions");
|
||||
const sessionDir = path.join(homeDir, ".continue", "cli-sessions");
|
||||
|
||||
// Create directory if it doesn't exist
|
||||
if (!fs.existsSync(sessionDir)) {
|
||||
|
|
@ -243,3 +243,120 @@ export function hasSession(): boolean {
|
|||
const sessionFilePath = getSessionFilePath();
|
||||
return fs.existsSync(sessionFilePath);
|
||||
}
|
||||
|
||||
/**
|
||||
* Session metadata for listing sessions
|
||||
*/
|
||||
export interface SessionMetadata {
|
||||
id: string; // Session ID from filename
|
||||
path: string; // Full file path
|
||||
timestamp: Date; // Last modified or session timestamp
|
||||
messageCount: number; // Total messages in session
|
||||
firstUserMessage?: string; // Preview of first user input
|
||||
}
|
||||
|
||||
/**
|
||||
* Get metadata from a session file
|
||||
*/
|
||||
function getSessionMetadata(filePath: string): SessionMetadata | null {
|
||||
try {
|
||||
const fileName = path.basename(filePath, ".json");
|
||||
const stats = fs.statSync(filePath);
|
||||
const sessionData = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
||||
|
||||
const chatHistory = sessionData.chatHistory || [];
|
||||
const messageCount = chatHistory.length;
|
||||
|
||||
// Find the first user message
|
||||
let firstUserMessage: string | undefined;
|
||||
for (let i = 0; i < chatHistory.length; i++) {
|
||||
if (chatHistory[i].role === "user") {
|
||||
const content = chatHistory[i].content;
|
||||
// Handle both string and array content types
|
||||
if (typeof content === "string") {
|
||||
firstUserMessage = content;
|
||||
} else if (Array.isArray(content)) {
|
||||
// For array content, find the first text part
|
||||
const textPart = content.find((part) => part.type === "text");
|
||||
firstUserMessage = textPart?.text || "(multimodal message)";
|
||||
} else {
|
||||
firstUserMessage = "(unknown content type)";
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Use session timestamp if available, otherwise file modification time
|
||||
const timestamp = sessionData.timestamp
|
||||
? new Date(sessionData.timestamp)
|
||||
: stats.mtime;
|
||||
|
||||
return {
|
||||
id: fileName,
|
||||
path: filePath,
|
||||
timestamp,
|
||||
messageCount,
|
||||
firstUserMessage,
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error(`Error reading session file ${filePath}:`, error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* List all available sessions with metadata
|
||||
*/
|
||||
export function listSessions(limit: number = 10): SessionMetadata[] {
|
||||
try {
|
||||
const sessionDir = getSessionDir();
|
||||
|
||||
if (!fs.existsSync(sessionDir)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const files = fs
|
||||
.readdirSync(sessionDir)
|
||||
.filter((file) => file.endsWith(".json"))
|
||||
.map((file) => path.join(sessionDir, file));
|
||||
|
||||
const sessions: SessionMetadata[] = [];
|
||||
|
||||
for (const filePath of files) {
|
||||
const metadata = getSessionMetadata(filePath);
|
||||
if (metadata) {
|
||||
sessions.push(metadata);
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by timestamp (most recent first) and limit results
|
||||
return sessions
|
||||
.sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())
|
||||
.slice(0, limit);
|
||||
} catch (error) {
|
||||
logger.error("Error listing sessions:", error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load chat history from a specific session file
|
||||
*/
|
||||
export function loadSessionById(
|
||||
sessionId: string,
|
||||
): ChatCompletionMessageParam[] | null {
|
||||
try {
|
||||
const sessionDir = getSessionDir();
|
||||
const sessionFilePath = path.join(sessionDir, `${sessionId}.json`);
|
||||
|
||||
if (!fs.existsSync(sessionFilePath)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const sessionData = JSON.parse(fs.readFileSync(sessionFilePath, "utf8"));
|
||||
return sessionData.chatHistory || null;
|
||||
} catch (error) {
|
||||
logger.error("Error loading session by ID:", error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
// Mode-related slash commands have been removed per user request
|
||||
// This test file is no longer needed but needs a dummy test for Jest
|
||||
// This test file is no longer needed but needs a dummy test for Vitest
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
|
|
|
|||
|
|
@ -78,9 +78,6 @@ export function createUITestContext(
|
|||
setMaxListeners: vi.fn(),
|
||||
};
|
||||
|
||||
// Note: Jest mocks need to be hoisted, so they can't be called inside functions
|
||||
// The actual mocking should be done at the top of test files
|
||||
|
||||
const cleanup = () => {
|
||||
vi.clearAllMocks();
|
||||
};
|
||||
|
|
|
|||
|
|
@ -78,7 +78,7 @@ describe("runTerminalCommandTool", () => {
|
|||
expect(elapsed).toBeLessThan(TEST_TIMEOUT_MS + 200); // Allow 200ms margin
|
||||
expect(elapsed).toBeGreaterThan(TEST_TIMEOUT_MS - 100); // Allow 100ms margin
|
||||
expect(result).toContain(`[Command timed out after ${TEST_TIMEOUT_MS / 1000} seconds of no output]`);
|
||||
}, TEST_TIMEOUT_MS + 2000); // Set Jest timeout with buffer
|
||||
}, TEST_TIMEOUT_MS + 2000); // Set test timeout with buffer
|
||||
|
||||
it("should not timeout commands that continuously produce output", async () => {
|
||||
// Create a command that produces output at intervals shorter than timeout
|
||||
|
|
@ -95,7 +95,7 @@ describe("runTerminalCommandTool", () => {
|
|||
expect(result).toContain("output 1");
|
||||
expect(result).toContain(`output ${iterations}`);
|
||||
expect(result).not.toContain("[Command timed out");
|
||||
}, TEST_TIMEOUT_MS * 3); // Set Jest timeout with buffer
|
||||
}, TEST_TIMEOUT_MS * 3); // Set test timeout with buffer
|
||||
|
||||
it("should reset timeout when command produces stderr output", async () => {
|
||||
// Create a command that produces stderr output periodically
|
||||
|
|
@ -112,7 +112,7 @@ describe("runTerminalCommandTool", () => {
|
|||
expect(result).toContain("done");
|
||||
expect(result).toContain("Stderr: error 1");
|
||||
expect(result).not.toContain("[Command timed out");
|
||||
}, TEST_TIMEOUT_MS * 3); // Set Jest timeout with buffer
|
||||
}, TEST_TIMEOUT_MS * 3); // Set test timeout with buffer
|
||||
|
||||
it("should include partial output when timing out", async () => {
|
||||
// Create a command that produces some output then stops
|
||||
|
|
@ -123,7 +123,7 @@ describe("runTerminalCommandTool", () => {
|
|||
|
||||
expect(result).toContain("initial output");
|
||||
expect(result).toContain(`[Command timed out after ${TEST_TIMEOUT_MS / 1000} seconds of no output]`);
|
||||
}, TEST_TIMEOUT_MS + 2000); // Set Jest timeout with buffer
|
||||
}, TEST_TIMEOUT_MS + 2000); // Set test timeout with buffer
|
||||
});
|
||||
|
||||
describe("output handling", () => {
|
||||
|
|
|
|||
127
src/ui/SessionSelector.test.tsx
Normal file
127
src/ui/SessionSelector.test.tsx
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
import {
|
||||
subDays,
|
||||
subMonths,
|
||||
subYears,
|
||||
startOfDay,
|
||||
addHours
|
||||
} from "date-fns";
|
||||
import { render } from "ink-testing-library";
|
||||
import React from "react";
|
||||
import { describe, expect, it, vi, beforeEach } from "vitest";
|
||||
|
||||
import type { SessionMetadata } from "../session.js";
|
||||
|
||||
import { SessionSelector } from "./SessionSelector.js";
|
||||
|
||||
describe("SessionSelector", () => {
|
||||
const mockOnSelect = vi.fn();
|
||||
const mockOnExit = vi.fn();
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("formats timestamps correctly for different time periods", () => {
|
||||
const now = new Date();
|
||||
const today = addHours(startOfDay(now), 14); // 2 PM today
|
||||
const yesterday = subDays(today, 1);
|
||||
const thisWeek = subDays(today, 3); // 3 days ago (this week)
|
||||
const thisYear = subMonths(today, 2); // 2 months ago (this year)
|
||||
const lastYear = subYears(today, 1); // 1 year ago
|
||||
|
||||
const sessions: SessionMetadata[] = [
|
||||
{
|
||||
id: "session-1",
|
||||
path: "/test/session-1.json",
|
||||
timestamp: today,
|
||||
messageCount: 10,
|
||||
firstUserMessage: "Today's session",
|
||||
},
|
||||
{
|
||||
id: "session-2",
|
||||
path: "/test/session-2.json",
|
||||
timestamp: yesterday,
|
||||
messageCount: 5,
|
||||
firstUserMessage: "Yesterday's session",
|
||||
},
|
||||
{
|
||||
id: "session-3",
|
||||
path: "/test/session-3.json",
|
||||
timestamp: thisWeek,
|
||||
messageCount: 8,
|
||||
firstUserMessage: "This week's session",
|
||||
},
|
||||
{
|
||||
id: "session-4",
|
||||
path: "/test/session-4.json",
|
||||
timestamp: thisYear,
|
||||
messageCount: 12,
|
||||
firstUserMessage: "This year's session",
|
||||
},
|
||||
{
|
||||
id: "session-5",
|
||||
path: "/test/session-5.json",
|
||||
timestamp: lastYear,
|
||||
messageCount: 3,
|
||||
firstUserMessage: "Last year's session",
|
||||
},
|
||||
];
|
||||
|
||||
const { lastFrame } = render(
|
||||
<SessionSelector
|
||||
sessions={sessions}
|
||||
onSelect={mockOnSelect}
|
||||
onExit={mockOnExit}
|
||||
/>
|
||||
);
|
||||
|
||||
// Check that the output contains expected date formats
|
||||
expect(lastFrame()).toContain("2:00 PM"); // Today should show time
|
||||
expect(lastFrame()).toContain("yesterday"); // Yesterday should show "yesterday"
|
||||
|
||||
// This week should show day name (we can't predict exact day without knowing when test runs)
|
||||
// but we can check it doesn't contain "ago" which was the old format
|
||||
expect(lastFrame()).not.toContain("days ago");
|
||||
|
||||
// This year should show month/day format like "Oct 18" (no "ago")
|
||||
expect(lastFrame()).toMatch(/[A-Z][a-z]{2} \d{1,2}/); // MMM d format
|
||||
|
||||
// Last year should include the year
|
||||
expect(lastFrame()).toMatch(/[A-Z][a-z]{2} \d{1,2}, \d{4}/); // MMM d, yyyy format
|
||||
});
|
||||
|
||||
it("handles empty sessions gracefully", () => {
|
||||
const { lastFrame } = render(
|
||||
<SessionSelector
|
||||
sessions={[]}
|
||||
onSelect={mockOnSelect}
|
||||
onExit={mockOnExit}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(lastFrame()).toContain("No previous sessions found");
|
||||
expect(lastFrame()).toContain("Start a new conversation with: cn");
|
||||
});
|
||||
|
||||
it("handles sessions without first user message", () => {
|
||||
const sessions: SessionMetadata[] = [
|
||||
{
|
||||
id: "session-1",
|
||||
path: "/test/session-1.json",
|
||||
timestamp: new Date(),
|
||||
messageCount: 0,
|
||||
firstUserMessage: undefined,
|
||||
},
|
||||
];
|
||||
|
||||
const { lastFrame } = render(
|
||||
<SessionSelector
|
||||
sessions={sessions}
|
||||
onSelect={mockOnSelect}
|
||||
onExit={mockOnExit}
|
||||
/>
|
||||
);
|
||||
|
||||
expect(lastFrame()).toContain("(no messages)");
|
||||
});
|
||||
});
|
||||
118
src/ui/SessionSelector.tsx
Normal file
118
src/ui/SessionSelector.tsx
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
import { format, isToday, isYesterday, isThisWeek, isThisYear } from "date-fns";
|
||||
import { Box, Text, useInput } from "ink";
|
||||
import React, { useMemo, useState } from "react";
|
||||
|
||||
import { SessionMetadata } from "../session.js";
|
||||
|
||||
import { useTerminalSize } from "./hooks/useTerminalSize.js";
|
||||
|
||||
interface SessionSelectorProps {
|
||||
sessions: SessionMetadata[];
|
||||
onSelect: (sessionId: string) => void;
|
||||
onExit: () => void;
|
||||
}
|
||||
|
||||
function formatTimestamp(date: Date): string {
|
||||
if (isToday(date)) {
|
||||
return format(date, "h:mm a");
|
||||
} else if (isYesterday(date)) {
|
||||
return "yesterday";
|
||||
} else if (isThisWeek(date)) {
|
||||
return format(date, "EEEE"); // Day name (e.g., "Monday")
|
||||
} else if (isThisYear(date)) {
|
||||
return format(date, "MMM d"); // e.g., "Jan 15"
|
||||
} else {
|
||||
return format(date, "MMM d, yyyy"); // e.g., "Jan 15, 2023"
|
||||
}
|
||||
}
|
||||
|
||||
function formatMessage(message: string | undefined): string {
|
||||
if (!message) return "(no messages)";
|
||||
// Ensure we're working with a string, handle edge cases from persisted data
|
||||
const messageStr = typeof message === "string" ? message : String(message);
|
||||
return messageStr.split("\n")[0];
|
||||
}
|
||||
|
||||
export function SessionSelector({
|
||||
sessions,
|
||||
onSelect,
|
||||
onExit,
|
||||
}: SessionSelectorProps) {
|
||||
const [selectedIndex, setSelectedIndex] = useState(0);
|
||||
const { rows: terminalHeight } = useTerminalSize();
|
||||
|
||||
// Calculate how many sessions we can display based on terminal height
|
||||
const displaySessions = useMemo(() => {
|
||||
// Reserve 5 lines for header and instructions, each session takes 3 lines (2 content + 1 spacer)
|
||||
const availableHeight = Math.max(1, terminalHeight - 5);
|
||||
const maxDisplayableSessions = Math.floor(availableHeight / 3);
|
||||
|
||||
return sessions.slice(0, maxDisplayableSessions);
|
||||
}, [sessions, terminalHeight]);
|
||||
|
||||
useInput((input, key) => {
|
||||
if (key.upArrow || input === "k") {
|
||||
setSelectedIndex((prev) =>
|
||||
prev > 0 ? prev - 1 : displaySessions.length - 1,
|
||||
);
|
||||
} else if (key.downArrow || input === "j") {
|
||||
setSelectedIndex((prev) =>
|
||||
prev < displaySessions.length - 1 ? prev + 1 : 0,
|
||||
);
|
||||
} else if (key.return) {
|
||||
if (displaySessions[selectedIndex]) {
|
||||
onSelect(displaySessions[selectedIndex].id);
|
||||
}
|
||||
} else if (key.escape || (key.ctrl && input === "c")) {
|
||||
onExit();
|
||||
}
|
||||
});
|
||||
|
||||
if (sessions.length === 0) {
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color="yellow">No previous sessions found.</Text>
|
||||
<Text color="gray">Start a new conversation with: cn</Text>
|
||||
<Text color="gray">Press ESC to exit</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box flexDirection="column" padding={1}>
|
||||
<Text color="blue" bold>
|
||||
Recent Sessions
|
||||
</Text>
|
||||
<Text color="gray">
|
||||
Use ↑↓ arrows to navigate, Enter to select, ESC to exit
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
|
||||
{displaySessions.map((session, index) => {
|
||||
const isSelected = index === selectedIndex;
|
||||
const indicator = isSelected ? "► " : " ";
|
||||
const color = isSelected ? "cyan" : "white";
|
||||
|
||||
return (
|
||||
<Box key={session.id} flexDirection="column">
|
||||
<Box paddingRight={3}>
|
||||
<Text color={color} wrap="truncate-end">
|
||||
{indicator}
|
||||
{formatMessage(session.firstUserMessage)}
|
||||
</Text>
|
||||
</Box>
|
||||
<Box marginLeft={2}>
|
||||
<Text color="gray">
|
||||
{formatTimestamp(session.timestamp)} - {session.messageCount}{" "}
|
||||
{session.messageCount === 1 ? "message" : "messages"}
|
||||
</Text>
|
||||
</Box>
|
||||
{index < displaySessions.length - 1 && (
|
||||
<Text key={`spacer-${session.id}`}> </Text>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
})}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
|
@ -5,7 +5,7 @@ import "./__tests__/TUIChat.input.test.js";
|
|||
import "./__tests__/TUIChat.fileSearch.test.js";
|
||||
import "./__tests__/TUIChat.slashCommands.test.js";
|
||||
|
||||
// Add a dummy test to satisfy Jest
|
||||
// Add a dummy test to satisfy Vitest
|
||||
describe("TUIChat Test Suite", () => {
|
||||
it("should import all test modules", () => {
|
||||
expect(true).toBe(true);
|
||||
|
|
|
|||
|
|
@ -1,9 +1,7 @@
|
|||
import { Box, Text } from "ink";
|
||||
import React, { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import React, { useEffect, useMemo } from "react";
|
||||
|
||||
import { useServices } from "../hooks/useService.js";
|
||||
import type { PermissionMode } from "../permissions/types.js";
|
||||
import { modeService } from "../services/ModeService.js";
|
||||
import {
|
||||
ApiClientServiceState,
|
||||
AuthServiceState,
|
||||
|
|
@ -11,164 +9,24 @@ import {
|
|||
MCPServiceState,
|
||||
ModelServiceState,
|
||||
} from "../services/types.js";
|
||||
import { getGitRemoteUrl, isGitRepo } from "../util/git.js";
|
||||
|
||||
import { ModeIndicator } from "./components/ModeIndicator.js";
|
||||
import { BottomStatusBar } from "./components/BottomStatusBar.js";
|
||||
import { ScreenContent } from "./components/ScreenContent.js";
|
||||
import { StaticChatContent } from "./components/StaticChatContent.js";
|
||||
import { ToolPermissionSelector } from "./components/ToolPermissionSelector.js";
|
||||
import { ConfigSelector } from "./ConfigSelector.js";
|
||||
import {
|
||||
useNavigation,
|
||||
type NavigationScreen,
|
||||
} from "./context/NavigationContext.js";
|
||||
import { useNavigation } from "./context/NavigationContext.js";
|
||||
import { startFileIndexing } from "./FileSearchUI.js";
|
||||
import { FreeTrialStatus } from "./FreeTrialStatus.js";
|
||||
import { FreeTrialTransitionUI } from "./FreeTrialTransitionUI.js";
|
||||
import { useChat } from "./hooks/useChat.js";
|
||||
import { useConfigSelector } from "./hooks/useConfigSelector.js";
|
||||
import { useContextPercentage } from "./hooks/useContextPercentage.js";
|
||||
import { useMessageRenderer } from "./hooks/useMessageRenderer.js";
|
||||
import { useModelSelector } from "./hooks/useModelSelector.js";
|
||||
import {
|
||||
getRepoUrlText,
|
||||
useCurrentMode,
|
||||
useIntroMessage,
|
||||
useLoginHandlers,
|
||||
useSelectors,
|
||||
} from "./hooks/useTUIChatHooks.js";
|
||||
import { LoadingAnimation } from "./LoadingAnimation.js";
|
||||
import { MCPSelector } from "./MCPSelector.js";
|
||||
import { ModelSelector } from "./ModelSelector.js";
|
||||
import type { SelectorOption } from "./Selector.js";
|
||||
import { Timer } from "./Timer.js";
|
||||
import { UpdateNotification } from "./UpdateNotification.js";
|
||||
import { UserInput } from "./UserInput.js";
|
||||
|
||||
// Type definitions for selectors
|
||||
interface ConfigOption extends SelectorOption {
|
||||
type: "local" | "assistant" | "create";
|
||||
slug?: string;
|
||||
}
|
||||
|
||||
interface ModelOption extends SelectorOption {
|
||||
index: number;
|
||||
provider: string;
|
||||
}
|
||||
|
||||
// Helper function to get repo URL text
|
||||
function getRepoUrlText(remoteUrl?: string): string {
|
||||
let url = remoteUrl ?? "";
|
||||
if (!url) {
|
||||
const isGit = isGitRepo();
|
||||
if (isGit) {
|
||||
const gitUrl = getGitRemoteUrl();
|
||||
if (gitUrl) {
|
||||
url = gitUrl;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!url) {
|
||||
url = process.cwd();
|
||||
}
|
||||
|
||||
url = url.replace(/\.git$/, "");
|
||||
url = url.replace(/^(https|http):\/\/.*?\//, "");
|
||||
return url;
|
||||
}
|
||||
|
||||
// Custom hook for intro message
|
||||
function useIntroMessage(
|
||||
isRemoteMode: boolean,
|
||||
services: any,
|
||||
allServicesReady: boolean,
|
||||
) {
|
||||
const [showIntroMessage, setShowIntroMessage] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const shouldShow =
|
||||
!isRemoteMode &&
|
||||
allServicesReady &&
|
||||
!!services.config?.config &&
|
||||
!!services.model?.model &&
|
||||
!!services.mcp?.mcpService;
|
||||
|
||||
setShowIntroMessage(shouldShow);
|
||||
}, [
|
||||
isRemoteMode,
|
||||
allServicesReady,
|
||||
services.config?.config,
|
||||
services.model?.model,
|
||||
services.mcp?.mcpService,
|
||||
]);
|
||||
|
||||
return [showIntroMessage, setShowIntroMessage] as const;
|
||||
}
|
||||
|
||||
// Custom hook for login handling
|
||||
function useLoginHandlers(
|
||||
navigateTo: any,
|
||||
navState: any,
|
||||
closeCurrentScreen: () => void,
|
||||
) {
|
||||
const handleLoginPrompt = useCallback(
|
||||
(promptText: string): Promise<string> => {
|
||||
return new Promise((resolve) => {
|
||||
navigateTo("login", { text: promptText, resolve });
|
||||
});
|
||||
},
|
||||
[navigateTo],
|
||||
);
|
||||
|
||||
const handleLoginTokenSubmit = useCallback(
|
||||
(token: string) => {
|
||||
if (navState.screenData?.resolve) {
|
||||
navState.screenData.resolve(token);
|
||||
closeCurrentScreen();
|
||||
}
|
||||
},
|
||||
[navState.screenData, closeCurrentScreen],
|
||||
);
|
||||
|
||||
return { handleLoginPrompt, handleLoginTokenSubmit };
|
||||
}
|
||||
|
||||
// Custom hook for mode tracking
|
||||
function useCurrentMode() {
|
||||
const [currentMode, setCurrentMode] = useState<PermissionMode>(
|
||||
modeService.getCurrentMode(),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handleModeChange = (newMode: PermissionMode) => {
|
||||
setCurrentMode(newMode);
|
||||
};
|
||||
|
||||
modeService.on("modeChanged", handleModeChange);
|
||||
return () => {
|
||||
modeService.off("modeChanged", handleModeChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return currentMode;
|
||||
}
|
||||
|
||||
// Custom hook to combine all selector logic
|
||||
function useSelectors(
|
||||
configPath: string | undefined,
|
||||
setMessages: React.Dispatch<React.SetStateAction<any[]>>,
|
||||
resetChatHistory: () => void,
|
||||
) {
|
||||
const { handleConfigSelect } = useConfigSelector({
|
||||
configPath,
|
||||
onMessage: (message) => {
|
||||
setMessages((prev) => [...prev, message]);
|
||||
},
|
||||
onChatReset: resetChatHistory,
|
||||
});
|
||||
|
||||
const { handleModelSelect } = useModelSelector({
|
||||
onMessage: (message) => {
|
||||
setMessages((prev) => [...prev, message]);
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
handleConfigSelect,
|
||||
handleModelSelect,
|
||||
};
|
||||
}
|
||||
|
||||
interface TUIChatProps {
|
||||
// Remote mode props
|
||||
|
|
@ -181,190 +39,6 @@ interface TUIChatProps {
|
|||
additionalRules?: string[];
|
||||
}
|
||||
|
||||
// Bottom status bar component
|
||||
interface BottomStatusBarProps {
|
||||
currentMode: PermissionMode;
|
||||
repoURlText: string;
|
||||
isRemoteMode: boolean;
|
||||
services: any;
|
||||
navState: any;
|
||||
navigateTo: (screen: NavigationScreen, data?: any) => void;
|
||||
closeCurrentScreen: () => void;
|
||||
}
|
||||
|
||||
const BottomStatusBar: React.FC<BottomStatusBarProps> = ({
|
||||
currentMode,
|
||||
repoURlText,
|
||||
isRemoteMode,
|
||||
services,
|
||||
navState,
|
||||
navigateTo,
|
||||
closeCurrentScreen,
|
||||
}) => (
|
||||
<Box flexDirection="row" justifyContent="space-between" alignItems="center">
|
||||
<Box marginLeft={2} flexDirection="row" alignItems="center">
|
||||
{currentMode === "normal" && (
|
||||
<>
|
||||
<Text color="dim" wrap="truncate-start">
|
||||
{repoURlText}
|
||||
</Text>
|
||||
<Text> </Text>
|
||||
</>
|
||||
)}
|
||||
<ModeIndicator />
|
||||
</Box>
|
||||
<Box>
|
||||
{!isRemoteMode && services.model?.model && (
|
||||
<FreeTrialStatus
|
||||
apiClient={services.apiClient?.apiClient || undefined}
|
||||
model={services.model.model}
|
||||
onTransitionStateChange={(shouldShow) => {
|
||||
if (shouldShow && navState.currentScreen === "chat") {
|
||||
navigateTo("free-trial");
|
||||
} else if (!shouldShow && navState.currentScreen === "free-trial") {
|
||||
closeCurrentScreen();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
<Box marginRight={2} marginLeft={2}>
|
||||
<UpdateNotification isRemoteMode={isRemoteMode} />
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
|
||||
// Component to handle all screen-specific rendering
|
||||
interface ScreenContentProps {
|
||||
isScreenActive: (screen: NavigationScreen) => boolean;
|
||||
navState: any;
|
||||
services: any;
|
||||
handleLoginTokenSubmit: (token: string) => void;
|
||||
handleConfigSelect: (config: ConfigOption) => Promise<void>;
|
||||
handleModelSelect: (model: ModelOption) => Promise<void>;
|
||||
handleReload: () => Promise<void>;
|
||||
closeCurrentScreen: () => void;
|
||||
activePermissionRequest: any;
|
||||
handleToolPermissionResponse: (
|
||||
requestId: string,
|
||||
approved: boolean,
|
||||
createPolicy?: boolean,
|
||||
stopStream?: boolean,
|
||||
) => void;
|
||||
handleUserMessage: (message: string) => void;
|
||||
isWaitingForResponse: boolean;
|
||||
inputMode: boolean;
|
||||
handleInterrupt: () => void;
|
||||
handleFileAttached: (filePath: string, content: string) => void;
|
||||
isInputDisabled: boolean;
|
||||
isRemoteMode: boolean;
|
||||
}
|
||||
|
||||
const ScreenContent: React.FC<ScreenContentProps> = ({
|
||||
isScreenActive,
|
||||
navState,
|
||||
services,
|
||||
handleLoginTokenSubmit,
|
||||
handleConfigSelect,
|
||||
handleModelSelect,
|
||||
handleReload,
|
||||
closeCurrentScreen,
|
||||
activePermissionRequest,
|
||||
handleToolPermissionResponse,
|
||||
handleUserMessage,
|
||||
isWaitingForResponse,
|
||||
inputMode,
|
||||
handleInterrupt,
|
||||
handleFileAttached,
|
||||
isInputDisabled,
|
||||
isRemoteMode,
|
||||
}) => {
|
||||
// Login prompt
|
||||
if (isScreenActive("login") && navState.screenData) {
|
||||
return (
|
||||
<Box
|
||||
paddingX={1}
|
||||
borderStyle="round"
|
||||
borderColor="yellow"
|
||||
flexDirection="column"
|
||||
gap={1}
|
||||
>
|
||||
<Text color="yellow" bold>
|
||||
Login Required
|
||||
</Text>
|
||||
<Text>{navState.screenData.text}</Text>
|
||||
<UserInput
|
||||
onSubmit={handleLoginTokenSubmit}
|
||||
isWaitingForResponse={false}
|
||||
inputMode={true}
|
||||
assistant={services.config?.config || undefined}
|
||||
disabled={false}
|
||||
placeholder="Enter your token..."
|
||||
hideNormalUI={true}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// Config selector (now includes organization switching)
|
||||
if (isScreenActive("config")) {
|
||||
return (
|
||||
<ConfigSelector
|
||||
onSelect={handleConfigSelect}
|
||||
onCancel={closeCurrentScreen}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (isScreenActive("mcp")) {
|
||||
return <MCPSelector onCancel={closeCurrentScreen} />;
|
||||
}
|
||||
|
||||
// Model selector
|
||||
if (isScreenActive("model")) {
|
||||
return (
|
||||
<ModelSelector
|
||||
onSelect={handleModelSelect}
|
||||
onCancel={closeCurrentScreen}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Free trial transition UI
|
||||
if (isScreenActive("free-trial")) {
|
||||
return <FreeTrialTransitionUI onReload={handleReload} />;
|
||||
}
|
||||
|
||||
// Chat screen with input area
|
||||
if (isScreenActive("chat")) {
|
||||
if (activePermissionRequest) {
|
||||
return (
|
||||
<ToolPermissionSelector
|
||||
toolName={activePermissionRequest.toolName}
|
||||
toolArgs={activePermissionRequest.toolArgs}
|
||||
requestId={activePermissionRequest.requestId}
|
||||
toolCallPreview={activePermissionRequest.toolCallPreview}
|
||||
onResponse={handleToolPermissionResponse}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<UserInput
|
||||
onSubmit={handleUserMessage}
|
||||
isWaitingForResponse={isWaitingForResponse}
|
||||
inputMode={inputMode}
|
||||
onInterrupt={handleInterrupt}
|
||||
assistant={services.config?.config || undefined}
|
||||
onFileAttached={handleFileAttached}
|
||||
disabled={isInputDisabled}
|
||||
isRemoteMode={isRemoteMode}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const TUIChat: React.FC<TUIChatProps> = ({
|
||||
remoteUrl,
|
||||
configPath,
|
||||
|
|
@ -433,6 +107,7 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
const {
|
||||
messages,
|
||||
setMessages,
|
||||
chatHistory,
|
||||
isWaitingForResponse,
|
||||
responseStartTime,
|
||||
inputMode,
|
||||
|
|
@ -459,10 +134,19 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
remoteUrl,
|
||||
});
|
||||
|
||||
// Calculate context percentage
|
||||
const contextData = useContextPercentage({
|
||||
chatHistory,
|
||||
model: services.model?.model || undefined,
|
||||
});
|
||||
|
||||
const { renderMessage } = useMessageRenderer();
|
||||
|
||||
const { handleConfigSelect, handleModelSelect } =
|
||||
useSelectors(configPath, setMessages, resetChatHistory);
|
||||
const { handleConfigSelect, handleModelSelect } = useSelectors(
|
||||
configPath,
|
||||
setMessages,
|
||||
resetChatHistory,
|
||||
);
|
||||
|
||||
// Determine if input should be disabled
|
||||
// Allow input even when services are loading, but disable for UI overlays
|
||||
|
|
@ -502,9 +186,13 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
{isWaitingForResponse && responseStartTime && (
|
||||
<Box paddingX={1} flexDirection="row" gap={1}>
|
||||
<LoadingAnimation visible={isWaitingForResponse} />
|
||||
<Text color="gray">(</Text>
|
||||
<Text key="loading-start" color="gray">
|
||||
(
|
||||
</Text>
|
||||
<Timer startTime={responseStartTime} />
|
||||
<Text color="gray">• esc to interrupt )</Text>
|
||||
<Text key="loading-end" color="gray">
|
||||
• esc to interrupt )
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
|
|
@ -532,12 +220,13 @@ const TUIChat: React.FC<TUIChatProps> = ({
|
|||
{/* Free trial status and Continue CLI info - always show */}
|
||||
<BottomStatusBar
|
||||
currentMode={currentMode}
|
||||
repoURlText={repoURlText}
|
||||
repoURLText={repoURlText}
|
||||
isRemoteMode={isRemoteMode}
|
||||
services={services}
|
||||
navState={navState}
|
||||
navigateTo={navigateTo}
|
||||
closeCurrentScreen={closeCurrentScreen}
|
||||
contextPercentage={contextData?.percentage}
|
||||
/>
|
||||
</Box>
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { AppRoot } from "../AppRoot.js";
|
|||
|
||||
export type TestMode = "local" | "remote";
|
||||
|
||||
// Dummy test to satisfy Jest
|
||||
// Dummy test to satisfy Vitest
|
||||
describe("TUIChat dual mode helper", () => {
|
||||
it("exports helper functions", () => {
|
||||
expect(testBothModes).toBeDefined();
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ export const createProps = (overrides: any = {}) => ({
|
|||
...overrides,
|
||||
});
|
||||
|
||||
// Add a dummy test to satisfy Jest requirement
|
||||
// Add a dummy test to satisfy Vitest requirement
|
||||
describe("TUIChat setup", () => {
|
||||
test("setup should export required functions", () => {
|
||||
expect(createProps).toBeDefined();
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ export function runTest(
|
|||
modes.forEach((testMode) => {
|
||||
describe(`[${testMode.toUpperCase()} MODE]`, () => {
|
||||
it(name, async () => {
|
||||
// Import mocks from Jest setup
|
||||
// Import mocks from Vitest setup
|
||||
const { useServices, useService } = await import(
|
||||
"../../hooks/useService.js"
|
||||
);
|
||||
|
|
|
|||
|
|
@ -159,7 +159,7 @@ export class MockRemoteServer {
|
|||
}
|
||||
}
|
||||
|
||||
// Add a dummy test to satisfy Jest requirement
|
||||
// Add a dummy test to satisfy Vitest requirement
|
||||
describe("MockRemoteServer", () => {
|
||||
test("should be defined", () => {
|
||||
expect(MockRemoteServer).toBeDefined();
|
||||
|
|
|
|||
70
src/ui/components/BottomStatusBar.tsx
Normal file
70
src/ui/components/BottomStatusBar.tsx
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
|
||||
import type { PermissionMode } from "../../permissions/types.js";
|
||||
import type { NavigationScreen } from "../context/NavigationContext.js";
|
||||
import { FreeTrialStatus } from "../FreeTrialStatus.js";
|
||||
import { UpdateNotification } from "../UpdateNotification.js";
|
||||
|
||||
import { ContextPercentageDisplay } from "./ContextPercentageDisplay.js";
|
||||
import { ModeIndicator } from "./ModeIndicator.js";
|
||||
|
||||
interface BottomStatusBarProps {
|
||||
currentMode: PermissionMode;
|
||||
repoURLText: string;
|
||||
isRemoteMode: boolean;
|
||||
services: any;
|
||||
navState: any;
|
||||
navigateTo: (screen: NavigationScreen, data?: any) => void;
|
||||
closeCurrentScreen: () => void;
|
||||
contextPercentage?: number;
|
||||
}
|
||||
|
||||
export const BottomStatusBar: React.FC<BottomStatusBarProps> = ({
|
||||
currentMode,
|
||||
repoURLText,
|
||||
isRemoteMode,
|
||||
services,
|
||||
navState,
|
||||
navigateTo,
|
||||
closeCurrentScreen,
|
||||
contextPercentage,
|
||||
}) => (
|
||||
<Box flexDirection="row" justifyContent="space-between" alignItems="center">
|
||||
<Box marginLeft={2} flexDirection="row" alignItems="center">
|
||||
{currentMode === "normal" && (
|
||||
<React.Fragment>
|
||||
<Text key="repo-url" color="dim" wrap="truncate-start">
|
||||
{repoURLText}
|
||||
</Text>
|
||||
<Text key="repo-separator"> </Text>
|
||||
</React.Fragment>
|
||||
)}
|
||||
<ModeIndicator />
|
||||
{contextPercentage !== undefined && contextPercentage > 75 && (
|
||||
<React.Fragment>
|
||||
<Text key="context-separator"> • </Text>
|
||||
<ContextPercentageDisplay percentage={contextPercentage} />
|
||||
</React.Fragment>
|
||||
)}
|
||||
</Box>
|
||||
<Box>
|
||||
{!isRemoteMode && services.model?.model && (
|
||||
<FreeTrialStatus
|
||||
apiClient={services.apiClient?.apiClient || undefined}
|
||||
model={services.model.model}
|
||||
onTransitionStateChange={(shouldShow) => {
|
||||
if (shouldShow && navState.currentScreen === "chat") {
|
||||
navigateTo("free-trial");
|
||||
} else if (!shouldShow && navState.currentScreen === "free-trial") {
|
||||
closeCurrentScreen();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
<Box marginRight={2} marginLeft={2}>
|
||||
<UpdateNotification isRemoteMode={isRemoteMode} />
|
||||
</Box>
|
||||
</Box>
|
||||
);
|
||||
22
src/ui/components/ContextPercentageDisplay.tsx
Normal file
22
src/ui/components/ContextPercentageDisplay.tsx
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
import { Text } from "ink";
|
||||
import React from "react";
|
||||
|
||||
interface ContextPercentageDisplayProps {
|
||||
percentage: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Component to display the current context usage percentage
|
||||
* Shows the percentage in gray color for consistency with other status indicators
|
||||
* Only displays when percentage exceeds 75% threshold
|
||||
*/
|
||||
export const ContextPercentageDisplay: React.FC<
|
||||
ContextPercentageDisplayProps
|
||||
> = ({ percentage }) => {
|
||||
// Only show if percentage is greater than 75%
|
||||
if (percentage <= 75) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return <Text color="dim">Context: {percentage}%</Text>;
|
||||
};
|
||||
158
src/ui/components/ScreenContent.tsx
Normal file
158
src/ui/components/ScreenContent.tsx
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
import { Box, Text } from "ink";
|
||||
import React from "react";
|
||||
|
||||
import { ConfigSelector } from "../ConfigSelector.js";
|
||||
import type { NavigationScreen } from "../context/NavigationContext.js";
|
||||
import { FreeTrialTransitionUI } from "../FreeTrialTransitionUI.js";
|
||||
import { MCPSelector } from "../MCPSelector.js";
|
||||
import { ModelSelector } from "../ModelSelector.js";
|
||||
import { OrganizationSelector } from "../OrganizationSelector.js";
|
||||
import type { ConfigOption, ModelOption } from "../types/selectorTypes.js";
|
||||
import { UserInput } from "../UserInput.js";
|
||||
|
||||
import { ToolPermissionSelector } from "./ToolPermissionSelector.js";
|
||||
|
||||
interface ScreenContentProps {
|
||||
isScreenActive: (screen: NavigationScreen) => boolean;
|
||||
navState: any;
|
||||
services: any;
|
||||
handleLoginTokenSubmit: (token: string) => void;
|
||||
handleOrganizationSelect: (
|
||||
organizationId: string | null,
|
||||
organizationName: string,
|
||||
) => Promise<void>;
|
||||
handleConfigSelect: (config: ConfigOption) => Promise<void>;
|
||||
handleModelSelect: (model: ModelOption) => Promise<void>;
|
||||
handleReload: () => Promise<void>;
|
||||
closeCurrentScreen: () => void;
|
||||
activePermissionRequest: any;
|
||||
handleToolPermissionResponse: (
|
||||
requestId: string,
|
||||
approved: boolean,
|
||||
createPolicy?: boolean,
|
||||
stopStream?: boolean,
|
||||
) => void;
|
||||
handleUserMessage: (message: string) => void;
|
||||
isWaitingForResponse: boolean;
|
||||
inputMode: boolean;
|
||||
handleInterrupt: () => void;
|
||||
handleFileAttached: (filePath: string, content: string) => void;
|
||||
isInputDisabled: boolean;
|
||||
isRemoteMode: boolean;
|
||||
}
|
||||
|
||||
export const ScreenContent: React.FC<ScreenContentProps> = ({
|
||||
isScreenActive,
|
||||
navState,
|
||||
services,
|
||||
handleLoginTokenSubmit,
|
||||
handleOrganizationSelect,
|
||||
handleConfigSelect,
|
||||
handleModelSelect,
|
||||
handleReload,
|
||||
closeCurrentScreen,
|
||||
activePermissionRequest,
|
||||
handleToolPermissionResponse,
|
||||
handleUserMessage,
|
||||
isWaitingForResponse,
|
||||
inputMode,
|
||||
handleInterrupt,
|
||||
handleFileAttached,
|
||||
isInputDisabled,
|
||||
isRemoteMode,
|
||||
}) => {
|
||||
// Login prompt
|
||||
if (isScreenActive("login") && navState.screenData) {
|
||||
return (
|
||||
<Box
|
||||
paddingX={1}
|
||||
borderStyle="round"
|
||||
borderColor="yellow"
|
||||
flexDirection="column"
|
||||
gap={1}
|
||||
>
|
||||
<Text color="yellow" bold>
|
||||
Login Required
|
||||
</Text>
|
||||
<Text>{navState.screenData.text}</Text>
|
||||
<UserInput
|
||||
onSubmit={handleLoginTokenSubmit}
|
||||
isWaitingForResponse={false}
|
||||
inputMode={true}
|
||||
assistant={services.config?.config || undefined}
|
||||
disabled={false}
|
||||
placeholder="Enter your token..."
|
||||
hideNormalUI={true}
|
||||
/>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
// Organization selector
|
||||
if (isScreenActive("organization")) {
|
||||
return (
|
||||
<OrganizationSelector
|
||||
onSelect={handleOrganizationSelect}
|
||||
onCancel={closeCurrentScreen}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Config selector
|
||||
if (isScreenActive("config")) {
|
||||
return (
|
||||
<ConfigSelector
|
||||
onSelect={handleConfigSelect}
|
||||
onCancel={closeCurrentScreen}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (isScreenActive("mcp")) {
|
||||
return <MCPSelector onCancel={closeCurrentScreen} />;
|
||||
}
|
||||
|
||||
// Model selector
|
||||
if (isScreenActive("model")) {
|
||||
return (
|
||||
<ModelSelector
|
||||
onSelect={handleModelSelect}
|
||||
onCancel={closeCurrentScreen}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
// Free trial transition UI
|
||||
if (isScreenActive("free-trial")) {
|
||||
return <FreeTrialTransitionUI onReload={handleReload} />;
|
||||
}
|
||||
|
||||
// Chat screen with input area
|
||||
if (isScreenActive("chat")) {
|
||||
if (activePermissionRequest) {
|
||||
return (
|
||||
<ToolPermissionSelector
|
||||
toolName={activePermissionRequest.toolName}
|
||||
toolArgs={activePermissionRequest.toolArgs}
|
||||
requestId={activePermissionRequest.requestId}
|
||||
toolCallPreview={activePermissionRequest.toolCallPreview}
|
||||
onResponse={handleToolPermissionResponse}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<UserInput
|
||||
onSubmit={handleUserMessage}
|
||||
isWaitingForResponse={isWaitingForResponse}
|
||||
inputMode={inputMode}
|
||||
onInterrupt={handleInterrupt}
|
||||
assistant={services.config?.config || undefined}
|
||||
onFileAttached={handleFileAttached}
|
||||
disabled={isInputDisabled}
|
||||
isRemoteMode={isRemoteMode}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
41
src/ui/hooks/useContextPercentage.ts
Normal file
41
src/ui/hooks/useContextPercentage.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
import { ModelConfig } from "@continuedev/config-yaml";
|
||||
import { ChatCompletionMessageParam } from "openai/resources.mjs";
|
||||
import { useMemo } from "react";
|
||||
|
||||
import {
|
||||
calculateContextUsagePercentage,
|
||||
countChatHistoryTokens,
|
||||
} from "../../util/tokenizer.js";
|
||||
|
||||
interface UseContextPercentageProps {
|
||||
chatHistory: ChatCompletionMessageParam[];
|
||||
model?: ModelConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to calculate the current context usage percentage
|
||||
* This uses the same logic as the compaction trigger to show users
|
||||
* how close they are to the context limit
|
||||
*/
|
||||
export function useContextPercentage({
|
||||
chatHistory,
|
||||
model,
|
||||
}: UseContextPercentageProps) {
|
||||
const contextData = useMemo(() => {
|
||||
// Return null if no model is available
|
||||
if (!model) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Calculate token count and percentage
|
||||
const tokenCount = countChatHistoryTokens(chatHistory);
|
||||
const percentage = calculateContextUsagePercentage(tokenCount, model);
|
||||
|
||||
return {
|
||||
tokenCount,
|
||||
percentage,
|
||||
};
|
||||
}, [chatHistory, model]);
|
||||
|
||||
return contextData;
|
||||
}
|
||||
148
src/ui/hooks/useTUIChatHooks.ts
Normal file
148
src/ui/hooks/useTUIChatHooks.ts
Normal file
|
|
@ -0,0 +1,148 @@
|
|||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import type { PermissionMode } from "../../permissions/types.js";
|
||||
import { modeService } from "../../services/ModeService.js";
|
||||
import { getGitRemoteUrl, isGitRepo } from "../../util/git.js";
|
||||
import type { ConfigOption, ModelOption } from "../types/selectorTypes.js";
|
||||
|
||||
import { useConfigSelector } from "./useConfigSelector.js";
|
||||
import { useModelSelector } from "./useModelSelector.js";
|
||||
import { useOrganizationSelector } from "./useOrganizationSelector.js";
|
||||
|
||||
// Helper function to get repo URL text
|
||||
export function getRepoUrlText(remoteUrl?: string): string {
|
||||
let url = remoteUrl ?? "";
|
||||
if (!url) {
|
||||
const isGit = isGitRepo();
|
||||
if (isGit) {
|
||||
const gitUrl = getGitRemoteUrl();
|
||||
if (gitUrl) {
|
||||
url = gitUrl;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!url) {
|
||||
url = process.cwd();
|
||||
}
|
||||
|
||||
url = url.replace(/\.git$/, "");
|
||||
url = url.replace(/^(https|http):\/\/.*?\//, "");
|
||||
return url;
|
||||
}
|
||||
|
||||
// Custom hook for intro message
|
||||
export function useIntroMessage(
|
||||
isRemoteMode: boolean,
|
||||
services: any,
|
||||
allServicesReady: boolean,
|
||||
) {
|
||||
const [showIntroMessage, setShowIntroMessage] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const shouldShow =
|
||||
!isRemoteMode &&
|
||||
allServicesReady &&
|
||||
!!services.config?.config &&
|
||||
!!services.model?.model &&
|
||||
!!services.mcp?.mcpService;
|
||||
|
||||
setShowIntroMessage(shouldShow);
|
||||
}, [
|
||||
isRemoteMode,
|
||||
allServicesReady,
|
||||
services.config?.config,
|
||||
services.model?.model,
|
||||
services.mcp?.mcpService,
|
||||
]);
|
||||
|
||||
return [showIntroMessage, setShowIntroMessage] as const;
|
||||
}
|
||||
|
||||
// Custom hook for login handling
|
||||
export function useLoginHandlers(
|
||||
navigateTo: any,
|
||||
navState: any,
|
||||
closeCurrentScreen: () => void,
|
||||
) {
|
||||
const handleLoginPrompt = useCallback(
|
||||
(promptText: string): Promise<string> => {
|
||||
return new Promise((resolve) => {
|
||||
navigateTo("login", { text: promptText, resolve });
|
||||
});
|
||||
},
|
||||
[navigateTo],
|
||||
);
|
||||
|
||||
const handleLoginTokenSubmit = useCallback(
|
||||
(token: string) => {
|
||||
if (navState.screenData?.resolve) {
|
||||
navState.screenData.resolve(token);
|
||||
closeCurrentScreen();
|
||||
}
|
||||
},
|
||||
[navState.screenData, closeCurrentScreen],
|
||||
);
|
||||
|
||||
return { handleLoginPrompt, handleLoginTokenSubmit };
|
||||
}
|
||||
|
||||
// Custom hook for mode tracking
|
||||
export function useCurrentMode() {
|
||||
const [currentMode, setCurrentMode] = useState<PermissionMode>(
|
||||
modeService.getCurrentMode(),
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const handleModeChange = (newMode: PermissionMode) => {
|
||||
setCurrentMode(newMode);
|
||||
};
|
||||
|
||||
modeService.on("modeChanged", handleModeChange);
|
||||
return () => {
|
||||
modeService.off("modeChanged", handleModeChange);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return currentMode;
|
||||
}
|
||||
|
||||
// Custom hook to combine all selector logic
|
||||
export function useSelectors(
|
||||
configPath: string | undefined,
|
||||
setMessages: React.Dispatch<React.SetStateAction<any[]>>,
|
||||
resetChatHistory: () => void,
|
||||
): {
|
||||
handleOrganizationSelect: (
|
||||
organizationId: string | null,
|
||||
organizationName: string,
|
||||
) => Promise<void>;
|
||||
handleConfigSelect: (config: ConfigOption) => Promise<void>;
|
||||
handleModelSelect: (model: ModelOption) => Promise<void>;
|
||||
} {
|
||||
const { handleOrganizationSelect } = useOrganizationSelector({
|
||||
onMessage: (message) => {
|
||||
setMessages((prev) => [...prev, message]);
|
||||
},
|
||||
onChatReset: resetChatHistory,
|
||||
});
|
||||
|
||||
const { handleConfigSelect } = useConfigSelector({
|
||||
configPath,
|
||||
onMessage: (message) => {
|
||||
setMessages((prev) => [...prev, message]);
|
||||
},
|
||||
onChatReset: resetChatHistory,
|
||||
});
|
||||
|
||||
const { handleModelSelect } = useModelSelector({
|
||||
onMessage: (message) => {
|
||||
setMessages((prev) => [...prev, message]);
|
||||
},
|
||||
});
|
||||
|
||||
return {
|
||||
handleOrganizationSelect,
|
||||
handleConfigSelect,
|
||||
handleModelSelect,
|
||||
};
|
||||
}
|
||||
17
src/ui/types/selectorTypes.ts
Normal file
17
src/ui/types/selectorTypes.ts
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
/**
|
||||
* Type definitions for selectors - compatible with existing hook interfaces
|
||||
*/
|
||||
|
||||
import type { SelectorOption } from "../Selector.js";
|
||||
|
||||
export interface ConfigOption extends SelectorOption {
|
||||
type: "local" | "assistant" | "create";
|
||||
slug?: string;
|
||||
}
|
||||
|
||||
export interface ModelOption {
|
||||
id: string;
|
||||
name: string;
|
||||
index: number;
|
||||
provider: string;
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue