fix: inline --rule improvements and fix msg queue behavior (#7939)

* fix: multi-line inline --rule values now work with cli

* fix: queue behavior

* fix: tests

* Update extensions/cli/src/ui/UserInput.tsx

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>

* fix: rename method

* fix: explicit pattern for hub slugs

---------

Co-authored-by: cubic-dev-ai[bot] <191113872+cubic-dev-ai[bot]@users.noreply.github.com>
This commit is contained in:
Nate Sesti 2025-09-23 23:39:59 -07:00 • committed by GitHub
parent e48921329e
commit 89e1ff2d6b
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 111 additions and 124 deletions

View file

@ -119,9 +119,7 @@ export interface ServerState {
model: any;
isProcessing: boolean;
lastActivity: number;
messageQueue: string[];
currentAbortController: AbortController | null;
shouldInterrupt: boolean;
serverRunning: boolean;
pendingPermission: PendingPermission | null;
systemMessage?: string;

View file

@ -17,6 +17,7 @@ import {
ModelServiceState,
} from "../services/types.js";
import { createSession, getSessionPersistenceSnapshot } from "../session.js";
import { messageQueue } from "../stream/messageQueue.js";
import { constructSystemMessage } from "../systemMessage.js";
import { telemetryService } from "../telemetry/telemetryService.js";
import { gracefulExit } from "../util/exit.js";
@ -138,9 +139,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
model,
isProcessing: false,
lastActivity: Date.now(),
messageQueue: [],
currentAbortController: null,
shouldInterrupt: false,
serverRunning: true,
pendingPermission: null,
};
@ -185,7 +184,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
res.json({
session: state.session, // Return session directly instead of converting
isProcessing: state.isProcessing,
messageQueueLength: state.messageQueue.length,
messageQueueLength: messageQueue.getQueueLength(),
pendingPermission: state.pendingPermission,
});
});
@ -200,17 +199,11 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
}
// Queue the message
state.messageQueue.push(message);
// If currently processing, set interrupt flag
if (state.isProcessing && state.currentAbortController) {
state.shouldInterrupt = true;
}
await messageQueue.enqueueMessage(message);
res.json({
queued: true,
position: state.messageQueue.length,
willInterrupt: state.shouldInterrupt,
position: messageQueue.getQueueLength(),
});
// Process messages if not already processing
@ -303,9 +296,6 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
state.currentAbortController.abort();
}
// Clear the message queue
state.messageQueue = [];
// Clean up intervals
if (inactivityChecker) {
clearInterval(inactivityChecker);
@ -325,7 +315,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
setTimeout(handleExitResponse, 100);
});
const server = app.listen(port, () => {
const server = app.listen(port, async () => {
console.log(chalk.green(`Server started on http://localhost:${port}`));
console.log(chalk.dim("Endpoints:"));
console.log(chalk.dim(" GET /state - Get current agent state"));
@ -354,7 +344,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
// If initial prompt provided, queue it for processing
if (actualPrompt) {
console.log(chalk.dim("\nProcessing initial prompt..."));
state.messageQueue.push(actualPrompt);
await messageQueue.enqueueMessage(actualPrompt);
processMessages(state, llmApi);
}
});
@ -383,10 +373,14 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
async function processMessages(state: ServerState, llmApi: any) {
let processedMessage = false;
while (state.messageQueue.length > 0 && state.serverRunning) {
const userMessage = state.messageQueue.shift()!;
while (state.serverRunning) {
const queuedMessage = messageQueue.getNextMessage();
if (!queuedMessage) {
break;
}
const userMessage = queuedMessage.message;
state.isProcessing = true;
state.shouldInterrupt = false;
state.lastActivity = Date.now();
processedMessage = true;
@ -410,7 +404,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
state,
llmApi,
state.currentAbortController,
() => state.shouldInterrupt,
() => false,
);
// No direct persistence here; ChatHistoryService handles persistence when appropriate
@ -443,7 +437,7 @@ export async function serve(prompt?: string, options: ServeOptions = {}) {
if (
processedMessage &&
state.serverRunning &&
state.messageQueue.length === 0
messageQueue.getQueueLength() === 0
) {
await storageSyncService.markAgentStatusUnread();
}

View file

@ -1,12 +1,15 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import {
import * as hubLoader from "./hubLoader.js";
const {
loadPackageFromHub,
mcpProcessor,
modelProcessor,
promptProcessor,
ruleProcessor,
} from "./hubLoader.js";
processRule,
} = hubLoader;
// Store the original fetch before any mocking
const originalFetch = global.fetch;
@ -136,6 +139,46 @@ describe("hubLoader", () => {
});
});
describe("processRule", () => {
beforeEach(() => {
// Ensure mocks are set up properly for processRule tests
global.fetch = mockFetch;
});
it("should treat multi-line strings as inline rules", async () => {
const loadRuleSpy = vi
.spyOn(hubLoader, "loadRuleFromHub")
.mockResolvedValue("hub-content");
const multilineRule = "Line one\nEnsure /tmp is ignored\nFinal line";
const result = await processRule(multilineRule);
expect(result).toBe(multilineRule);
expect(loadRuleSpy).not.toHaveBeenCalled();
loadRuleSpy.mockRestore();
});
it("should still treat owner/package strings as hub slugs", async () => {
// Mock fetch to return a proper response for this test
const JSZip = (await import("jszip")).default;
const zip = new JSZip();
zip.file("rule.md", "hub-content");
const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
mockFetch.mockResolvedValueOnce({
ok: true,
arrayBuffer: () => Promise.resolve(zipBuffer),
} as Response);
const slug = "owner/package";
const result = await processRule(slug);
expect(result).toBe("hub-content");
expect(mockFetch).toHaveBeenCalled();
});
});
describe("processors", () => {
it("should define rule processor correctly", () => {
expect(ruleProcessor.type).toBe("rule");

View file

@ -3,6 +3,11 @@ import JSZip from "jszip";
import { env } from "./env.js";
import { logger } from "./util/logger.js";
/**
* Pattern to match valid hub slugs (owner/package format)
*/
const HUB_SLUG_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
/**
* Hub package type definitions
*/
@ -220,28 +225,23 @@ export const loadPromptFromHub = (slug: string) =>
* Process a rule specification - supports file paths, hub slugs, or direct content
*/
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 await loadRuleFromHub(ruleSpec);
}
const trimmedRuleSpec = ruleSpec.trim();
const hasNewline = /[\r\n]/.test(ruleSpec);
// If it looks like a file path
if (
ruleSpec.startsWith(".") ||
ruleSpec.startsWith("/") ||
ruleSpec.includes("/") ||
ruleSpec.includes("\\") ||
/\.[a-zA-Z]+$/.test(ruleSpec) // Has file extension at the end
) {
// If it looks like a file path (single line, typical path indicators)
const looksLikePath =
!hasNewline &&
(trimmedRuleSpec.startsWith(".") ||
trimmedRuleSpec.startsWith("/") ||
trimmedRuleSpec.includes("\\") ||
/\.[a-zA-Z]+$/.test(trimmedRuleSpec));
if (looksLikePath) {
const fs = await import("fs");
const path = await import("path");
try {
const absolutePath = path.resolve(ruleSpec);
const absolutePath = path.resolve(trimmedRuleSpec);
if (!fs.existsSync(absolutePath)) {
throw new Error(`Rule file not found: ${ruleSpec}`);
}
@ -253,6 +253,23 @@ export async function processRule(ruleSpec: string): Promise<string> {
}
}
// Check if it might be a hub slug (contains "/" and is a single line)
if (!hasNewline && trimmedRuleSpec.includes("/")) {
const parts = trimmedRuleSpec.split("/");
// If it's exactly 2 parts and matches hub slug pattern, treat as hub slug
if (parts.length === 2 && HUB_SLUG_PATTERN.test(trimmedRuleSpec)) {
return await loadRuleFromHub(trimmedRuleSpec);
}
// If it has more than 2 parts, it's an invalid hub slug
if (parts.length > 2) {
throw new Error(
`Invalid hub slug format. Expected "owner/package", got: ${trimmedRuleSpec}`,
);
}
}
// Otherwise, treat it as direct string content
return ruleSpec;
}

View file

@ -1,4 +1,4 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { describe, expect, it, vi } from "vitest";
vi.mock("../util/logger.js", () => ({
logger: {
@ -16,11 +16,6 @@ vi.mock("../util/logger.js", () => ({
import { messageQueue } from "./messageQueue.js";
describe("messageQueue", () => {
beforeEach(() => {
// Drain any leftover items from previous tests
while (messageQueue.getAllQueuedMessages()) {}
});
it("enqueues and emits messageQueued", async () => {
const event = new Promise<any>((resolve) =>
messageQueue.once("messageQueued", resolve),
@ -33,30 +28,4 @@ describe("messageQueue", () => {
const queued = await event;
expect(queued.message).toBe("hello world");
});
it("combines messages, merges image maps, writes history, and clears queue", async () => {
const bufA = Buffer.from("A");
const bufB = Buffer.from("B");
const img1 = new Map<string, Buffer>([["a", bufA]]);
const img2 = new Map<string, Buffer>([["b", bufB]]);
const history = { addEntry: vi.fn() } as any;
await messageQueue.enqueueMessage("one", img1);
await messageQueue.enqueueMessage("two", img2, history);
const combined = messageQueue.getAllQueuedMessages();
expect(combined).toBeTruthy();
expect(combined!.message).toBe("one\ntwo");
expect(combined!.imageMap).toBeDefined();
expect(combined!.imageMap!.get("a")).toEqual(bufA);
expect(combined!.imageMap!.get("b")).toEqual(bufB);
// queue should be cleared
expect(messageQueue.getQueueLength()).toBe(0);
// input history should receive the combined message
expect(history.addEntry).toHaveBeenCalledWith("one\ntwo");
});
});

View file

@ -1,12 +1,13 @@
import { EventEmitter } from "events";
import { InputHistory } from "../util/inputHistory.js";
import type { InputHistory } from "../util/inputHistory.js";
import { logger } from "../util/logger.js";
export interface QueuedMessage {
message: string;
imageMap?: Map<string, Buffer>;
timestamp: number;
history?: InputHistory;
}
export interface MessageProcessor {
@ -18,7 +19,6 @@ export interface MessageProcessor {
*/
class MessageQueue extends EventEmitter {
private queue: QueuedMessage[] = [];
private inputHistory: InputHistory | undefined;
constructor() {
super();
@ -27,14 +27,13 @@ class MessageQueue extends EventEmitter {
async enqueueMessage(
message: string,
imageMap?: Map<string, Buffer>,
inputHistory?: InputHistory,
history?: InputHistory,
): Promise<boolean> {
this.inputHistory = inputHistory;
const queuedMessage: QueuedMessage = {
message,
imageMap,
timestamp: Date.now(),
history,
};
this.queue.push(queuedMessage);
@ -48,42 +47,11 @@ class MessageQueue extends EventEmitter {
return true;
}
public getAllQueuedMessages() {
if (this.queue.length === 0) return undefined;
// Combine all queued messages into one
const combinedMessage = this.queue.map((msg) => msg.message).join("\n");
const combinedImageMap = new Map<string, Buffer>();
// Merge all image maps
for (const queuedMsg of this.queue) {
if (queuedMsg.imageMap) {
for (const [key, value] of queuedMsg.imageMap) {
combinedImageMap.set(key, value);
}
}
}
const result = {
message: combinedMessage,
imageMap: combinedImageMap.size > 0 ? combinedImageMap : undefined,
timestamp: Date.now(),
};
// Add to input history and clear the queue
this.inputHistory?.addEntry(combinedMessage);
this.queue = [];
logger.debug("MessageQueue: All messages dequeued and combined", {
combinedLength: combinedMessage.length,
queueLength: this.queue.length,
});
return result;
}
public getLatestMessage() {
return this.getAllQueuedMessages();
/**
* Dequeues and returns the next message to be processed (FIFO - oldest first)
*/
public getNextMessage(): QueuedMessage | undefined {
return this.queue.shift();
}
getQueueLength(): number {

View file

@ -548,16 +548,14 @@ const UserInput: React.FC<UserInputProps> = ({
textBuffer.expandAllPasteBlocks();
const submittedText = textBuffer.text.trim();
if (isWaitingForResponse || isCompacting) {
inputHistory.addEntry(submittedText);
// We don't queue, we just send in remote mode because the server handles queueing
if (!isRemoteMode && (isWaitingForResponse || isCompacting)) {
// Process message later when LLM has responded or compaction is complete
void messageQueue.enqueueMessage(
submittedText,
imageMap,
inputHistory,
);
void messageQueue.enqueueMessage(submittedText, imageMap);
} else {
// Submit with images
inputHistory.addEntry(submittedText);
onSubmit(submittedText, imageMap);
}

View file

@ -337,13 +337,13 @@ export function useChat({
// Check if there are queued messages and process them after a microtask delay
// This ensures the GUI state has been updated before processing the next message
const queuedMessageData = messageQueue.getLatestMessage();
const queuedMessageData = messageQueue.getNextMessage();
if (queuedMessageData) {
const { message: latestQueuedMessage, imageMap } = queuedMessageData;
logger.debug("processing queued message", { latestQueuedMessage });
// Clear queued messages from display since they're about to be processed
// Note: messageQueue.getLatestMessage() already cleared the actual queue
// Note: messageQueue.getNextMessage() already cleared the actual queue
setQueuedMessages([]);
await new Promise((resolve) => setTimeout(resolve, 100)); // add timeout for react to render the tui