Elffuss BraidHub

kikocis/continue public

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>
Changeset78599bd09fb681bc527f0a34aa611fc86ec081213182adc05e443e01d5772a0f
AuthorNate Sesti <33237525+sestinj@users.noreply.github.com> · 2025-09-23 23:39 -07:00
CommitterGitHub <noreply@github.com> · 2025-09-23 23:39 -07:00
Parents0e7d07cb2a28

Browse the files at this changeset

8 files changed

modified extensions/cli/src/commands/serve.helpers.ts +0 −2
@@ -119,9 +119,7 @@
119119 model: any;
120120 isProcessing: boolean;
121121 lastActivity: number;
122- messageQueue: string[];
123122 currentAbortController: AbortController | null;
124- shouldInterrupt: boolean;
125123 serverRunning: boolean;
126124 pendingPermission: PendingPermission | null;
127125 systemMessage?: string;
modified extensions/cli/src/commands/serve.ts +15 −21
@@ -17,6 +17,7 @@
1717 ModelServiceState,
1818 } from "../services/types.js";
1919 import { createSession, getSessionPersistenceSnapshot } from "../session.js";
20+import { messageQueue } from "../stream/messageQueue.js";
2021 import { constructSystemMessage } from "../systemMessage.js";
2122 import { telemetryService } from "../telemetry/telemetryService.js";
2223 import { gracefulExit } from "../util/exit.js";
@@ -138,9 +139,7 @@
138139 model,
139140 isProcessing: false,
140141 lastActivity: Date.now(),
141- messageQueue: [],
142142 currentAbortController: null,
143- shouldInterrupt: false,
144143 serverRunning: true,
145144 pendingPermission: null,
146145 };
@@ -185,7 +184,7 @@
185184 res.json({
186185 session: state.session, // Return session directly instead of converting
187186 isProcessing: state.isProcessing,
188- messageQueueLength: state.messageQueue.length,
187+ messageQueueLength: messageQueue.getQueueLength(),
189188 pendingPermission: state.pendingPermission,
190189 });
191190 });
@@ -200,17 +199,11 @@
200199 }
201200
202201 // Queue the message
203- state.messageQueue.push(message);
204-
205- // If currently processing, set interrupt flag
206- if (state.isProcessing && state.currentAbortController) {
207- state.shouldInterrupt = true;
208- }
202+ await messageQueue.enqueueMessage(message);
209203
210204 res.json({
211205 queued: true,
212- position: state.messageQueue.length,
213- willInterrupt: state.shouldInterrupt,
206+ position: messageQueue.getQueueLength(),
214207 });
215208
216209 // Process messages if not already processing
@@ -303,9 +296,6 @@
303296 state.currentAbortController.abort();
304297 }
305298
306- // Clear the message queue
307- state.messageQueue = [];
308-
309299 // Clean up intervals
310300 if (inactivityChecker) {
311301 clearInterval(inactivityChecker);
@@ -325,7 +315,7 @@
325315 setTimeout(handleExitResponse, 100);
326316 });
327317
328- const server = app.listen(port, () => {
318+ const server = app.listen(port, async () => {
329319 console.log(chalk.green(`Server started on http://localhost:${port}`));
330320 console.log(chalk.dim("Endpoints:"));
331321 console.log(chalk.dim(" GET /state - Get current agent state"));
@@ -354,7 +344,7 @@
354344 // If initial prompt provided, queue it for processing
355345 if (actualPrompt) {
356346 console.log(chalk.dim("\nProcessing initial prompt..."));
357- state.messageQueue.push(actualPrompt);
347+ await messageQueue.enqueueMessage(actualPrompt);
358348 processMessages(state, llmApi);
359349 }
360350 });
@@ -383,10 +373,14 @@
383373
384374 async function processMessages(state: ServerState, llmApi: any) {
385375 let processedMessage = false;
386- while (state.messageQueue.length > 0 && state.serverRunning) {
387- const userMessage = state.messageQueue.shift()!;
376+ while (state.serverRunning) {
377+ const queuedMessage = messageQueue.getNextMessage();
378+ if (!queuedMessage) {
379+ break;
380+ }
381+
382+ const userMessage = queuedMessage.message;
388383 state.isProcessing = true;
389- state.shouldInterrupt = false;
390384 state.lastActivity = Date.now();
391385 processedMessage = true;
392386
@@ -410,7 +404,7 @@
410404 state,
411405 llmApi,
412406 state.currentAbortController,
413- () => state.shouldInterrupt,
407+ () => false,
414408 );
415409
416410 // No direct persistence here; ChatHistoryService handles persistence when appropriate
@@ -443,7 +437,7 @@
443437 if (
444438 processedMessage &&
445439 state.serverRunning &&
446- state.messageQueue.length === 0
440+ messageQueue.getQueueLength() === 0
447441 ) {
448442 await storageSyncService.markAgentStatusUnread();
449443 }
modified extensions/cli/src/hubLoader.test.ts +45 −2
@@ -1,12 +1,15 @@
11 import { beforeEach, describe, expect, it, vi } from "vitest";
22
3-import {
3+import * as hubLoader from "./hubLoader.js";
4+
5+const {
46 loadPackageFromHub,
57 mcpProcessor,
68 modelProcessor,
79 promptProcessor,
810 ruleProcessor,
9-} from "./hubLoader.js";
11+ processRule,
12+} = hubLoader;
1013
1114 // Store the original fetch before any mocking
1215 const originalFetch = global.fetch;
@@ -136,6 +139,46 @@
136139 });
137140 });
138141
142+ describe("processRule", () => {
143+ beforeEach(() => {
144+ // Ensure mocks are set up properly for processRule tests
145+ global.fetch = mockFetch;
146+ });
147+
148+ it("should treat multi-line strings as inline rules", async () => {
149+ const loadRuleSpy = vi
150+ .spyOn(hubLoader, "loadRuleFromHub")
151+ .mockResolvedValue("hub-content");
152+
153+ const multilineRule = "Line one\nEnsure /tmp is ignored\nFinal line";
154+ const result = await processRule(multilineRule);
155+
156+ expect(result).toBe(multilineRule);
157+ expect(loadRuleSpy).not.toHaveBeenCalled();
158+
159+ loadRuleSpy.mockRestore();
160+ });
161+
162+ it("should still treat owner/package strings as hub slugs", async () => {
163+ // Mock fetch to return a proper response for this test
164+ const JSZip = (await import("jszip")).default;
165+ const zip = new JSZip();
166+ zip.file("rule.md", "hub-content");
167+ const zipBuffer = await zip.generateAsync({ type: "arraybuffer" });
168+
169+ mockFetch.mockResolvedValueOnce({
170+ ok: true,
171+ arrayBuffer: () => Promise.resolve(zipBuffer),
172+ } as Response);
173+
174+ const slug = "owner/package";
175+ const result = await processRule(slug);
176+
177+ expect(result).toBe("hub-content");
178+ expect(mockFetch).toHaveBeenCalled();
179+ });
180+ });
181+
139182 describe("processors", () => {
140183 it("should define rule processor correctly", () => {
141184 expect(ruleProcessor.type).toBe("rule");
modified extensions/cli/src/hubLoader.ts +35 −18
@@ -3,6 +3,11 @@
33 import { env } from "./env.js";
44 import { logger } from "./util/logger.js";
55
6+/**
7+ * Pattern to match valid hub slugs (owner/package format)
8+ */
9+const HUB_SLUG_PATTERN = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
10+
611 /**
712 * Hub package type definitions
813 */
@@ -220,28 +225,23 @@
220225 * Process a rule specification - supports file paths, hub slugs, or direct content
221226 */
222227 export async function processRule(ruleSpec: string): Promise<string> {
223- // If it looks like a hub slug (contains / but doesn't start with . or /)
224- if (
225- ruleSpec.includes("/") &&
226- !ruleSpec.startsWith(".") &&
227- !ruleSpec.startsWith("/")
228- ) {
229- return await loadRuleFromHub(ruleSpec);
230- }
231-
232- // If it looks like a file path
233- if (
234- ruleSpec.startsWith(".") ||
235- ruleSpec.startsWith("/") ||
236- ruleSpec.includes("/") ||
237- ruleSpec.includes("\\") ||
238- /\.[a-zA-Z]+$/.test(ruleSpec) // Has file extension at the end
239- ) {
228+ const trimmedRuleSpec = ruleSpec.trim();
229+ const hasNewline = /[\r\n]/.test(ruleSpec);
230+
231+ // If it looks like a file path (single line, typical path indicators)
232+ const looksLikePath =
233+ !hasNewline &&
234+ (trimmedRuleSpec.startsWith(".") ||
235+ trimmedRuleSpec.startsWith("/") ||
236+ trimmedRuleSpec.includes("\\") ||
237+ /\.[a-zA-Z]+$/.test(trimmedRuleSpec));
238+
239+ if (looksLikePath) {
240240 const fs = await import("fs");
241241 const path = await import("path");
242242
243243 try {
244- const absolutePath = path.resolve(ruleSpec);
244+ const absolutePath = path.resolve(trimmedRuleSpec);
245245 if (!fs.existsSync(absolutePath)) {
246246 throw new Error(`Rule file not found: ${ruleSpec}`);
247247 }
@@ -253,6 +253,23 @@
253253 }
254254 }
255255
256+ // Check if it might be a hub slug (contains "/" and is a single line)
257+ if (!hasNewline && trimmedRuleSpec.includes("/")) {
258+ const parts = trimmedRuleSpec.split("/");
259+
260+ // If it's exactly 2 parts and matches hub slug pattern, treat as hub slug
261+ if (parts.length === 2 && HUB_SLUG_PATTERN.test(trimmedRuleSpec)) {
262+ return await loadRuleFromHub(trimmedRuleSpec);
263+ }
264+
265+ // If it has more than 2 parts, it's an invalid hub slug
266+ if (parts.length > 2) {
267+ throw new Error(
268+ `Invalid hub slug format. Expected "owner/package", got: ${trimmedRuleSpec}`,
269+ );
270+ }
271+ }
272+
256273 // Otherwise, treat it as direct string content
257274 return ruleSpec;
258275 }
modified extensions/cli/src/stream/messageQueue.test.ts +1 −32
@@ -1,4 +1,4 @@
1-import { beforeEach, describe, expect, it, vi } from "vitest";
1+import { describe, expect, it, vi } from "vitest";
22
33 vi.mock("../util/logger.js", () => ({
44 logger: {
@@ -16,11 +16,6 @@
1616 import { messageQueue } from "./messageQueue.js";
1717
1818 describe("messageQueue", () => {
19- beforeEach(() => {
20- // Drain any leftover items from previous tests
21- while (messageQueue.getAllQueuedMessages()) {}
22- });
23-
2419 it("enqueues and emits messageQueued", async () => {
2520 const event = new Promise<any>((resolve) =>
2621 messageQueue.once("messageQueued", resolve),
@@ -33,30 +28,4 @@
3328 const queued = await event;
3429 expect(queued.message).toBe("hello world");
3530 });
36-
37- it("combines messages, merges image maps, writes history, and clears queue", async () => {
38- const bufA = Buffer.from("A");
39- const bufB = Buffer.from("B");
40-
41- const img1 = new Map<string, Buffer>([["a", bufA]]);
42- const img2 = new Map<string, Buffer>([["b", bufB]]);
43-
44- const history = { addEntry: vi.fn() } as any;
45-
46- await messageQueue.enqueueMessage("one", img1);
47- await messageQueue.enqueueMessage("two", img2, history);
48-
49- const combined = messageQueue.getAllQueuedMessages();
50- expect(combined).toBeTruthy();
51- expect(combined!.message).toBe("one\ntwo");
52- expect(combined!.imageMap).toBeDefined();
53- expect(combined!.imageMap!.get("a")).toEqual(bufA);
54- expect(combined!.imageMap!.get("b")).toEqual(bufB);
55-
56- // queue should be cleared
57- expect(messageQueue.getQueueLength()).toBe(0);
58-
59- // input history should receive the combined message
60- expect(history.addEntry).toHaveBeenCalledWith("one\ntwo");
61- });
6231 });
modified extensions/cli/src/stream/messageQueue.ts +9 −41
@@ -1,12 +1,13 @@
11 import { EventEmitter } from "events";
22
3-import { InputHistory } from "../util/inputHistory.js";
3+import type { InputHistory } from "../util/inputHistory.js";
44 import { logger } from "../util/logger.js";
55
66 export interface QueuedMessage {
77 message: string;
88 imageMap?: Map<string, Buffer>;
99 timestamp: number;
10+ history?: InputHistory;
1011 }
1112
1213 export interface MessageProcessor {
@@ -18,7 +19,6 @@
1819 */
1920 class MessageQueue extends EventEmitter {
2021 private queue: QueuedMessage[] = [];
21- private inputHistory: InputHistory | undefined;
2222
2323 constructor() {
2424 super();
@@ -27,14 +27,13 @@
2727 async enqueueMessage(
2828 message: string,
2929 imageMap?: Map<string, Buffer>,
30- inputHistory?: InputHistory,
30+ history?: InputHistory,
3131 ): Promise<boolean> {
32- this.inputHistory = inputHistory;
33-
3432 const queuedMessage: QueuedMessage = {
3533 message,
3634 imageMap,
3735 timestamp: Date.now(),
36+ history,
3837 };
3938
4039 this.queue.push(queuedMessage);
@@ -48,42 +47,11 @@
4847 return true;
4948 }
5049
51- public getAllQueuedMessages() {
52- if (this.queue.length === 0) return undefined;
53-
54- // Combine all queued messages into one
55- const combinedMessage = this.queue.map((msg) => msg.message).join("\n");
56- const combinedImageMap = new Map<string, Buffer>();
57-
58- // Merge all image maps
59- for (const queuedMsg of this.queue) {
60- if (queuedMsg.imageMap) {
61- for (const [key, value] of queuedMsg.imageMap) {
62- combinedImageMap.set(key, value);
63- }
64- }
65- }
66-
67- const result = {
68- message: combinedMessage,
69- imageMap: combinedImageMap.size > 0 ? combinedImageMap : undefined,
70- timestamp: Date.now(),
71- };
72-
73- // Add to input history and clear the queue
74- this.inputHistory?.addEntry(combinedMessage);
75- this.queue = [];
76-
77- logger.debug("MessageQueue: All messages dequeued and combined", {
78- combinedLength: combinedMessage.length,
79- queueLength: this.queue.length,
80- });
81-
82- return result;
83- }
84-
85- public getLatestMessage() {
86- return this.getAllQueuedMessages();
50+ /**
51+ * Dequeues and returns the next message to be processed (FIFO - oldest first)
52+ */
53+ public getNextMessage(): QueuedMessage | undefined {
54+ return this.queue.shift();
8755 }
8856
8957 getQueueLength(): number {
modified extensions/cli/src/ui/UserInput.tsx +5 −7
@@ -548,16 +548,14 @@
548548 textBuffer.expandAllPasteBlocks();
549549 const submittedText = textBuffer.text.trim();
550550
551- if (isWaitingForResponse || isCompacting) {
551+ inputHistory.addEntry(submittedText);
552+
553+ // We don't queue, we just send in remote mode because the server handles queueing
554+ if (!isRemoteMode && (isWaitingForResponse || isCompacting)) {
552555 // Process message later when LLM has responded or compaction is complete
553- void messageQueue.enqueueMessage(
554- submittedText,
555- imageMap,
556- inputHistory,
557- );
556+ void messageQueue.enqueueMessage(submittedText, imageMap);
558557 } else {
559558 // Submit with images
560- inputHistory.addEntry(submittedText);
561559 onSubmit(submittedText, imageMap);
562560 }
563561
modified extensions/cli/src/ui/hooks/useChat.ts +2 −2
@@ -337,13 +337,13 @@
337337
338338 // Check if there are queued messages and process them after a microtask delay
339339 // This ensures the GUI state has been updated before processing the next message
340- const queuedMessageData = messageQueue.getLatestMessage();
340+ const queuedMessageData = messageQueue.getNextMessage();
341341 if (queuedMessageData) {
342342 const { message: latestQueuedMessage, imageMap } = queuedMessageData;
343343 logger.debug("processing queued message", { latestQueuedMessage });
344344
345345 // Clear queued messages from display since they're about to be processed
346- // Note: messageQueue.getLatestMessage() already cleared the actual queue
346+ // Note: messageQueue.getNextMessage() already cleared the actual queue
347347 setQueuedMessages([]);
348348
349349 await new Promise((resolve) => setTimeout(resolve, 100)); // add timeout for react to render the tui