Merge pull request #73 from continuedev/some-fixes

fix: useMemo instead of useEffect
This commit is contained in:
Nate Sesti 2025-07-20 01:34:28 -07:00 • committed by GitHub
commit 5a2861cf8e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
19 changed files with 725 additions and 195 deletions

56
package-lock.json generated
View file

@ -23,6 +23,7 @@
"glob": "^11.0.3",
"ignore-walk": "^7.0.0",
"ink": "^6.0.1",
"jszip": "^3.10.1",
"lowlight": "^3.3.0",
"minimatch": "^10.0.3",
"node-fetch": "^3.3.2",
@ -48,6 +49,7 @@
"@types/ignore-walk": "^4.0.3",
"@types/ink-testing-library": "^1.0.4",
"@types/jest": "^29.5.14",
"@types/jszip": "^3.4.0",
"@types/nock": "^10.0.3",
"@types/readline-sync": "^1.4.8",
"conventional-changelog-conventionalcommits": "^9.1.0",
@ -4215,6 +4217,16 @@
"pretty-format": "^29.0.0"
}
},
"node_modules/@types/jszip": {
"version": "3.4.0",
"resolved": "https://registry.npmjs.org/@types/jszip/-/jszip-3.4.0.tgz",
"integrity": "sha512-GFHqtQQP3R4NNuvZH3hNCYD0NbyBZ42bkN7kO3NDrU/SnvIZWMS8Bp38XCsRKBT5BXvgm0y1zqpZWp/ZkRzBzg==",
"dev": true,
"license": "MIT",
"dependencies": {
"jszip": "*"
}
},
"node_modules/@types/keygrip": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/@types/keygrip/-/keygrip-1.0.6.tgz",
@ -5653,7 +5665,6 @@
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz",
"integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==",
"dev": true,
"license": "MIT"
},
"node_modules/cors": {
@ -7594,6 +7605,12 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/immediate": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz",
"integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==",
"license": "MIT"
},
"node_modules/import-fresh": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz",
@ -8177,7 +8194,6 @@
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz",
"integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==",
"dev": true,
"license": "MIT"
},
"node_modules/isexe": {
@ -9668,6 +9684,18 @@
"graceful-fs": "^4.1.6"
}
},
"node_modules/jszip": {
"version": "3.10.1",
"resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz",
"integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==",
"license": "(MIT OR GPL-3.0-or-later)",
"dependencies": {
"lie": "~3.3.0",
"pako": "~1.0.2",
"readable-stream": "~2.3.6",
"setimmediate": "^1.0.5"
}
},
"node_modules/kleur": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/kleur/-/kleur-3.0.3.tgz",
@ -9700,6 +9728,15 @@
"node": ">=6"
}
},
"node_modules/lie": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz",
"integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==",
"license": "MIT",
"dependencies": {
"immediate": "~3.0.5"
}
},
"node_modules/lines-and-columns": {
"version": "1.2.4",
"resolved": "https://registry.npmjs.org/lines-and-columns/-/lines-and-columns-1.2.4.tgz",
@ -13320,6 +13357,12 @@
"integrity": "sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw==",
"license": "BlueOak-1.0.0"
},
"node_modules/pako": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz",
"integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==",
"license": "(MIT AND Zlib)"
},
"node_modules/parent-module": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz",
@ -13679,7 +13722,6 @@
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
"integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==",
"dev": true,
"license": "MIT"
},
"node_modules/prompts": {
@ -13980,7 +14022,6 @@
"version": "2.3.8",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz",
"integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==",
"dev": true,
"license": "MIT",
"dependencies": {
"core-util-is": "~1.0.0",
@ -13996,7 +14037,6 @@
"version": "5.1.2",
"resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz",
"integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==",
"dev": true,
"license": "MIT"
},
"node_modules/readline-sync": {
@ -14450,6 +14490,12 @@
"node": ">= 18"
}
},
"node_modules/setimmediate": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz",
"integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==",
"license": "MIT"
},
"node_modules/setprototypeof": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",

View file

@ -45,6 +45,7 @@
"glob": "^11.0.3",
"ignore-walk": "^7.0.0",
"ink": "^6.0.1",
"jszip": "^3.10.1",
"lowlight": "^3.3.0",
"minimatch": "^10.0.3",
"node-fetch": "^3.3.2",
@ -67,6 +68,7 @@
"@types/ignore-walk": "^4.0.3",
"@types/ink-testing-library": "^1.0.4",
"@types/jest": "^29.5.14",
"@types/jszip": "^3.4.0",
"@types/nock": "^10.0.3",
"@types/readline-sync": "^1.4.8",
"conventional-changelog-conventionalcommits": "^9.1.0",

View file

@ -1,4 +1,5 @@
import { parseArgs } from "./args.js";
import { jest } from '@jest/globals';
import { parseArgs, processRule } from "./args.js";
describe("parseArgs", () => {
const originalArgv = process.argv;
@ -245,3 +246,196 @@ describe("parseArgs", () => {
]);
});
});
describe("processRule (loadRuleFromHub integration)", () => {
// Mock fetch for hub tests
const originalFetch = global.fetch;
const mockFetch = jest.fn() as jest.MockedFunction<typeof fetch>;
beforeAll(() => {
global.fetch = mockFetch;
});
afterAll(() => {
global.fetch = originalFetch;
});
beforeEach(() => {
mockFetch.mockClear();
});
describe("loadRuleFromHub", () => {
it("should successfully load a rule from the Continue Hub", async () => {
// Create a mock zip file containing a markdown rule
const JSZip = (await import("jszip")).default;
const zip = new JSZip();
const ruleContent = "# Sentry Next.js Rule\n\nThis is a sample rule for Sentry integration with Next.js applications.";
zip.file("rule.md", ruleContent);
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
// Mock successful fetch response
mockFetch.mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(zipBuffer),
} as Response);
const result = await processRule("continuedev/sentry-nextjs");
expect(result).toBe(ruleContent);
expect(mockFetch).toHaveBeenCalledWith(
new URL("v0/continuedev/sentry-nextjs/latest/download", "https://api.continue.dev/")
);
});
it("should handle HTTP errors when loading from hub", async () => {
mockFetch.mockResolvedValue({
ok: false,
status: 404,
statusText: "Not Found",
} as Response);
await expect(processRule("continuedev/nonexistent-rule")).rejects.toThrow(
'Failed to load rule from hub "continuedev/nonexistent-rule": HTTP 404: Not Found'
);
});
it("should handle network errors when loading from hub", async () => {
mockFetch.mockRejectedValue(new Error("Network error"));
await expect(processRule("continuedev/sentry-nextjs")).rejects.toThrow(
'Failed to load rule from hub "continuedev/sentry-nextjs": Network error'
);
});
it("should handle invalid slug format", async () => {
// "invalid-slug" doesn't contain "/" so it's treated as direct content, not a hub slug
// Let's test with a slug that has wrong format but contains "/"
await expect(processRule("invalid/slug/too/many/parts")).rejects.toThrow(
'Invalid hub slug format. Expected "owner/package", got: invalid/slug/too/many/parts'
);
});
it("should handle empty zip file", async () => {
const JSZip = (await import("jszip")).default;
const zip = new JSZip();
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
mockFetch.mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(zipBuffer),
} as Response);
await expect(processRule("continuedev/empty-rule")).rejects.toThrow(
'Failed to load rule from hub "continuedev/empty-rule": No rule content found in downloaded zip file'
);
});
it("should handle zip with only directories", async () => {
const JSZip = (await import("jszip")).default;
const zip = new JSZip();
zip.folder("docs"); // Create a directory but no files
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
mockFetch.mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(zipBuffer),
} as Response);
await expect(processRule("continuedev/directory-only")).rejects.toThrow(
'Failed to load rule from hub "continuedev/directory-only": No rule content found in downloaded zip file'
);
});
it("should prefer markdown files and ignore other file types", async () => {
const JSZip = (await import("jszip")).default;
const zip = new JSZip();
const mdContent = "# Main Rule\n\nThis is the markdown rule content.";
const txtContent = "This is just a text file.";
zip.file("README.txt", txtContent);
zip.file("rule.md", mdContent);
zip.file("package.json", '{"name": "test"}');
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
mockFetch.mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(zipBuffer),
} as Response);
const result = await processRule("continuedev/mixed-files");
expect(result).toBe(mdContent);
});
it("should handle multiple markdown files and use the first one", async () => {
const JSZip = (await import("jszip")).default;
const zip = new JSZip();
const rule1Content = "# First Rule\n\nThis is the first rule.";
const rule2Content = "# Second Rule\n\nThis is the second rule.";
zip.file("rule1.md", rule1Content);
zip.file("rule2.md", rule2Content);
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
mockFetch.mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(zipBuffer),
} as Response);
const result = await processRule("continuedev/multiple-rules");
// Should use the first markdown file found (alphabetically)
expect(result).toBe(rule1Content);
});
it("should handle malformed zip files", async () => {
const invalidZipBuffer = new ArrayBuffer(10);
mockFetch.mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(invalidZipBuffer),
} as Response);
await expect(processRule("continuedev/corrupted-zip")).rejects.toThrow(
'Failed to load rule from hub "continuedev/corrupted-zip"'
);
});
});
describe("processRule logic", () => {
it("should identify hub slugs correctly", async () => {
const JSZip = (await import("jszip")).default;
const zip = new JSZip();
zip.file("rule.md", "# Hub Rule");
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
mockFetch.mockResolvedValue({
ok: true,
arrayBuffer: () => Promise.resolve(zipBuffer),
} as Response);
const result = await processRule("owner/package");
expect(result).toBe("# Hub Rule");
expect(mockFetch).toHaveBeenCalled();
});
it("should treat direct strings as content", async () => {
const directContent = "This is direct rule content";
const result = await processRule(directContent);
expect(result).toBe(directContent);
expect(mockFetch).not.toHaveBeenCalled();
});
it("should distinguish between hub slugs and file paths", async () => {
// This would be treated as a file path, not a hub slug
// since it starts with "."
await expect(processRule("./owner/package")).rejects.toThrow(
'Failed to read rule file "./owner/package": Rule file not found'
);
expect(mockFetch).not.toHaveBeenCalled();
});
});
});

View file

@ -1,5 +1,7 @@
import * as fs from "fs";
import JSZip from "jszip";
import * as path from "path";
import { env } from "./env.js";
export interface CommandLineArgs {
isHeadless: boolean;
@ -29,13 +31,53 @@ function loadRuleFromFile(filePath: string): string {
}
/**
* Load rule content from hub.continue.dev (not yet implemented)
* Load rule content from hub.continue.dev
* @param slug - The slug in format "owner/package"
* @returns The rule content from the hub
*/
function loadRuleFromHub(slug: string): string {
// TODO: Implement hub integration
throw new Error(`Hub rules not yet supported: ${slug}`);
async function loadRuleFromHub(slug: string): Promise<string> {
const parts = slug.split("/");
if (parts.length !== 2) {
throw new Error(
`Invalid hub slug format. Expected "owner/package", got: ${slug}`
);
}
const [ownerSlug, ruleSlug] = parts;
const hubUrl = env.apiBase;
const downloadUrl = new URL(
`v0/${ownerSlug}/${ruleSlug}/latest/download`,
hubUrl
);
try {
const response = await fetch(downloadUrl);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
// The API returns a zip file, so we need to extract the rule content
const arrayBuffer = await response.arrayBuffer();
const zip = new JSZip();
const zipContents = await zip.loadAsync(arrayBuffer);
// Find the first .md or .txt file (rule content)
const ruleFiles = Object.keys(zipContents.files).filter(
(filename) => filename.endsWith(".md") && !zipContents.files[filename].dir
);
if (ruleFiles.length === 0) {
throw new Error("No rule content found in downloaded zip file");
}
// Use the first rule file found - TODO support multiple rules and parse frontmatter
const ruleFile = zipContents.files[ruleFiles[0]];
const content = await ruleFile.async("text");
return content;
} catch (error: any) {
throw new Error(`Failed to load rule from hub "${slug}": ${error.message}`);
}
}
/**
@ -43,14 +85,14 @@ function loadRuleFromHub(slug: string): string {
* @param ruleSpec - Can be a file path, hub slug, or direct string content
* @returns The processed rule content
*/
export function processRule(ruleSpec: string): string {
export async function processRule(ruleSpec: string): Promise<string> {
// If it looks like a hub slug (contains / but doesn't start with . or /)
if (
ruleSpec.includes("/") &&
!ruleSpec.startsWith(".") &&
!ruleSpec.startsWith("/")
) {
return loadRuleFromHub(ruleSpec);
return await loadRuleFromHub(ruleSpec);
}
// If it looks like a file path (contains . or / or ends with common file extensions)

View file

@ -231,6 +231,7 @@ async function requestDeviceAuthorization(): Promise<DeviceAuthorizationResponse
try {
const params = new URLSearchParams({
client_id: env.workOsClientId,
screen_hint: "sign-up",
});
// Use WorkOS User Management device authorization endpoint
@ -426,46 +427,39 @@ export async function login(): Promise<AuthConfig> {
};
}
console.info(chalk.white("\nSigning in with Continue..."));
// Request device authorization
const deviceAuth = await requestDeviceAuthorization();
console.info(
chalk.white(`Your authentication code: ${chalk.bold(deviceAuth.user_code)}`)
);
console.info(
chalk.dim(
`If the browser doesn't automatically open, use this link: ${deviceAuth.verification_uri_complete}`
)
);
// Try to open the complete verification URL in browser
try {
console.info(chalk.white("\nSigning in with Continue..."));
// Request device authorization
const deviceAuth = await requestDeviceAuthorization();
console.info(
chalk.white(
`Your authentication code: ${chalk.bold(deviceAuth.user_code)}`
)
);
console.info(
chalk.dim(
`If the browser doesn't automatically open, use this link: ${deviceAuth.verification_uri_complete}`
)
);
// Try to open the complete verification URL in browser
try {
await open(deviceAuth.verification_uri_complete);
} catch (error) {
console.info(chalk.yellow("Unable to open browser automatically"));
}
console.info(chalk.dim("\nWaiting for confirmation..."));
// Poll for token
const authConfig = await pollForDeviceToken(
deviceAuth.device_code,
deviceAuth.interval,
deviceAuth.expires_in
);
console.info(chalk.white("✅ Success!"));
return authConfig;
} catch (error: any) {
console.error(chalk.red("Authentication error:"), error.message || error);
throw error;
await open(deviceAuth.verification_uri_complete);
} catch (error) {
console.info(chalk.yellow("Unable to open browser automatically"));
}
console.info(chalk.dim("\nWaiting for confirmation..."));
// Poll for token
const authConfig = await pollForDeviceToken(
deviceAuth.device_code,
deviceAuth.interval,
deviceAuth.expires_in
);
console.info(chalk.white("✅ Success!"));
return authConfig;
}
/**

View file

@ -10,8 +10,10 @@ import { loadSession, saveSession } from "../session.js";
import { streamChatResponse } from "../streamChatResponse.js";
import { constructSystemMessage } from "../systemMessage.js";
import { startTUIChat } from "../ui/index.js";
import { safeStdout } from "../util/consoleOverride.js";
import { formatError } from "../util/formatError.js";
import logger from "../util/logger.js";
import { getVersion } from "../version.js";
export interface ChatOptions {
headless?: boolean;
@ -26,8 +28,13 @@ async function initializeChat(options: ChatOptions) {
// Use onboarding flow for initialization
if (!options.headless) {
console.log(chalk.white(CONTINUE_ASCII_ART));
console.info(chalk.gray(`v${getVersion()}\n`));
}
const result = await initializeWithOnboarding(authConfig, options.config);
const result = await initializeWithOnboarding(
authConfig,
options.config,
options.rule
);
// Ensure organization is selected if authenticated
let finalAuthConfig = authConfig;
@ -90,7 +97,7 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
// If no session loaded or not resuming, initialize with system message
if (chatHistory.length === 0) {
const rulesSystemMessage = ""; // TODO //assistant.systemMessage;
const systemMessage = constructSystemMessage(
const systemMessage = await constructSystemMessage(
rulesSystemMessage,
options.rule
);
@ -131,9 +138,9 @@ export async function chat(prompt?: string, options: ChatOptions = {}) {
abortController
);
// In headless mode, only print the final response
// In headless mode, only print the final response using safe stdout
if (options.headless && finalResponse.trim()) {
logger.info(finalResponse);
safeStdout(finalResponse + "\n");
}
// Save session after each successful response

View file

@ -4,11 +4,15 @@ import * as path from "path";
import { logout as workosLogout } from "../auth/workos.js";
export async function logout() {
const onboardingFlagPath = path.join(
os.homedir(),
".continue",
".onboarding_complete"
);
workosLogout();
// Remove onboarding completion flag so user will go through onboarding again
const onboardingFlagPath = path.join(os.homedir(), ".continue", ".onboarding_complete");
if (fs.existsSync(onboardingFlagPath)) {
fs.unlinkSync(onboardingFlagPath);
}
}
}

View file

@ -137,7 +137,22 @@ export async function loadConfig(
organizationId: organizationId ?? undefined,
});
if (assistants.length === 0) {
// In case the user doesn't have any assistants, we fall back to a default - TODO
const resp = await apiClient.getAssistant({
ownerSlug: "continuedev",
packageSlug: "default-agent",
organizationId: organizationId ?? undefined,
});
if (!resp.configResult.config) {
throw new Error("Failed to load default agent.");
}
return resp.configResult.config as AssistantUnrolled;
}
const result = assistants[0].configResult;
if (result.errors?.length || !result.config) {
throw new Error(
result.errors?.join("\n") ?? "Failed to load assistant."

View file

@ -4,8 +4,9 @@ import { Command } from "commander";
import { chat } from "./commands/chat.js";
import { login } from "./commands/login.js";
import { logout } from "./commands/logout.js";
import { getVersion } from "./version.js";
import { configureConsoleForHeadless } from "./util/consoleOverride.js";
import logger from "./util/logger.js";
import { getVersion } from "./version.js";
// Add global error handlers to prevent uncaught errors from crashing the process
process.on("unhandledRejection", (reason, promise) => {
@ -47,15 +48,26 @@ program
[] as string[]
)
.action(async (prompt, options) => {
// Configure console overrides FIRST, before any other logging
const isHeadless = options.print;
configureConsoleForHeadless(isHeadless);
if (options.verbose) {
logger.setLevel('debug');
logger.setLevel("debug");
const logPath = logger.getLogPath();
const sessionId = logger.getSessionId();
console.log(`Verbose logging enabled (session: ${sessionId})`);
console.log(`Logs: ${logPath}`);
console.log(`Filter this session: grep '\\[${sessionId}\\]' ${logPath}`);
logger.debug('Verbose logging enabled');
// In headless mode, suppress these verbose logs
if (!isHeadless) {
console.log(`Verbose logging enabled (session: ${sessionId})`);
console.log(`Logs: ${logPath}`);
console.log(
`Filter this session: grep '\\[${sessionId}\\]' ${logPath}`
);
}
logger.debug("Verbose logging enabled");
}
options.headless = options.print;
options.print = undefined;
await chat(prompt, options);
});

View file

@ -1,9 +1,25 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { type AssistantConfig } from "@continuedev/sdk";
import chalk from "chalk";
import { readFileSync } from "fs";
import { dirname, join } from "path";
import { fileURLToPath } from "url";
import { getAllSlashCommands } from "./commands/commands.js";
import { MCPService } from "./mcp.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
function getVersion(): string {
try {
const packagePath = join(__dirname, "..", "package.json");
const packageJson = JSON.parse(readFileSync(packagePath, "utf-8"));
return packageJson.version;
} catch (error) {
return "unknown";
}
}
export function loadSystemMessage(
assistant: AssistantConfig
): string | undefined {

View file

@ -5,6 +5,7 @@ import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import * as readlineSync from "readline-sync";
import { processRule } from "./args.js";
import { AuthConfig, isAuthenticated, login } from "./auth/workos.js";
import { initialize } from "./config.js";
import { MCPService } from "./mcp.js";
@ -212,9 +213,58 @@ export async function markOnboardingComplete(): Promise<void> {
fs.writeFileSync(flagPath, new Date().toISOString());
}
/**
* Process rules and inject them into the assistant config
* @param config - The assistant config to modify
* @param rules - Array of rule specifications to process and inject
* @returns The modified config with injected rules
*/
async function injectRulesIntoConfig(
config: AssistantUnrolled,
rules: string[]
): Promise<AssistantUnrolled> {
if (!rules || rules.length === 0) {
return config;
}
let processedRules: string[] = [];
for (const ruleSpec of rules) {
try {
const processedRule = await processRule(ruleSpec);
processedRules.push(processedRule);
} catch (error: any) {
console.warn(
chalk.yellow(
`Warning: Failed to process rule "${ruleSpec}": ${error.message}`
)
);
}
}
if (processedRules.length === 0) {
return config;
}
// Clone the config to avoid mutating the original
const modifiedConfig = { ...config };
// Combine processed rules with existing system message if the config has one
const existingSystemMessage = (modifiedConfig as any).systemMessage || "";
const rulesSection = processedRules.join("\n\n");
if (existingSystemMessage) {
(modifiedConfig as any).systemMessage = `${existingSystemMessage}\n\n${rulesSection}`;
} else {
(modifiedConfig as any).systemMessage = rulesSection;
}
return modifiedConfig;
}
export async function initializeWithOnboarding(
authConfig: AuthConfig,
configPath: string | undefined
configPath: string | undefined,
rules?: string[]
): Promise<OnboardingResult> {
const firstTime = await isFirstTime();
@ -229,5 +279,10 @@ export async function initializeWithOnboarding(
result = await runNormalFlow(configPath, authConfig);
}
// Inject rules into the config if provided
if (rules && rules.length > 0) {
result.config = await injectRulesIntoConfig(result.config, rules);
}
return result;
}

View file

@ -1,9 +1,9 @@
import { constructSystemMessage } from './systemMessage.js';
describe('constructSystemMessage', () => {
it('should return base system message with rules when rulesSystemMessage is provided', () => {
it('should return base system message with rules when rulesSystemMessage is provided', async () => {
const rulesMessage = 'These are the rules for the assistant.';
const result = constructSystemMessage(rulesMessage);
const result = await constructSystemMessage(rulesMessage);
expect(result).toContain('You are an agent in the Continue CLI');
expect(result).toContain('<context name="userRules">');
@ -11,17 +11,17 @@ describe('constructSystemMessage', () => {
expect(result).toContain('</context>');
});
it('should return base system message with agent content when no rules but agent file exists', () => {
it('should return base system message with agent content when no rules but agent file exists', async () => {
// The implementation checks for agent files like AGENTS.md which exists in this project
const result = constructSystemMessage('');
const result = await constructSystemMessage('');
expect(result).toContain('You are an agent in the Continue CLI');
expect(result).toContain('<context name="userRules">');
expect(result).toContain('AGENTS.md');
});
it('should include base system message components', () => {
const result = constructSystemMessage('');
it('should include base system message components', async () => {
const result = await constructSystemMessage('');
expect(result).toContain('You are an agent in the Continue CLI');
expect(result).toContain('<env>');
@ -30,72 +30,72 @@ describe('constructSystemMessage', () => {
expect(result).toContain('Any file paths you return in your final response MUST be absolute');
});
it('should handle whitespace-only rules message', () => {
const result = constructSystemMessage(' ');
it('should handle whitespace-only rules message', async () => {
const result = await constructSystemMessage(' ');
expect(result).toContain('You are an agent in the Continue CLI');
expect(result).toContain('<context name="userRules">');
});
it('should include working directory information', () => {
const result = constructSystemMessage('');
it('should include working directory information', async () => {
const result = await constructSystemMessage('');
expect(result).toContain('Working directory:');
expect(result).toContain('<env>');
});
it('should include platform information', () => {
const result = constructSystemMessage('');
it('should include platform information', async () => {
const result = await constructSystemMessage('');
expect(result).toContain('Platform:');
});
it('should include current date', () => {
const result = constructSystemMessage('');
it('should include current date', async () => {
const result = await constructSystemMessage('');
expect(result).toContain('Today\'s date:');
expect(result).toContain(new Date().toISOString().split('T')[0]);
});
it('should format rules section correctly', () => {
it('should format rules section correctly', async () => {
const rulesMessage = 'Rule 1: Do this\nRule 2: Do that';
const result = constructSystemMessage(rulesMessage);
const result = await constructSystemMessage(rulesMessage);
expect(result).toContain('<context name="userRules">');
expect(result).toContain(rulesMessage);
expect(result).toContain('</context>');
});
it('should handle multiline rules message', () => {
it('should handle multiline rules message', async () => {
const rulesMessage = `Rule 1: First rule
Rule 2: Second rule
Rule 3: Third rule`;
const result = constructSystemMessage(rulesMessage);
const result = await constructSystemMessage(rulesMessage);
expect(result).toContain(rulesMessage);
expect(result).toContain('<context name="userRules">');
expect(result).toContain('</context>');
});
it('should handle special characters in rules message', () => {
it('should handle special characters in rules message', async () => {
const rulesMessage = 'Rule with <special> characters & symbols!';
const result = constructSystemMessage(rulesMessage);
const result = await constructSystemMessage(rulesMessage);
expect(result).toContain(rulesMessage);
expect(result).toContain('<context name="userRules">');
});
it('should handle very long rules message', () => {
it('should handle very long rules message', async () => {
const rulesMessage = 'A'.repeat(1000);
const result = constructSystemMessage(rulesMessage);
const result = await constructSystemMessage(rulesMessage);
expect(result).toContain(rulesMessage);
expect(result).toContain('<context name="userRules">');
});
it('should combine rules and agent content when both are present', () => {
it('should combine rules and agent content when both are present', async () => {
const rulesMessage = 'These are the rules.';
const result = constructSystemMessage(rulesMessage);
const result = await constructSystemMessage(rulesMessage);
expect(result).toContain('<context name="userRules">');
expect(result).toContain(rulesMessage);

View file

@ -99,7 +99,10 @@ ${getGitStatus()}
* @param additionalRules - Additional rules from --rule flags
* @returns The comprehensive system message with base message and rules section
*/
export function constructSystemMessage(rulesSystemMessage: string, additionalRules?: string[]): string {
export async function constructSystemMessage(
rulesSystemMessage: string,
additionalRules?: string[]
): Promise<string> {
const agentFiles = ["AGENTS.md", "AGENT.md", "CLAUDE.md", "CODEX.md"];
let agentContent = "";
@ -123,10 +126,12 @@ export function constructSystemMessage(rulesSystemMessage: string, additionalRul
if (additionalRules && additionalRules.length > 0) {
for (const ruleSpec of additionalRules) {
try {
const processedRule = processRule(ruleSpec);
const processedRule = await processRule(ruleSpec);
processedRules.push(processedRule);
} catch (error: any) {
console.warn(`Warning: Failed to process rule "${ruleSpec}": ${error.message}`);
console.warn(
`Warning: Failed to process rule "${ruleSpec}": ${error.message}`
);
}
}
}
@ -149,7 +154,7 @@ export function constructSystemMessage(rulesSystemMessage: string, additionalRul
// Add processed rules from --rule flags
if (processedRules.length > 0) {
const separator = (rulesSystemMessage || agentContent) ? "\n\n" : "\n";
const separator = rulesSystemMessage || agentContent ? "\n\n" : "\n";
systemMessage += `${separator}${processedRules.join("\n\n")}`;
}

View file

@ -18,25 +18,19 @@ interface FileItem {
const fileCache = new Map<string, FileItem[]>();
let allFiles: FileItem[] = [];
let cacheInitialized = false;
let cacheInitializationPromise: Promise<void> | null = null;
const FileSearchUI: React.FC<FileSearchUIProps> = ({
filter,
selectedIndex,
onSelect,
onFilesUpdated,
}) => {
const [files, setFiles] = useState<FileItem[]>([]);
const [isLoading, setIsLoading] = useState(false);
const initializingRef = useRef(false);
// Initialize cache once
const initializeCache = async () => {
if (cacheInitialized || initializingRef.current) {
return;
}
initializingRef.current = true;
// Initialize cache once
const initializeCache = async (): Promise<void> => {
if (cacheInitialized) {
return;
}
if (cacheInitializationPromise) {
return cacheInitializationPromise;
}
cacheInitializationPromise = (async () => {
try {
// Use a single, more efficient pattern
const patterns = [
@ -127,79 +121,94 @@ const FileSearchUI: React.FC<FileSearchUIProps> = ({
cacheInitialized = true;
} catch (error) {
console.error("Error initializing file cache:", error);
} finally {
initializingRef.current = false;
}
};
})();
return cacheInitializationPromise;
};
// Filter files from cache
const filterFiles = (filterText: string): FileItem[] => {
if (!cacheInitialized) {
return [];
}
// Export function to start indexing proactively
export const startFileIndexing = (): Promise<void> => {
return initializeCache();
};
if (filterText.length === 0) {
// Show most recently modified files when no filter
return allFiles
.sort((a, b) => {
const aFileName = a.path.split('/').pop() || a.path;
const bFileName = b.path.split('/').pop() || b.path;
return aFileName.localeCompare(bFileName);
})
.slice(0, 10);
}
// Filter files from cache
const filterFiles = (filterText: string): FileItem[] => {
if (!cacheInitialized) {
return [];
}
const lowerFilter = filterText.toLowerCase();
// Check cache first
const cacheKey = lowerFilter;
if (fileCache.has(cacheKey)) {
return fileCache.get(cacheKey)!;
}
const filteredFiles = allFiles
.filter((file) => {
return (
file.displayName.toLowerCase().includes(lowerFilter) ||
file.path.toLowerCase().includes(lowerFilter)
);
})
if (filterText.length === 0) {
// Show most recently modified files when no filter
return allFiles
.sort((a, b) => {
const aFileName = a.path.split('/').pop() || a.path;
const bFileName = b.path.split('/').pop() || b.path;
// Prioritize exact matches in file name
const aNameMatch = aFileName.toLowerCase().includes(lowerFilter);
const bNameMatch = bFileName.toLowerCase().includes(lowerFilter);
if (aNameMatch && !bNameMatch) return -1;
if (!aNameMatch && bNameMatch) return 1;
// Then prioritize files that start with the filter
const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter);
const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter);
if (aStartsWith && !bStartsWith) return -1;
if (!aStartsWith && bStartsWith) return 1;
// Finally, sort by file name
return aFileName.localeCompare(bFileName);
})
.slice(0, 10);
}
// Cache the result
fileCache.set(cacheKey, filteredFiles);
// Limit cache size
if (fileCache.size > 100) {
const firstKey = fileCache.keys().next().value;
if (firstKey) {
fileCache.delete(firstKey);
}
const lowerFilter = filterText.toLowerCase();
// Check cache first
const cacheKey = lowerFilter;
if (fileCache.has(cacheKey)) {
return fileCache.get(cacheKey)!;
}
const filteredFiles = allFiles
.filter((file) => {
return (
file.displayName.toLowerCase().includes(lowerFilter) ||
file.path.toLowerCase().includes(lowerFilter)
);
})
.sort((a, b) => {
const aFileName = a.path.split('/').pop() || a.path;
const bFileName = b.path.split('/').pop() || b.path;
// Prioritize exact matches in file name
const aNameMatch = aFileName.toLowerCase().includes(lowerFilter);
const bNameMatch = bFileName.toLowerCase().includes(lowerFilter);
if (aNameMatch && !bNameMatch) return -1;
if (!aNameMatch && bNameMatch) return 1;
// Then prioritize files that start with the filter
const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter);
const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter);
if (aStartsWith && !bStartsWith) return -1;
if (!aStartsWith && bStartsWith) return 1;
// Finally, sort by file name
return aFileName.localeCompare(bFileName);
})
.slice(0, 10);
// Cache the result
fileCache.set(cacheKey, filteredFiles);
// Limit cache size
if (fileCache.size > 100) {
const firstKey = fileCache.keys().next().value;
if (firstKey) {
fileCache.delete(firstKey);
}
}
return filteredFiles;
};
return filteredFiles;
};
const FileSearchUI: React.FC<FileSearchUIProps> = ({
filter,
selectedIndex,
onSelect,
onFilesUpdated,
}) => {
const [files, setFiles] = useState<FileItem[]>([]);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
const searchFiles = async () => {

View file

@ -1,10 +1,8 @@
import { type AssistantConfig } from "@continuedev/sdk";
import { Box, Text } from "ink";
import React, { useEffect, useState } from "react";
import {
getAllSlashCommands,
type SlashCommand,
} from "../commands/commands.js";
import React, { useMemo } from "react";
import { getAllSlashCommands } from "../commands/commands.js";
interface SlashCommandUIProps {
assistant: AssistantConfig;
@ -17,11 +15,11 @@ const SlashCommandUI: React.FC<SlashCommandUIProps> = ({
filter,
selectedIndex,
}) => {
const [allCommands, setAllCommands] = useState<SlashCommand[]>([]);
useEffect(() => {
setAllCommands(getAllSlashCommands(assistant));
}, [assistant]);
// Memoize the slash commands to prevent excessive re-renders
// Only recalculate when assistant.prompts changes
const allCommands = useMemo(() => {
return getAllSlashCommands(assistant);
}, [assistant.prompts]);
// Filter commands based on the current filter
const filteredCommands = allCommands

View file

@ -1,12 +1,13 @@
import { AssistantUnrolled, ModelConfig } from "@continuedev/config-yaml";
import { BaseLlmApi } from "@continuedev/openai-adapters";
import { Box, Text } from "ink";
import React, { useState } from "react";
import React, { useState, useEffect } from "react";
import { loadAuthConfig } from "../auth/workos.js";
import { initialize } from "../config.js";
import { introMessage } from "../intro.js";
import { MCPService } from "../mcp.js";
import ConfigSelector from "./ConfigSelector.js";
import { startFileIndexing } from "./FileSearchUI.js";
import { useChat } from "./hooks/useChat.js";
import { useConfigSelector } from "./hooks/useConfigSelector.js";
import { useMessageRenderer } from "./hooks/useMessageRenderer.js";
@ -50,6 +51,14 @@ const TUIChat: React.FC<TUIChatProps> = ({
} | null>(null);
const [loginToken, setLoginToken] = useState("");
// Start file indexing as soon as the component mounts
useEffect(() => {
// Start indexing files in the background immediately
startFileIndexing().catch((error) => {
console.error("Failed to start file indexing:", error);
});
}, []);
// Custom login prompt handler for TUI
const handleLoginPrompt = (promptText: string): Promise<string> => {
return new Promise((resolve) => {

View file

@ -44,20 +44,20 @@ describe("TUIChat - Basic UI Tests", () => {
});
describe("Loading States", () => {
it("shows loading spinner when loading", async () => {
it("shows UI correctly when loading", async () => {
const { lastFrame, stdin } = render(<TUIChat {...createProps()} />);
// Trigger loading by sending a message
stdin.write("trigger loading");
stdin.write("test message");
stdin.write("\r");
// Give it a moment to start loading
// Give it a moment to process
await new Promise((resolve) => setTimeout(resolve, 50));
const frame = lastFrame();
// The message was submitted (shows in the UI)
expect(frame).toContain("trigger loading");
// Note: The actual loading spinner might not be visible in this test environment
// The UI should still be properly rendered
expect(frame).toContain("Ask anything");
// Note: The actual loading spinner behavior might not be visible in this test environment
});
it("hides loading spinner when not loading", () => {
@ -78,13 +78,10 @@ describe("TUIChat - Basic UI Tests", () => {
const frame = lastFrame();
// Should show the submitted message
expect(frame).toContain("test");
// Should show placeholder message rather than text in input box
expect(frame).toContain(
"Ask anything, @ for context, / for slash commands"
);
});
});
});
});

View file

@ -61,7 +61,15 @@ export function useChat({
rulesSystemMessage,
additionalRules
);
if (systemMessage) {
if (systemMessage instanceof Promise) {
// Handle the promise case - we'll need to initialize this asynchronously
systemMessage.then((resolvedMessage) => {
if (resolvedMessage) {
history.push({ role: "system", content: resolvedMessage });
setChatHistory([...history]);
}
});
} else if (systemMessage) {
history.push({ role: "system", content: systemMessage });
}
}
@ -96,6 +104,25 @@ export function useChat({
Array<{ path: string; content: string }>
>([]);
useEffect(() => {
// Initialize system message asynchronously
const initializeSystemMessage = async () => {
if (chatHistory.length === 0 || !chatHistory.some(msg => msg.role === "system")) {
const rulesSystemMessage = "";
const systemMessage = await constructSystemMessage(
rulesSystemMessage,
additionalRules
);
if (systemMessage) {
const newHistory = [{ role: "system" as const, content: systemMessage }];
setChatHistory(newHistory);
}
}
};
initializeSystemMessage();
}, []);
useEffect(() => {
if (initialPrompt) {
handleUserMessage(initialPrompt);
@ -371,9 +398,9 @@ export function useChat({
setAttachedFiles((prev) => [...prev, { path: filePath, content }]);
};
const resetChatHistory = () => {
const resetChatHistory = async () => {
const rulesSystemMessage = "";
const systemMessage = constructSystemMessage(
const systemMessage = await constructSystemMessage(
rulesSystemMessage,
additionalRules
);
@ -398,4 +425,4 @@ export function useChat({
handleFileAttached,
resetChatHistory,
};
}
}

View file

@ -0,0 +1,98 @@
/**
* Console override utility to prevent unwanted output in headless mode
* This ensures that only intentional stdout output reaches the user
*/
interface ConsoleBackup {
log: typeof console.log;
info: typeof console.info;
warn: typeof console.warn;
error: typeof console.error;
debug: typeof console.debug;
}
let originalConsole: ConsoleBackup | null = null;
let isHeadlessMode = false;
/**
* Override console methods to prevent unwanted output in headless mode
* In headless mode, only console.error and explicitly allowed outputs should reach stdout
*/
export function configureConsoleForHeadless(headless: boolean): void {
isHeadlessMode = headless;
if (headless && !originalConsole) {
// Backup original console methods
originalConsole = {
log: console.log,
info: console.info,
warn: console.warn,
error: console.error,
debug: console.debug,
};
// Override console methods to suppress output in headless mode
console.log = () => {}; // Suppress all console.log
console.info = () => {}; // Suppress all console.info
console.warn = () => {}; // Suppress all console.warn
console.debug = () => {}; // Suppress all console.debug
// Keep console.error for genuine errors, but send to stderr
console.error = (...args: any[]) => {
originalConsole!.error(...args);
};
} else if (!headless && originalConsole) {
// Restore original console methods
console.log = originalConsole.log;
console.info = originalConsole.info;
console.warn = originalConsole.warn;
console.error = originalConsole.error;
console.debug = originalConsole.debug;
originalConsole = null;
}
}
/**
* Safe stdout output that bypasses console overrides
* Use this for intentional output in headless mode
*/
export function safeStdout(message: string): void {
process.stdout.write(message);
}
/**
* Safe stderr output that bypasses console overrides
* Use this for error messages that should always be visible
*/
export function safeStderr(message: string): void {
process.stderr.write(message);
}
/**
* Temporarily restore console for a specific operation
* Useful for debugging or when you need original console behavior
*/
export function withOriginalConsole<T>(fn: () => T): T {
if (!originalConsole || !isHeadlessMode) {
return fn();
}
// Temporarily restore
const tempConsole = { ...console };
Object.assign(console, originalConsole);
try {
return fn();
} finally {
// Restore overrides
Object.assign(console, tempConsole);
}
}
/**
* Check if currently in headless mode
*/
export function isInHeadlessMode(): boolean {
return isHeadlessMode;
}