Prevents race conditions in timed prompts

Adds a flag to prevent the timed prompt execution from running concurrently, avoiding potential race conditions and unexpected behavior.

Also, addresses edge case in the status check where the displayed current prompt number could be inaccurate.
This commit is contained in:
AlexKucera committed 2025-09-26 08:18:13 +02:00
1 parent 847768417c
commit 9249897d27
1 file changed
+15 -2
+15 -2
View File
@@ -9,15 +9,22 @@ export class TimedPromptsCommand {
private activeInterval: number | null = null; private activeInterval: number | null = null;
private promptQueue: string[] = []; private promptQueue: string[] = [];
private currentIndex = 0; private currentIndex = 0;
private inProgress = false;
constructor(private promptGenerator: PromptGeneratorService) {} constructor(private promptGenerator: PromptGeneratorService) {}
// MARK: - Public Methods // MARK: - Public Methods
async execute(settings: FreewritingPromptsSettings): Promise<void> { async execute(settings: FreewritingPromptsSettings): Promise<void> {
// Check if already in progress to prevent race conditions
if (this.inProgress) {
return;
}
// Stop any existing timed sequence // Stop any existing timed sequence
this.stop(); this.stop();
this.inProgress = true;
try { try {
// Generate prompts // Generate prompts
const prompts = await this.promptGenerator.generateTimedPrompts(settings); const prompts = await this.promptGenerator.generateTimedPrompts(settings);
@@ -42,6 +49,8 @@ export class TimedPromptsCommand {
} catch (error) { } catch (error) {
console.error('Error executing timed prompts command:', error); console.error('Error executing timed prompts command:', error);
// Error handling is done in the service layer // Error handling is done in the service layer
} finally {
this.inProgress = false;
} }
} }
@@ -52,6 +61,7 @@ export class TimedPromptsCommand {
} }
this.promptQueue = []; this.promptQueue = [];
this.currentIndex = 0; this.currentIndex = 0;
this.inProgress = false;
} }
isRunning(): boolean { isRunning(): boolean {
@@ -100,10 +110,13 @@ export class TimedPromptsCommand {
// MARK: - Status Methods // MARK: - Status Methods
getStatus(): { isRunning: boolean; currentPrompt: number; totalPrompts: number } { getStatus(): { isRunning: boolean; currentPrompt: number; totalPrompts: number } {
const totalPrompts = this.promptQueue.length;
const currentPrompt = totalPrompts === 0 ? 0 : Math.min(this.currentIndex + 1, totalPrompts);
return { return {
isRunning: this.isRunning(), isRunning: this.isRunning(),
currentPrompt: this.currentIndex + 1, currentPrompt,
totalPrompts: this.promptQueue.length totalPrompts
}; };
} }