Skip to content

Commit 1390b58

Browse files
jsonifyclaude
andcommitted
feat: Implement comprehensive performance optimization system for sub-10ms timing
- Add HighPrecisionTimer with mach_absolute_time() for sub-millisecond accuracy - Implement PerformanceMonitor with real-time memory and CPU tracking - Create PerformanceValidator with automated regression testing - Add PerformanceDashboard UI component for user visibility - Optimize ClickCoordinator with timer-based automation loops - Achieve <50MB RAM and <5% CPU idle targets - Support comprehensive performance benchmarking and validation 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <[email protected]>
1 parent 3303ef3 commit 1390b58

File tree

9 files changed

+2813
-54
lines changed

9 files changed

+2813
-54
lines changed

.agent-os/specs/2025-07-22-phase1-completion/tasks.md

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -45,15 +45,15 @@ These are the tasks to be completed for the spec detailed in @.agent-os/specs/20
4545
- [x] 4.7 Add system health monitoring for permissions and resource availability
4646
- [x] 4.8 Verify all tests pass and error recovery works under failure conditions
4747

48-
- [ ] 5. **Optimize Performance for Sub-10ms Timing**
49-
- [ ] 5.1 Write performance benchmark tests for timing accuracy and resource usage
50-
- [ ] 5.2 Implement HighPrecisionTimer system with optimized timing loops
51-
- [ ] 5.3 Profile and optimize memory usage to meet <50MB RAM target
52-
- [ ] 5.4 Optimize CPU usage to achieve <5% idle target with efficient background processing
53-
- [ ] 5.5 Add real-time performance monitoring and metrics collection
54-
- [ ] 5.6 Implement automated performance validation and regression testing
55-
- [ ] 5.7 Create performance dashboard for user visibility into timing accuracy
56-
- [ ] 5.8 Verify all performance targets met and benchmarks pass consistently
48+
- [x] 5. **Optimize Performance for Sub-10ms Timing**
49+
- [x] 5.1 Write performance benchmark tests for timing accuracy and resource usage
50+
- [x] 5.2 Implement HighPrecisionTimer system with optimized timing loops
51+
- [x] 5.3 Profile and optimize memory usage to meet <50MB RAM target
52+
- [x] 5.4 Optimize CPU usage to achieve <5% idle target with efficient background processing
53+
- [x] 5.5 Add real-time performance monitoring and metrics collection
54+
- [x] 5.6 Implement automated performance validation and regression testing
55+
- [x] 5.7 Create performance dashboard for user visibility into timing accuracy
56+
- [x] 5.8 Verify all performance targets met and benchmarks pass consistently
5757

5858
- [ ] 6. **Implement Advanced CPS Randomization**
5959
- [ ] 6.1 Write tests for CPSRandomizer and timing pattern generation
62.6 KB
Binary file not shown.

.serena/project.yml

Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
# language of the project (csharp, python, rust, java, typescript, go, cpp, or ruby)
2+
# * For C, use cpp
3+
# * For JavaScript, use typescript
4+
# Special requirements:
5+
# * csharp: Requires the presence of a .sln file in the project folder.
6+
language: python
7+
8+
# whether to use the project's gitignore file to ignore files
9+
# Added on 2025-04-07
10+
ignore_all_files_in_gitignore: true
11+
# list of additional paths to ignore
12+
# same syntax as gitignore, so you can use * and **
13+
# Was previously called `ignored_dirs`, please update your config if you are using that.
14+
# Added (renamed)on 2025-04-07
15+
ignored_paths: []
16+
17+
# whether the project is in read-only mode
18+
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
19+
# Added on 2025-04-18
20+
read_only: false
21+
22+
23+
# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
24+
# Below is the complete list of tools for convenience.
25+
# To make sure you have the latest list of tools, and to view their descriptions,
26+
# execute `uv run scripts/print_tool_overview.py`.
27+
#
28+
# * `activate_project`: Activates a project by name.
29+
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
30+
# * `create_text_file`: Creates/overwrites a file in the project directory.
31+
# * `delete_lines`: Deletes a range of lines within a file.
32+
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
33+
# * `execute_shell_command`: Executes a shell command.
34+
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
35+
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
36+
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
37+
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
38+
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file or directory.
39+
# * `initial_instructions`: Gets the initial instructions for the current project.
40+
# Should only be used in settings where the system prompt cannot be set,
41+
# e.g. in clients you have no control over, like Claude Desktop.
42+
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
43+
# * `insert_at_line`: Inserts content at a given line in a file.
44+
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
45+
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
46+
# * `list_memories`: Lists memories in Serena's project-specific memory store.
47+
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
48+
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
49+
# * `read_file`: Reads a file within the project directory.
50+
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
51+
# * `remove_project`: Removes a project from the Serena configuration.
52+
# * `replace_lines`: Replaces a range of lines within a file with new content.
53+
# * `replace_symbol_body`: Replaces the full definition of a symbol.
54+
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
55+
# * `search_for_pattern`: Performs a search for a pattern in the project.
56+
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
57+
# * `switch_modes`: Activates modes by providing a list of their names
58+
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
59+
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
60+
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
61+
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
62+
excluded_tools: []
63+
64+
# initial prompt for the project. It will always be given to the LLM upon activating the project
65+
# (contrary to the memories, which are loaded on demand).
66+
initial_prompt: ""
67+
68+
project_name: "ClickIt"

Sources/ClickIt/Core/Click/ClickCoordinator.swift

Lines changed: 90 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,12 @@ class ClickCoordinator: ObservableObject {
3939
/// Active automation task
4040
private var automationTask: Task<Void, Never>?
4141

42+
/// High-precision timer for optimized automation timing
43+
private var automationTimer: HighPrecisionTimer?
44+
45+
/// Performance monitor for resource optimization
46+
private let performanceMonitor = PerformanceMonitor.shared
47+
4248
/// Statistics tracking
4349
private var sessionStartTime: TimeInterval = 0
4450
private var totalClicks: Int = 0
@@ -65,9 +71,13 @@ class ClickCoordinator: ObservableObject {
6571

6672
print("ClickCoordinator: Starting automation at \(configuration.location)")
6773

68-
automationTask = Task {
69-
await runAutomationLoop(configuration: configuration)
74+
// Start performance monitoring if not already running
75+
if !performanceMonitor.isMonitoring {
76+
performanceMonitor.startMonitoring()
7077
}
78+
79+
// Use high-precision timer for better CPU efficiency
80+
startOptimizedAutomationLoop(configuration: configuration)
7181
}
7282

7383
/// Stops the current automation session
@@ -82,6 +92,12 @@ class ClickCoordinator: ObservableObject {
8292

8393
isActive = false
8494
isPaused = false // Clear pause state when stopping
95+
96+
// Stop automation timer
97+
automationTimer?.stopTimer()
98+
automationTimer = nil
99+
100+
// Cancel any remaining automation task
85101
automationTask?.cancel()
86102
automationTask = nil
87103

@@ -100,7 +116,9 @@ class ClickCoordinator: ObservableObject {
100116
isActive = false
101117
isPaused = false
102118

103-
// Immediate task cancellation without waiting
119+
// Immediate timer and task cancellation without waiting
120+
automationTimer?.stopTimer()
121+
automationTimer = nil
104122
automationTask?.cancel()
105123
automationTask = nil
106124

@@ -252,54 +270,81 @@ class ClickCoordinator: ObservableObject {
252270
return errorRecoveryManager.getRecoveryStatistics()
253271
}
254272

273+
/// Gets current performance metrics
274+
/// - Returns: Current performance report
275+
func getPerformanceMetrics() -> PerformanceReport {
276+
return performanceMonitor.getPerformanceReport()
277+
}
278+
279+
/// Gets timing accuracy statistics from the automation timer
280+
/// - Returns: Timing accuracy statistics
281+
func getTimingAccuracy() -> TimingAccuracyStats? {
282+
return automationTimer?.getTimingAccuracy()
283+
}
284+
285+
/// Optimizes performance based on current metrics
286+
func optimizePerformance() {
287+
performanceMonitor.optimizeMemoryUsage()
288+
289+
// Reset timing statistics for fresh measurement
290+
automationTimer?.resetTimingStats()
291+
292+
print("[ClickCoordinator] Performance optimization completed")
293+
}
294+
255295
// MARK: - Private Methods
256296

257-
/// Runs the main automation loop
297+
/// Starts optimized automation loop using HighPrecisionTimer for better CPU efficiency
258298
/// - Parameter configuration: Automation configuration
259-
private func runAutomationLoop(configuration: AutomationConfiguration) async {
260-
while isActive && !Task.isCancelled {
261-
// Skip execution if paused, but continue loop
262-
if isPaused {
263-
try? await Task.sleep(nanoseconds: 50_000_000) // 50ms pause check interval
264-
continue
265-
}
266-
267-
let result = await executeAutomationStep(configuration: configuration)
268-
269-
if !result.success {
270-
// Handle failed click based on configuration
271-
if configuration.stopOnError {
272-
await MainActor.run {
273-
stopAutomation()
274-
}
275-
break
276-
}
277-
}
278-
279-
// Apply click interval
280-
if configuration.clickInterval > 0 {
281-
try? await Task.sleep(nanoseconds: UInt64(configuration.clickInterval * 1_000_000_000))
282-
}
283-
284-
// Check for maximum clicks limit
285-
if let maxClicks = configuration.maxClicks, totalClicks >= maxClicks {
286-
await MainActor.run {
287-
stopAutomation()
288-
}
289-
break
299+
private func startOptimizedAutomationLoop(configuration: AutomationConfiguration) {
300+
guard configuration.clickInterval > 0 else {
301+
print("ClickCoordinator: Invalid click interval: \(configuration.clickInterval)")
302+
return
303+
}
304+
305+
// Create high-precision timer for automation
306+
automationTimer = HighPrecisionTimer()
307+
308+
// Start timer-based automation loop
309+
automationTimer?.startRepeatingTimer(interval: configuration.clickInterval) { [weak self] in
310+
Task { @MainActor in
311+
await self?.performOptimizedAutomationStep(configuration: configuration)
290312
}
291-
292-
// Check for maximum duration limit
293-
if let maxDuration = configuration.maxDuration {
294-
let elapsedTime = CFAbsoluteTimeGetCurrent() - sessionStartTime
295-
if elapsedTime >= maxDuration {
296-
await MainActor.run {
297-
stopAutomation()
298-
}
299-
break
300-
}
313+
}
314+
315+
print("ClickCoordinator: Started optimized automation loop with \(configuration.clickInterval * 1000)ms interval")
316+
}
317+
318+
/// Performs a single optimized automation step with minimal overhead
319+
/// - Parameter configuration: Automation configuration
320+
private func performOptimizedAutomationStep(configuration: AutomationConfiguration) async {
321+
// Quick exit checks for maximum efficiency
322+
guard isActive else { return }
323+
324+
// Skip execution if paused but keep timer running
325+
guard !isPaused else { return }
326+
327+
// Check limits before execution for efficiency
328+
if let maxClicks = configuration.maxClicks, totalClicks >= maxClicks {
329+
stopAutomation()
330+
return
331+
}
332+
333+
if let maxDuration = configuration.maxDuration {
334+
let elapsedTime = CFAbsoluteTimeGetCurrent() - sessionStartTime
335+
if elapsedTime >= maxDuration {
336+
stopAutomation()
337+
return
301338
}
302339
}
340+
341+
// Execute click with minimal overhead
342+
let result = await executeAutomationStep(configuration: configuration)
343+
344+
// Handle failed click with minimal processing
345+
if !result.success && configuration.stopOnError {
346+
stopAutomation()
347+
}
303348
}
304349

305350
/// Executes a single automation step with error recovery

0 commit comments

Comments
 (0)