Class: Clacky::Tools::RunProject

Inherits:
Base
  • Object
show all
Defined in:
lib/clacky/tools/run_project.rb

Constant Summary collapse

CONFIG_PATHS =
['.1024', '.clackyai/.environments.yaml'].freeze
@@process_state =
nil
@@reader_thread =
nil

Instance Method Summary collapse

Methods inherited from Base

#category, #description, #name, #parameters, #to_function_definition

Constructor Details

#initializeRunProject

Returns a new instance of RunProject.



36
37
38
# File 'lib/clacky/tools/run_project.rb', line 36

def initialize
  super
end

Instance Method Details

#execute(action:, max_lines: 100, working_dir: nil) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/clacky/tools/run_project.rb', line 40

def execute(action:, max_lines: 100, working_dir: nil)
  @working_dir = working_dir if working_dir
  case action
  when "start"
    start_project
  when "stop"
    stop_project
  when "status"
    get_status
  when "output"
    get_output(max_lines)
  else
    { error: "Unknown action: #{action}" }
  end
end

#format_call(args) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/clacky/tools/run_project.rb', line 56

def format_call(args)
  action = args[:action] || args['action']

  case action
  when 'start'
    config = load_project_config
    if config && (cmd = config['run_command'] || config['run_commands'])
      cmd = cmd.join(' && ') if cmd.is_a?(Array)
      cmd_preview = cmd.length > 40 ? "#{cmd[0..40]}..." : cmd
      "RunProject(start: #{cmd_preview})"
    else
      "RunProject(start)"
    end
  when 'output'
    max_lines = args[:max_lines] || args['max_lines'] || 100
    "RunProject(output: #{max_lines} lines)"
  else
    "RunProject(#{action})"
  end
end

#format_result(result) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/clacky/tools/run_project.rb', line 77

def format_result(result)
  if result[:error]
    "[Error] #{result[:error]}"
  elsif result[:status]
    case result[:status]
    when 'started'
      cmd_preview = result[:command] ? result[:command][0..50] : ''
      output_preview = result[:output]&.lines&.first(2)&.join&.strip
      msg = "[OK] Started (PID: #{result[:pid]}, cmd: #{cmd_preview})"
      msg += "\n  #{output_preview}" if output_preview && !output_preview.empty?
      msg
    when 'stopped'
      "[OK] Stopped"
    when 'running'
      uptime = result[:uptime] ? "#{result[:uptime].round(1)}s" : "unknown"
      "[Running] #{uptime}, PID: #{result[:pid]}"
    when 'not_running'
      "[Not Running]"
    else
      result[:status].to_s
    end
  else
    "Done"
  end
end

#get_output(max_lines) ⇒ Object



199
200
201
202
203
204
205
206
207
208
209
210
# File 'lib/clacky/tools/run_project.rb', line 199

def get_output(max_lines)
  return { error: 'No running process' } unless @@process_state

  output = read_buffered_output(max_lines: max_lines)

  {
    status: 'running',
    pid: @@process_state[:thread].pid,
    uptime: Time.now - @@process_state[:start_time],
    output: output
  }
end

#get_statusObject



186
187
188
189
190
191
192
193
194
195
196
197
# File 'lib/clacky/tools/run_project.rb', line 186

def get_status
  if @@process_state && @@process_state[:thread].alive?
    {
      status: 'running',
      pid: @@process_state[:thread].pid,
      uptime: Time.now - @@process_state[:start_time],
      command: @@process_state[:command]
    }
  else
    { status: 'not_running' }
  end
end

#load_project_configObject



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/clacky/tools/run_project.rb', line 230

def load_project_config
  base = @working_dir || Dir.pwd
  CONFIG_PATHS.each do |path|
    full_path = File.join(base, path)
    next unless File.exist?(full_path)

    begin
      content = File.read(full_path)
      return YAML.safe_load(content)
    rescue StandardError => e
      next
    end
  end

  nil
end

#read_buffered_output(max_lines:) ⇒ Object



283
284
285
286
287
288
289
290
291
292
# File 'lib/clacky/tools/run_project.rb', line 283

def read_buffered_output(max_lines:)
  return "" unless @@process_state

  stdout_lines = @@process_state[:stdout_buffer].to_a
  stderr_lines = @@process_state[:stderr_buffer].to_a

  # Combine and get last N lines
  all_lines = (stdout_lines + stderr_lines).last(max_lines)
  all_lines.join
end

#start_output_reader_threadObject



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
# File 'lib/clacky/tools/run_project.rb', line 247

def start_output_reader_thread
  @@reader_thread = Thread.new do
    loop do
      break unless @@process_state

      stdout = @@process_state[:stdout]
      stderr = @@process_state[:stderr]
      stdout_buf = @@process_state[:stdout_buffer]
      stderr_buf = @@process_state[:stderr_buffer]

      begin
        ready = IO.select([stdout, stderr], nil, nil, 0.5)
        if ready
          ready[0].each do |io|
            begin
              data = io.read_nonblock(4096)
              # Convert binary shell output to valid UTF-8, preserving multibyte chars
              data = Clacky::Utils::Encoding.to_utf8(data)
              
              if io == stdout
                stdout_buf.push_lines(data)
              else
                stderr_buf.push_lines(data)
              end
            rescue IO::WaitReadable, EOFError
            end
          end
        end
      rescue StandardError => e
      end

      sleep 0.1
    end
  end
end

#start_projectObject



104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/clacky/tools/run_project.rb', line 104

def start_project
  config = load_project_config
  return { error: "No .1024 config file found. Create .1024 with 'run_command: your_command'" } unless config

  command = config['run_command'] || config['run_commands']
  return { error: "No 'run_command' defined in .1024" } unless command

  command = command.join(' && ') if command.is_a?(Array)

  stop_existing_process if @@process_state

  begin
    # close_others: true prevents inheriting the server's listening socket (port 7070)
    # when run_project is called from openclacky server. Without this, the spawned
    # project server may inherit and hold the fd, causing port conflicts.
    stdin, stdout, stderr, wait_thr = Open3.popen3(command, close_others: true)

    @@process_state = {
      stdin: stdin,
      stdout: stdout,
      stderr: stderr,
      thread: wait_thr,
      start_time: Time.now,
      command: command,
      stdout_buffer: Utils::LimitStack.new(max_size: 5000),
      stderr_buffer: Utils::LimitStack.new(max_size: 5000)
    }

    start_output_reader_thread

    sleep 2

    output = read_buffered_output(max_lines: 50)

    {
      status: 'started',
      pid: wait_thr.pid,
      command: command,
      output: output,
      message: "Project started in background. Use run_project(action: 'output') to check logs."
    }
  rescue StandardError => e
    @@process_state = nil
    {
      error: "Failed to start project: #{e.message}",
      command: command
    }
  end
end

#stop_existing_processObject



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/clacky/tools/run_project.rb', line 212

def stop_existing_process
  return unless @@process_state

  thread = @@process_state[:thread]
  if thread.alive?
    Process.kill('INT', thread.pid) rescue nil
    sleep 1

    if thread.alive?
      Process.kill('KILL', thread.pid) rescue nil
    end
  end

  @@reader_thread&.kill
  @@process_state = nil
  @@reader_thread = nil
end

#stop_projectObject



154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
# File 'lib/clacky/tools/run_project.rb', line 154

def stop_project
  return { status: 'not_running', message: 'No running process to stop' } unless @@process_state

  thread = @@process_state[:thread]
  pid = thread.pid

  begin
    if thread.alive?
      Process.kill('INT', pid)
      sleep 1

      if thread.alive?
        Process.kill('KILL', pid) rescue nil
      end
    end

    @@reader_thread&.kill

    @@process_state = nil
    @@reader_thread = nil

    {
      status: 'stopped',
      message: "Process #{pid} stopped successfully"
    }
  rescue StandardError => e
    {
      error: "Failed to stop process: #{e.message}"
    }
  end
end